diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/RN50-quickgelu.json b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/RN50-quickgelu.json new file mode 100644 index 0000000000000000000000000000000000000000..8c2f91260cdeb043434dc1e893cce81d4ce7f0d1 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/RN50-quickgelu.json @@ -0,0 +1,22 @@ +{ + "embed_dim": 1024, + "quick_gelu": true, + "vision_cfg": { + "image_size": 224, + "layers": [ + 3, + 4, + 6, + 3 + ], + "width": 64, + "patch_size": null + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 512, + "heads": 8, + "layers": 12 + } +} diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/RN50.json b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/RN50.json new file mode 100644 index 0000000000000000000000000000000000000000..33aa884d54fee0076c33676831e49d5e1ffcb8f2 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/RN50.json @@ -0,0 +1,21 @@ +{ + "embed_dim": 1024, + "vision_cfg": { + "image_size": 224, + "layers": [ + 3, + 4, + 6, + 3 + ], + "width": 64, + "patch_size": null + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 512, + "heads": 8, + "layers": 12 + } +} \ No newline at end of file diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/RN50x16.json b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/RN50x16.json new file mode 100644 index 0000000000000000000000000000000000000000..3161e1a2c9a839161e652a4d729c2cdc971161db --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/RN50x16.json @@ -0,0 +1,21 @@ +{ + "embed_dim": 768, + "vision_cfg": { + "image_size": 384, + "layers": [ + 6, + 8, + 18, + 8 + ], + "width": 96, + "patch_size": null + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 768, + "heads": 12, + "layers": 12 + } +} \ No newline at end of file diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/RN50x4.json b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/RN50x4.json new file mode 100644 index 0000000000000000000000000000000000000000..e155237f8ce1026aaaeecc80751eabe6f329f0bb --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/RN50x4.json @@ -0,0 +1,21 @@ +{ + "embed_dim": 640, + "vision_cfg": { + "image_size": 288, + "layers": [ + 4, + 6, + 10, + 6 + ], + "width": 80, + "patch_size": null + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 640, + "heads": 10, + "layers": 12 + } +} \ No newline at end of file diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/RN50x64.json b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/RN50x64.json new file mode 100644 index 0000000000000000000000000000000000000000..f5aaa2ee3de21ddb03cbd12766a3419bf34898c7 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/RN50x64.json @@ -0,0 +1,21 @@ +{ + "embed_dim": 1024, + "vision_cfg": { + "image_size": 448, + "layers": [ + 3, + 15, + 36, + 10 + ], + "width": 128, + "patch_size": null + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 1024, + "heads": 16, + "layers": 12 + } +} \ No newline at end of file diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/ViT-B-16-plus-240.json b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/ViT-B-16-plus-240.json new file mode 100644 index 0000000000000000000000000000000000000000..5bbd12bcd01f64d6d0a0aa8316b129327a0d169a --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/ViT-B-16-plus-240.json @@ -0,0 +1,16 @@ +{ + "embed_dim": 640, + "vision_cfg": { + "image_size": 240, + "layers": 12, + "width": 896, + "patch_size": 16 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 640, + "heads": 10, + "layers": 12 + } +} \ No newline at end of file diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/ViT-B-16-plus.json b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/ViT-B-16-plus.json new file mode 100644 index 0000000000000000000000000000000000000000..5dc1e09baccef2b15055c1bffeb9903e760101c6 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/ViT-B-16-plus.json @@ -0,0 +1,16 @@ +{ + "embed_dim": 640, + "vision_cfg": { + "image_size": 224, + "layers": 12, + "width": 896, + "patch_size": 16 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 640, + "heads": 10, + "layers": 12 + } +} \ No newline at end of file diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/ViT-B-16.json b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/ViT-B-16.json new file mode 100644 index 0000000000000000000000000000000000000000..395eea77ec3907c0611531aba63459b193e67b9c --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/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 + } +} \ No newline at end of file diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/ViT-B-32-plus-256.json b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/ViT-B-32-plus-256.json new file mode 100644 index 0000000000000000000000000000000000000000..2f09c857de9a4c01ae51297a7e2451984879f9de --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/ViT-B-32-plus-256.json @@ -0,0 +1,16 @@ +{ + "embed_dim": 640, + "vision_cfg": { + "image_size": 256, + "layers": 12, + "width": 896, + "patch_size": 32 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 640, + "heads": 10, + "layers": 12 + } +} \ No newline at end of file diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/ViT-B-32-quickgelu.json b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/ViT-B-32-quickgelu.json new file mode 100644 index 0000000000000000000000000000000000000000..ce6bd923593293ed50dfcfb28b73ca7403bcf3c5 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/ViT-B-32-quickgelu.json @@ -0,0 +1,17 @@ +{ + "embed_dim": 512, + "quick_gelu": true, + "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/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/ViT-B-32.json b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/ViT-B-32.json new file mode 100644 index 0000000000000000000000000000000000000000..07c8e28eb06fa1813ba932fe4eec668262d1c47f --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/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/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/ViT-H-14.json b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/ViT-H-14.json new file mode 100644 index 0000000000000000000000000000000000000000..3e3a7e934e7f02e41f4829996c4950e05f015a74 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/ViT-H-14.json @@ -0,0 +1,17 @@ +{ + "embed_dim": 1024, + "vision_cfg": { + "image_size": 224, + "layers": 32, + "width": 1280, + "head_width": 80, + "patch_size": 14 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 1024, + "heads": 16, + "layers": 24 + } +} \ No newline at end of file diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/ViT-H-16.json b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/ViT-H-16.json new file mode 100644 index 0000000000000000000000000000000000000000..588485455fdf8193ec16474450b94e31c91ea93c --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/ViT-H-16.json @@ -0,0 +1,17 @@ +{ + "embed_dim": 1024, + "vision_cfg": { + "image_size": 224, + "layers": 32, + "width": 1280, + "head_width": 80, + "patch_size": 16 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 1024, + "heads": 16, + "layers": 24 + } +} \ No newline at end of file diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/ViT-L-14-280.json b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/ViT-L-14-280.json new file mode 100644 index 0000000000000000000000000000000000000000..2262deaefa82792d35d73c0d7c8e620525092581 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/ViT-L-14-280.json @@ -0,0 +1,16 @@ +{ + "embed_dim": 768, + "vision_cfg": { + "image_size": 280, + "layers": 24, + "width": 1024, + "patch_size": 14 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 768, + "heads": 12, + "layers": 12 + } +} \ No newline at end of file diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/ViT-L-14-336.json b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/ViT-L-14-336.json new file mode 100644 index 0000000000000000000000000000000000000000..8d1f74c2639c3a3705df9865b9c08215675ddc97 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/ViT-L-14-336.json @@ -0,0 +1,16 @@ +{ + "embed_dim": 768, + "vision_cfg": { + "image_size": 336, + "layers": 24, + "width": 1024, + "patch_size": 14 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 768, + "heads": 12, + "layers": 12 + } +} \ No newline at end of file diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/ViT-L-14.json b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/ViT-L-14.json new file mode 100644 index 0000000000000000000000000000000000000000..d4a4bbb1dd4ed4edb317d3ace4f3ad13b211c241 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/ViT-L-14.json @@ -0,0 +1,16 @@ +{ + "embed_dim": 768, + "vision_cfg": { + "image_size": 224, + "layers": 24, + "width": 1024, + "patch_size": 14 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 768, + "heads": 12, + "layers": 12 + } +} \ No newline at end of file diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/ViT-L-16-320.json b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/ViT-L-16-320.json new file mode 100644 index 0000000000000000000000000000000000000000..fc2d13ca9ec7f0b56a886ddaf66c4a7ba7a442ba --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/ViT-L-16-320.json @@ -0,0 +1,16 @@ +{ + "embed_dim": 768, + "vision_cfg": { + "image_size": 320, + "layers": 24, + "width": 1024, + "patch_size": 16 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 768, + "heads": 12, + "layers": 12 + } +} \ No newline at end of file diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/ViT-L-16.json b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/ViT-L-16.json new file mode 100644 index 0000000000000000000000000000000000000000..82a1cedfa290adacbbdc02bc5d589734c22d41d3 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/ViT-L-16.json @@ -0,0 +1,16 @@ +{ + "embed_dim": 768, + "vision_cfg": { + "image_size": 224, + "layers": 24, + "width": 1024, + "patch_size": 16 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 768, + "heads": 12, + "layers": 12 + } +} \ No newline at end of file diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/ViT-M-16-alt.json b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/ViT-M-16-alt.json new file mode 100644 index 0000000000000000000000000000000000000000..1a317aad8e02d9c26d2decc7cc49a18dfdf9e0d8 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/ViT-M-16-alt.json @@ -0,0 +1,17 @@ +{ + "embed_dim": 384, + "vision_cfg": { + "image_size": 224, + "layers": 12, + "width": 512, + "patch_size": 16, + "ls_init_value": 1e-4 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 384, + "heads": 6, + "layers": 12 + } +} \ No newline at end of file diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/ViT-M-16.json b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/ViT-M-16.json new file mode 100644 index 0000000000000000000000000000000000000000..f2f3225a46e09237730a151d161f70c86b985172 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/ViT-M-16.json @@ -0,0 +1,16 @@ +{ + "embed_dim": 512, + "vision_cfg": { + "image_size": 224, + "layers": 12, + "width": 512, + "patch_size": 16 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 512, + "heads": 8, + "layers": 12 + } +} \ No newline at end of file diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/ViT-M-32-alt.json b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/ViT-M-32-alt.json new file mode 100644 index 0000000000000000000000000000000000000000..fd222aeac0f582ef6a1a33f1b3fec70a5b386ac0 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/ViT-M-32-alt.json @@ -0,0 +1,16 @@ +{ + "embed_dim": 384, + "vision_cfg": { + "image_size": 224, + "layers": 12, + "width": 512, + "patch_size": 32 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 384, + "heads": 6, + "layers": 12 + } +} \ No newline at end of file diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/ViT-M-32.json b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/ViT-M-32.json new file mode 100644 index 0000000000000000000000000000000000000000..4f718642821035d9776d1e006817d65ede074366 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/ViT-M-32.json @@ -0,0 +1,16 @@ +{ + "embed_dim": 512, + "vision_cfg": { + "image_size": 224, + "layers": 12, + "width": 512, + "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/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/ViT-S-16-alt.json b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/ViT-S-16-alt.json new file mode 100644 index 0000000000000000000000000000000000000000..a8c056555e4da3ba0d1475a61fc316362ecce76f --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/ViT-S-16-alt.json @@ -0,0 +1,16 @@ +{ + "embed_dim": 256, + "vision_cfg": { + "image_size": 224, + "layers": 12, + "width": 384, + "patch_size": 16 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 256, + "heads": 4, + "layers": 10 + } +} \ No newline at end of file diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/ViT-S-16.json b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/ViT-S-16.json new file mode 100644 index 0000000000000000000000000000000000000000..1d8504e59658803f3093e5b05de45f30a09b8185 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/ViT-S-16.json @@ -0,0 +1,16 @@ +{ + "embed_dim": 384, + "vision_cfg": { + "image_size": 224, + "layers": 12, + "width": 384, + "patch_size": 16 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 384, + "heads": 6, + "layers": 12 + } +} \ No newline at end of file diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/ViT-S-32-alt.json b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/ViT-S-32-alt.json new file mode 100644 index 0000000000000000000000000000000000000000..e1dfdec9824df09a2010e991ccfa1d9ee2f45807 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/ViT-S-32-alt.json @@ -0,0 +1,16 @@ +{ + "embed_dim": 256, + "vision_cfg": { + "image_size": 224, + "layers": 12, + "width": 384, + "patch_size": 32 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 256, + "heads": 4, + "layers": 10 + } +} \ No newline at end of file diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/ViT-S-32.json b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/ViT-S-32.json new file mode 100644 index 0000000000000000000000000000000000000000..9b8b4191b268de267268cfcb90fc01c6b9df07d8 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/ViT-S-32.json @@ -0,0 +1,16 @@ +{ + "embed_dim": 384, + "vision_cfg": { + "image_size": 224, + "layers": 12, + "width": 384, + "patch_size": 32 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 384, + "heads": 6, + "layers": 12 + } +} \ No newline at end of file diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/ViT-bigG-14.json b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/ViT-bigG-14.json new file mode 100644 index 0000000000000000000000000000000000000000..2cfba479a2e8f3737e71ce240732bf3bc743d8b7 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/ViT-bigG-14.json @@ -0,0 +1,18 @@ +{ + "embed_dim": 1280, + "vision_cfg": { + "image_size": 224, + "layers": 48, + "width": 1664, + "head_width": 104, + "mlp_ratio": 4.9231, + "patch_size": 14 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 1280, + "heads": 20, + "layers": 32 + } +} \ No newline at end of file diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/ViT-e-14.json b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/ViT-e-14.json new file mode 100644 index 0000000000000000000000000000000000000000..91a0fe14d25a107fb8ec48dd7faae313fd26ed7b --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/ViT-e-14.json @@ -0,0 +1,18 @@ +{ + "embed_dim": 1280, + "vision_cfg": { + "image_size": 224, + "layers": 56, + "width": 1792, + "head_width": 112, + "mlp_ratio": 8.5715, + "patch_size": 14 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 1280, + "heads": 20, + "layers": 36 + } +} \ No newline at end of file diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/ViT-g-14.json b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/ViT-g-14.json new file mode 100644 index 0000000000000000000000000000000000000000..8c4b7325cc75b6112be7107d36ae2cb5762d9091 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/ViT-g-14.json @@ -0,0 +1,18 @@ +{ + "embed_dim": 1024, + "vision_cfg": { + "image_size": 224, + "layers": 40, + "width": 1408, + "head_width": 88, + "mlp_ratio": 4.3637, + "patch_size": 14 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 1024, + "heads": 16, + "layers": 24 + } +} \ No newline at end of file diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/coca_ViT-B-32.json b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/coca_ViT-B-32.json new file mode 100644 index 0000000000000000000000000000000000000000..7e7eb520a6a0096e5602d509ecd6186e278f4725 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/coca_ViT-B-32.json @@ -0,0 +1,30 @@ +{ + "embed_dim": 512, + "vision_cfg": { + "image_size": 224, + "layers": 12, + "width": 768, + "patch_size": 32, + "attentional_pool": true, + "attn_pooler_heads": 8, + "output_tokens": true + }, + "text_cfg": { + "context_length": 76, + "vocab_size": 49408, + "width": 512, + "heads": 8, + "layers": 12, + "embed_cls": true, + "output_tokens": true + }, + "multimodal_cfg": { + "context_length": 76, + "vocab_size": 49408, + "width": 512, + "heads": 8, + "layers": 12, + "attn_pooler_heads": 8 + }, + "custom_text": true +} \ No newline at end of file diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/coca_ViT-L-14.json b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/coca_ViT-L-14.json new file mode 100644 index 0000000000000000000000000000000000000000..3d5ca4ca2338540f06852df5ff35ea6277e64555 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/coca_ViT-L-14.json @@ -0,0 +1,30 @@ +{ + "embed_dim": 768, + "vision_cfg": { + "image_size": 224, + "layers": 24, + "width": 1024, + "patch_size": 14, + "attentional_pool": true, + "attn_pooler_heads": 8, + "output_tokens": true + }, + "text_cfg": { + "context_length": 76, + "vocab_size": 49408, + "width": 768, + "heads": 12, + "layers": 12, + "embed_cls": true, + "output_tokens": true + }, + "multimodal_cfg": { + "context_length": 76, + "vocab_size": 49408, + "width": 768, + "heads": 12, + "layers": 12, + "attn_pooler_heads": 12 + }, + "custom_text": true +} diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/coca_base.json b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/coca_base.json new file mode 100644 index 0000000000000000000000000000000000000000..cf8c6cecb78a49d7e7140145a0307cbd561077c2 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/coca_base.json @@ -0,0 +1,31 @@ +{ + "embed_dim": 512, + "multimodal_cfg": { + "width": 768, + "context_length": 76, + "vocab_size": 64000, + "mlp_ratio": 4, + "layers": 12, + "dim_head": 64, + "heads": 12, + "n_queries": 256, + "attn_pooler_heads": 8 + }, + "vision_cfg": { + "image_size": 288, + "layers": 12, + "width": 768, + "patch_size": 18, + "output_tokens": true + }, + "text_cfg": { + "context_length": 76, + "vocab_size": 64000, + "layers": 12, + "heads": 12, + "width": 768, + "embed_cls": true, + "output_tokens": true + }, + "custom_text": true +} \ No newline at end of file diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/coca_roberta-ViT-B-32.json b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/coca_roberta-ViT-B-32.json new file mode 100644 index 0000000000000000000000000000000000000000..fb46354b95a17a46d7fcfd9d504e917ee6c1608c --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/coca_roberta-ViT-B-32.json @@ -0,0 +1,24 @@ +{ + "embed_dim": 512, + "vision_cfg": { + "image_size": 224, + "layers": 12, + "width": 768, + "patch_size": 32, + "output_tokens": true + }, + "text_cfg": { + "hf_model_name": "roberta-base", + "hf_tokenizer_name": "roberta-base", + "proj": "linear", + "width": 768, + "output_tokens": true + }, + "multimodal_cfg": { + "context_length": 76, + "width": 768, + "heads": 8, + "layers": 12 + }, + "custom_text": true +} diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/convnext_base.json b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/convnext_base.json new file mode 100644 index 0000000000000000000000000000000000000000..bb6dba181d950ea5081155c90d47e72c94816b80 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/convnext_base.json @@ -0,0 +1,19 @@ +{ + "embed_dim": 512, + "vision_cfg": { + "timm_model_name": "convnext_base", + "timm_model_pretrained": false, + "timm_pool": "", + "timm_proj": "linear", + "timm_drop": 0.0, + "timm_drop_path": 0.1, + "image_size": 224 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 512, + "heads": 8, + "layers": 12 + } +} \ No newline at end of file diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/convnext_base_w.json b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/convnext_base_w.json new file mode 100644 index 0000000000000000000000000000000000000000..82ea7ae3659e5514f37ff982f0ab1141dff4bd18 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/convnext_base_w.json @@ -0,0 +1,19 @@ +{ + "embed_dim": 640, + "vision_cfg": { + "timm_model_name": "convnext_base", + "timm_model_pretrained": false, + "timm_pool": "", + "timm_proj": "linear", + "timm_drop": 0.0, + "timm_drop_path": 0.1, + "image_size": 256 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 640, + "heads": 10, + "layers": 12 + } +} \ No newline at end of file diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/convnext_base_w_320.json b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/convnext_base_w_320.json new file mode 100644 index 0000000000000000000000000000000000000000..0a07c4e16abaa4015ecc5f82ec845de16e1f9d88 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/convnext_base_w_320.json @@ -0,0 +1,19 @@ +{ + "embed_dim": 640, + "vision_cfg": { + "timm_model_name": "convnext_base", + "timm_model_pretrained": false, + "timm_pool": "", + "timm_proj": "linear", + "timm_drop": 0.0, + "timm_drop_path": 0.1, + "image_size": 320 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 640, + "heads": 10, + "layers": 12 + } +} \ No newline at end of file diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/convnext_large.json b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/convnext_large.json new file mode 100644 index 0000000000000000000000000000000000000000..c4a1fea73dbead71c218a0e74b9b15f9b252e3ef --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/convnext_large.json @@ -0,0 +1,19 @@ +{ + "embed_dim": 768, + "vision_cfg": { + "timm_model_name": "convnext_large", + "timm_model_pretrained": false, + "timm_pool": "", + "timm_proj": "linear", + "timm_drop": 0.0, + "timm_drop_path": 0.1, + "image_size": 224 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 768, + "heads": 12, + "layers": 12 + } +} \ No newline at end of file diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/convnext_large_d.json b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/convnext_large_d.json new file mode 100644 index 0000000000000000000000000000000000000000..ae8fed21b58e1a6a411daf8b792ee50f0ab42346 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/convnext_large_d.json @@ -0,0 +1,19 @@ +{ + "embed_dim": 768, + "vision_cfg": { + "timm_model_name": "convnext_large", + "timm_model_pretrained": false, + "timm_pool": "", + "timm_proj": "mlp", + "timm_drop": 0.0, + "timm_drop_path": 0.1, + "image_size": 256 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 768, + "heads": 12, + "layers": 16 + } +} \ No newline at end of file diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/convnext_large_d_320.json b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/convnext_large_d_320.json new file mode 100644 index 0000000000000000000000000000000000000000..54c3df36a6f56ace0b12ada24c13058de96feed8 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/convnext_large_d_320.json @@ -0,0 +1,19 @@ +{ + "embed_dim": 768, + "vision_cfg": { + "timm_model_name": "convnext_large", + "timm_model_pretrained": false, + "timm_pool": "", + "timm_proj": "mlp", + "timm_drop": 0.0, + "timm_drop_path": 0.1, + "image_size": 320 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 768, + "heads": 12, + "layers": 16 + } +} \ No newline at end of file diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/convnext_small.json b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/convnext_small.json new file mode 100644 index 0000000000000000000000000000000000000000..3592c2a5cd21aae8d2544931773cf7603f67ea28 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/convnext_small.json @@ -0,0 +1,19 @@ +{ + "embed_dim": 512, + "vision_cfg": { + "timm_model_name": "convnext_small", + "timm_model_pretrained": false, + "timm_pool": "", + "timm_proj": "linear", + "timm_drop": 0.0, + "timm_drop_path": 0.1, + "image_size": 224 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 512, + "heads": 8, + "layers": 12 + } +} \ No newline at end of file diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/convnext_tiny.json b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/convnext_tiny.json new file mode 100644 index 0000000000000000000000000000000000000000..ad11470f5ec40ffec771096971ce58d3d5b9249b --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/convnext_tiny.json @@ -0,0 +1,19 @@ +{ + "embed_dim": 1024, + "vision_cfg": { + "timm_model_name": "convnext_tiny", + "timm_model_pretrained": false, + "timm_pool": "", + "timm_proj": "linear", + "timm_drop": 0.0, + "timm_drop_path": 0.1, + "image_size": 224 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 512, + "heads": 8, + "layers": 12 + } +} \ No newline at end of file diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/convnext_xlarge.json b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/convnext_xlarge.json new file mode 100644 index 0000000000000000000000000000000000000000..2a909965932eef994177c829fefc2bdc1c219b3f --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/convnext_xlarge.json @@ -0,0 +1,19 @@ +{ + "embed_dim": 1024, + "vision_cfg": { + "timm_model_name": "convnext_xlarge", + "timm_model_pretrained": false, + "timm_pool": "", + "timm_proj": "linear", + "timm_drop": 0.0, + "timm_drop_path": 0.1, + "image_size": 256 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 1024, + "heads": 16, + "layers": 20 + } +} \ No newline at end of file diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/convnext_xxlarge.json b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/convnext_xxlarge.json new file mode 100644 index 0000000000000000000000000000000000000000..23a55a681c346d1a315d8a163c1cb6ad495e6a91 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/convnext_xxlarge.json @@ -0,0 +1,19 @@ +{ + "embed_dim": 1024, + "vision_cfg": { + "timm_model_name": "convnext_xxlarge", + "timm_model_pretrained": false, + "timm_pool": "", + "timm_proj": "linear", + "timm_drop": 0.0, + "timm_drop_path": 0.1, + "image_size": 256 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 1024, + "heads": 16, + "layers": 24 + } +} \ No newline at end of file diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/convnext_xxlarge_320.json b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/convnext_xxlarge_320.json new file mode 100644 index 0000000000000000000000000000000000000000..ac5134ca12cbaa97772cde059270d345386a74c7 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/convnext_xxlarge_320.json @@ -0,0 +1,19 @@ +{ + "embed_dim": 1024, + "vision_cfg": { + "timm_model_name": "convnext_xxlarge", + "timm_model_pretrained": false, + "timm_pool": "", + "timm_proj": "linear", + "timm_drop": 0.0, + "timm_drop_path": 0.1, + "image_size": 320 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 1024, + "heads": 16, + "layers": 24 + } +} \ No newline at end of file diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/mt5-base-ViT-B-32.json b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/mt5-base-ViT-B-32.json new file mode 100644 index 0000000000000000000000000000000000000000..58cad89cf0f446bbe15e4e25b1ac43424a828017 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/mt5-base-ViT-B-32.json @@ -0,0 +1,15 @@ +{ + "embed_dim": 512, + "vision_cfg": { + "image_size": 224, + "layers": 12, + "width": 768, + "patch_size": 32 + }, + "text_cfg": { + "hf_model_name": "google/mt5-base", + "hf_tokenizer_name": "google/mt5-base", + "proj": "mlp", + "pooler_type": "mean_pooler" + } +} diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/mt5-xl-ViT-H-14.json b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/mt5-xl-ViT-H-14.json new file mode 100644 index 0000000000000000000000000000000000000000..b432810777ba7269dbb0e89edfe65cdd27e7d255 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/mt5-xl-ViT-H-14.json @@ -0,0 +1,16 @@ +{ + "embed_dim": 1024, + "vision_cfg": { + "image_size": 224, + "layers": 32, + "width": 1280, + "head_width": 80, + "patch_size": 14 + }, + "text_cfg": { + "hf_model_name": "google/mt5-xl", + "hf_tokenizer_name": "google/mt5-xl", + "proj": "mlp", + "pooler_type": "mean_pooler" + } +} diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/roberta-ViT-B-32.json b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/roberta-ViT-B-32.json new file mode 100644 index 0000000000000000000000000000000000000000..ed687d472a73bb2ac96025f355f80437ab14c260 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/roberta-ViT-B-32.json @@ -0,0 +1,16 @@ +{ + "embed_dim": 512, + "quick_gelu": true, + "vision_cfg": { + "image_size": 224, + "layers": 12, + "width": 768, + "patch_size": 32 + }, + "text_cfg": { + "hf_model_name": "roberta-base", + "hf_tokenizer_name": "roberta-base", + "proj": "mlp", + "pooler_type": "mean_pooler" + } +} diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/swin_base_patch4_window7_224.json b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/swin_base_patch4_window7_224.json new file mode 100644 index 0000000000000000000000000000000000000000..bd6820f0cf2aa655e0a2723287f4b78895a58e6a --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/swin_base_patch4_window7_224.json @@ -0,0 +1,17 @@ +{ + "embed_dim": 640, + "vision_cfg": { + "timm_model_name": "swin_base_patch4_window7_224", + "timm_model_pretrained": false, + "timm_pool": "", + "timm_proj": "linear", + "image_size": 224 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 640, + "heads": 10, + "layers": 12 + } +} \ No newline at end of file diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/vit_medium_patch16_gap_256.json b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/vit_medium_patch16_gap_256.json new file mode 100644 index 0000000000000000000000000000000000000000..8843eaf08cad16c3e7b5f496fd650715c9573f65 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/vit_medium_patch16_gap_256.json @@ -0,0 +1,17 @@ +{ + "embed_dim": 512, + "vision_cfg": { + "timm_model_name": "vit_medium_patch16_gap_256", + "timm_model_pretrained": false, + "timm_pool": "", + "timm_proj": "linear", + "image_size": 256 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 512, + "heads": 8, + "layers": 12 + } +} \ No newline at end of file diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/vit_relpos_medium_patch16_cls_224.json b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/vit_relpos_medium_patch16_cls_224.json new file mode 100644 index 0000000000000000000000000000000000000000..ed217b202d5e6071c5307f4547c97ff4cfe2abd1 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/vit_relpos_medium_patch16_cls_224.json @@ -0,0 +1,17 @@ +{ + "embed_dim": 512, + "vision_cfg": { + "timm_model_name": "vit_relpos_medium_patch16_cls_224", + "timm_model_pretrained": false, + "timm_pool": "", + "timm_proj": "linear", + "image_size": 224 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 512, + "heads": 8, + "layers": 12 + } +} \ No newline at end of file diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/xlm-roberta-base-ViT-B-32.json b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/xlm-roberta-base-ViT-B-32.json new file mode 100644 index 0000000000000000000000000000000000000000..751bccc2c6fc41bc4ff20182de88d86739d518d9 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/xlm-roberta-base-ViT-B-32.json @@ -0,0 +1,15 @@ +{ + "embed_dim": 512, + "vision_cfg": { + "image_size": 224, + "layers": 12, + "width": 768, + "patch_size": 32 + }, + "text_cfg": { + "hf_model_name": "xlm-roberta-base", + "hf_tokenizer_name": "xlm-roberta-base", + "proj": "mlp", + "pooler_type": "mean_pooler" + } +} diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/xlm-roberta-large-ViT-H-14.json b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/xlm-roberta-large-ViT-H-14.json new file mode 100644 index 0000000000000000000000000000000000000000..31f271faa9bbb7a9da53900b483a4c00a16f3c4a --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/model_configs/xlm-roberta-large-ViT-H-14.json @@ -0,0 +1,16 @@ +{ + "embed_dim": 1024, + "vision_cfg": { + "image_size": 224, + "layers": 32, + "width": 1280, + "head_width": 80, + "patch_size": 14 + }, + "text_cfg": { + "hf_model_name": "xlm-roberta-large", + "hf_tokenizer_name": "xlm-roberta-large", + "proj": "mlp", + "pooler_type": "mean_pooler" + } +} diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/tiny_clip/__init__.py b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/tiny_clip/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..310ee0047ad9767ba8d3ce1928f9c1a695fbf807 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/tiny_clip/__init__.py @@ -0,0 +1,11 @@ +from .constants import OPENAI_DATASET_MEAN, OPENAI_DATASET_STD +from .factory import list_models, create_model, create_model_and_transforms, get_tokenizer, add_model_config, \ + load_model, load_exp +from .loss import ClipLoss +from .model import CLIP, CLIPTextCfg, CLIPVisionCfg, convert_weights_to_fp16, trace_model +from .openai import load_openai_model, list_openai_models +from .pretrained import list_pretrained, list_pretrained_tag_models, list_pretrained_model_tags,\ + get_pretrained_url, download_pretrained_from_url, is_pretrained_cfg, get_pretrained_cfg, download_pretrained +from .tokenizer import SimpleTokenizer, tokenize +from .transform import image_transform +from .l0module import L0Module diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/tiny_clip/clip_soft_loss.py b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/tiny_clip/clip_soft_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..dc036027ec98bebe18e1a2f84940c373b3bc863f --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/tiny_clip/clip_soft_loss.py @@ -0,0 +1,88 @@ +import torch +import torch.distributed.nn +from torch import distributed as dist, nn as nn +from torch.nn import functional as F +from open_clip.loss import gather_features, gather_feature +from contextlib import nullcontext +import numpy as np + + +class ClipSoftLoss(nn.Module): + def __init__( + self, + local_loss=False, + gather_with_grad=False, + cache_labels=False, + rank=None, + world_size=None, + use_horovod=False, + ): + super().__init__() + self.local_loss = local_loss + self.gather_with_grad = gather_with_grad + if rank is None: + assert world_size is None + rank, world_size = dist.get_rank(), dist.get_world_size() + self.rank = rank + self.world_size = world_size + self.use_horovod = use_horovod + assert self.local_loss + + # cache state + self.feat_buffer = dict() + + def compute_sim(self, image_features, text_features): + all_image_features = self.gather_feature(image_features) + all_text_features = self.gather_feature(text_features) + + # calculate logits + # with torch.cuda.amp.autocast(enabled=False): + with nullcontext(): + logits_per_image = image_features @ all_text_features.T + logits_per_text = text_features @ all_image_features.T + return logits_per_image, logits_per_text + + def gather_feature(self, feat): + feat_id = id(feat) + if feat_id not in self.feat_buffer: + args = (self.local_loss, self.gather_with_grad, + self.rank, self.world_size, self.use_horovod) + all_feat = gather_feature(feat, *args) + self.feat_buffer[feat_id] = all_feat + return self.feat_buffer[feat_id] + + def forward(self, + image_features, text_features, logit_scale, + teacher_image_features, teacher_text_features, teacher_logit_scale, + average_two_losses=True, + labels=None, + ): + # calculated ground-truth and cache if enabled + logits_per_image, logits_per_text = self.compute_sim( + image_features, text_features) + teacher_logits_per_image, teacher_logits_per_text = self.compute_sim( + teacher_image_features, teacher_text_features) + + self.feat_buffer.clear() + + # with torch.cuda.amp.autocast(enabled=False): + with nullcontext(): + logits_per_image = logit_scale * logits_per_image + logits_per_text = logit_scale * logits_per_text + teacher_logits_per_image = teacher_logit_scale * teacher_logits_per_image + teacher_logits_per_text = teacher_logit_scale * teacher_logits_per_text + + def single_loss_fn(logits, teacher_logits): + teacher_probs = F.softmax(teacher_logits, -1) + return F.cross_entropy(logits, teacher_probs) + + if average_two_losses: + total_loss = (single_loss_fn(logits_per_image, teacher_logits_per_image) + + single_loss_fn(logits_per_text, teacher_logits_per_text)) / 2 + return total_loss + else: + img2text_loss = single_loss_fn( + logits_per_image, teacher_logits_per_image) + text2img_loss = single_loss_fn( + logits_per_text, teacher_logits_per_text) + return img2text_loss, text2img_loss diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/tiny_clip/constants.py b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/tiny_clip/constants.py new file mode 100644 index 0000000000000000000000000000000000000000..a670bb3fab442baeb9af53b91c312e6982af57ee --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/tiny_clip/constants.py @@ -0,0 +1,2 @@ +OPENAI_DATASET_MEAN = (0.48145466, 0.4578275, 0.40821073) +OPENAI_DATASET_STD = (0.26862954, 0.26130258, 0.27577711) diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/tiny_clip/factory.py b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/tiny_clip/factory.py new file mode 100644 index 0000000000000000000000000000000000000000..f08fba9594f02f4c0e94a0e704b1c44b6562e3df --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/tiny_clip/factory.py @@ -0,0 +1,286 @@ +import json +import logging +import os +import pathlib +import re +from copy import deepcopy +from pathlib import Path +from typing import Optional, Tuple + +import torch + +from .constants import OPENAI_DATASET_MEAN, OPENAI_DATASET_STD +from .model import CLIP, convert_weights_to_fp16, resize_pos_embed +from .model import load_pruned_model, prune_model +from .pretrained import get_pretrained_cfg, download_pretrained + +# Optional imports - these may not be available in all environments +try: + from .openai import load_openai_model +except ImportError: + load_openai_model = None + +try: + from .transform import image_transform +except ImportError: + # Simple placeholder for image_transform + def image_transform(image_size, is_train=True, mean=None, std=None, val_keep_ratio=True): + from torchvision import transforms + if mean is None: + mean = OPENAI_DATASET_MEAN + if std is None: + std = OPENAI_DATASET_STD + if is_train: + return transforms.Compose([ + transforms.RandomResizedCrop(image_size), + transforms.RandomHorizontalFlip(), + transforms.ToTensor(), + transforms.Normalize(mean=mean, std=std) + ]) + else: + return transforms.Compose([ + transforms.Resize(image_size), + transforms.CenterCrop(image_size), + transforms.ToTensor(), + transforms.Normalize(mean=mean, std=std) + ]) + +try: + from .tokenizer import HFTokenizer, tokenize +except ImportError: + # Placeholder tokenizers + class HFTokenizer: + def __init__(self, *args, **kwargs): + raise NotImplementedError("HFTokenizer requires additional dependencies") + + def tokenize(*args, **kwargs): + raise NotImplementedError("tokenize requires additional dependencies") + +HF_HUB_PREFIX = 'hf-hub:' +_MODEL_CONFIG_PATHS = [Path(__file__).parent / f"model_configs/"] +# directory (model_name: config) of model architecture configs +_MODEL_CONFIGS = {} + + +def _natural_key(string_): + return [int(s) if s.isdigit() else s for s in re.split(r'(\d+)', string_.lower())] + + +def _rescan_model_configs(): + global _MODEL_CONFIGS + + config_ext = ('.json',) + config_files = [] + for config_path in _MODEL_CONFIG_PATHS: + if config_path.is_file() and config_path.suffix in config_ext: + config_files.append(config_path) + elif config_path.is_dir(): + for ext in config_ext: + config_files.extend(config_path.glob(f'*{ext}')) + + for cf in config_files: + with open(cf, 'r') as f: + model_cfg = json.load(f) + if all(a in model_cfg for a in ('embed_dim', 'vision_cfg', 'text_cfg')): + _MODEL_CONFIGS[cf.stem] = model_cfg + + _MODEL_CONFIGS = {k: v for k, v in sorted( + _MODEL_CONFIGS.items(), key=lambda x: _natural_key(x[0]))} + + +_rescan_model_configs() # initial populate of model config registry + + +def get_model_config(model_name): + if model_name in _MODEL_CONFIGS: + return deepcopy(_MODEL_CONFIGS[model_name]) + else: + return None + + +def get_tokenizer(model_name): + if model_name.startswith(HF_HUB_PREFIX): + tokenizer = HFTokenizer(model_name[len(HF_HUB_PREFIX):]) + else: + config = get_model_config(model_name) + tokenizer = HFTokenizer( + config['text_cfg']['hf_tokenizer_name']) if 'hf_tokenizer_name' in config['text_cfg'] else tokenize + return tokenizer + + +def load_state_dict(checkpoint_path: str, map_location='cpu'): + checkpoint = torch.load(checkpoint_path, map_location=map_location) + if isinstance(checkpoint, dict) and 'state_dict' in checkpoint: + state_dict = checkpoint['state_dict'] + else: + state_dict = checkpoint + if next(iter(state_dict.items()))[0].startswith('module'): + state_dict = {k[7:]: v for k, v in state_dict.items()} + return state_dict + + +def load_checkpoint(model, checkpoint_path, strict=True): + state_dict = load_state_dict(checkpoint_path) + resize_pos_embed(state_dict, model) + incompatible_keys = model.load_state_dict(state_dict, strict=strict) + return incompatible_keys + + +def load_pruned_checkpoint(model, checkpoint_path, strict=True): + state_dict = load_state_dict(checkpoint_path) + resize_pos_embed(state_dict, model) + incompatible_keys = load_pruned_model(model, state_dict, strict=strict) + return incompatible_keys + + +def create_model( + model_name: str, + pretrained: str = '', + precision: str = 'fp32', + device: torch.device = torch.device('cpu'), + jit: bool = False, + force_quick_gelu: bool = False, + pretrained_image: bool = False, + cache_dir: Optional[str] = None, + args=None, +): + # for callers using old naming with / in ViT names + model_name = model_name.replace('/', '-') + if pretrained.lower() == 'openai': + if load_openai_model is None: + raise RuntimeError("load_openai_model is not available. Please install required dependencies.") + logging.info(f'Loading pretrained {model_name} from OpenAI.') + model = load_openai_model( + model_name, device=device, jit=jit, cache_dir=cache_dir) + # See https://discuss.pytorch.org/t/valueerror-attemting-to-unscale-fp16-gradients/81372 + if precision == "amp" or precision == "fp32": + model = model.float() + else: + if model_name in _MODEL_CONFIGS: + logging.info(f'Loading {model_name} model config.') + model_cfg = deepcopy(_MODEL_CONFIGS[model_name]) + else: + logging.error( + f'Model config for {model_name} not found; available models {list_models()}.') + raise RuntimeError(f'Model config for {model_name} not found.') + + if force_quick_gelu: + # override for use of QuickGELU on non-OpenAI transformer models + model_cfg["quick_gelu"] = True + + if pretrained_image: + if 'timm_model_name' in model_cfg.get('vision_cfg', {}): + # pretrained weight loading for timm models set via vision_cfg + model_cfg['vision_cfg']['timm_model_pretrained'] = True + else: + assert False, 'pretrained image towers currently only supported for timm models' + if args is not None: + model_cfg['mask_image'] = getattr(args, 'prune_image', False) + model_cfg['mask_text'] = getattr(args, 'prune_text', False) + model_cfg['sparsity_warmup'] = getattr( + args, 'sparsity_warmup', 1000) + model_cfg['start_sparsity'] = getattr(args, 'start_sparsity', 0.0) + model_cfg['sparsity'] = getattr(args, 'target_sparsity', 0.25) + logging.info( + f'model sparsity varies from {model_cfg["start_sparsity"]} to {model_cfg["sparsity"]}, sparsity warmup steps: {model_cfg["sparsity_warmup"]}') + + logging.info(str(model_cfg)) + auto_weight_inheritance = model_cfg.get('mask_image', False) or \ + model_cfg.get('mask_text', False) + + model = CLIP(**model_cfg) + pretrained_cfg = {} + if pretrained: + checkpoint_path = '' + pretrained_cfg = get_pretrained_cfg(model_name, pretrained) + if pretrained_cfg: + checkpoint_path = download_pretrained( + pretrained_cfg, cache_dir=cache_dir) + elif os.path.exists(pretrained): + checkpoint_path = pretrained + + if checkpoint_path: + logging.info( + f'Loading pretrained {model_name} weights ({pretrained}).') + if not auto_weight_inheritance: + load_checkpoint(model, checkpoint_path) + else: + load_pruned_checkpoint(model, checkpoint_path) + model = prune_model(model) + else: + logging.warning( + f'Pretrained weights ({pretrained}) not found for model {model_name}.') + raise RuntimeError( + f'Pretrained weights ({pretrained}) not found for model {model_name}.') + + model.to(device=device) + if precision == "fp16": + assert device.type != 'cpu' + convert_weights_to_fp16(model) + + # set image / mean metadata from pretrained_cfg if available, or use default + if 'davit' in model_name.lower(): + pretrained_cfg['mean'] = [0.485, 0.456, 0.406] + pretrained_cfg['std'] = [0.229, 0.224, 0.225] + model.visual.image_mean = pretrained_cfg.get( + 'mean', None) or OPENAI_DATASET_MEAN + model.visual.image_std = pretrained_cfg.get( + 'std', None) or OPENAI_DATASET_STD + + if jit: + model = torch.jit.script(model) + + return model + + +def create_model_and_transforms( + model_name: str, + pretrained: str = '', + precision: str = 'fp32', + device: torch.device = torch.device('cpu'), + jit: bool = False, + force_quick_gelu: bool = False, + pretrained_image: bool = False, + image_mean: Optional[Tuple[float, ...]] = None, + image_std: Optional[Tuple[float, ...]] = None, + cache_dir: Optional[str] = None, + args=None, +): + model = create_model( + model_name, pretrained, precision, device, jit, + force_quick_gelu=force_quick_gelu, + pretrained_image=pretrained_image, + cache_dir=cache_dir, + args=args) + + image_mean = image_mean or getattr(model.visual, 'image_mean', None) + image_std = image_std or getattr(model.visual, 'image_std', None) + val_keep_ratio = 'davit' not in model_name.lower() + preprocess_train = image_transform( + model.visual.image_size, is_train=True, mean=image_mean, std=image_std) + preprocess_val = image_transform(model.visual.image_size, is_train=False, + mean=image_mean, std=image_std, val_keep_ratio=val_keep_ratio) + return model, preprocess_train, preprocess_val + + +def list_models(): + """ enumerate available model architectures based on config files """ + return list(_MODEL_CONFIGS.keys()) + + +def add_model_config(path): + """ add model config path or file and update registry """ + if not isinstance(path, Path): + path = Path(path) + _MODEL_CONFIG_PATHS.append(path) + _rescan_model_configs() + + +def load_exp(name, device='cpu'): + assert '@' in name + teacher_model_name, teacher_pretrained = name.split('@') + return create_model_and_transforms(teacher_model_name, pretrained=teacher_pretrained) + + +def load_model(name, device='cpu'): + return load_exp(name, device)[0] diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/tiny_clip/imagenet_zeroshot_data.py b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/tiny_clip/imagenet_zeroshot_data.py new file mode 100644 index 0000000000000000000000000000000000000000..2ffa6af96150bdd146ac3e395e60f90fbed8eed7 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/tiny_clip/imagenet_zeroshot_data.py @@ -0,0 +1,251 @@ + + +imagenet_classnames = ["tench", "goldfish", "great white shark", "tiger shark", "hammerhead shark", "electric ray", + "stingray", "rooster", "hen", "ostrich", "brambling", "goldfinch", "house finch", "junco", + "indigo bunting", "American robin", "bulbul", "jay", "magpie", "chickadee", "American dipper", + "kite (bird of prey)", "bald eagle", "vulture", "great grey owl", "fire salamander", + "smooth newt", "newt", "spotted salamander", "axolotl", "American bullfrog", "tree frog", + "tailed frog", "loggerhead sea turtle", "leatherback sea turtle", "mud turtle", "terrapin", + "box turtle", "banded gecko", "green iguana", "Carolina anole", + "desert grassland whiptail lizard", "agama", "frilled-necked lizard", "alligator lizard", + "Gila monster", "European green lizard", "chameleon", "Komodo dragon", "Nile crocodile", + "American alligator", "triceratops", "worm snake", "ring-necked snake", + "eastern hog-nosed snake", "smooth green snake", "kingsnake", "garter snake", "water snake", + "vine snake", "night snake", "boa constrictor", "African rock python", "Indian cobra", + "green mamba", "sea snake", "Saharan horned viper", "eastern diamondback rattlesnake", + "sidewinder rattlesnake", "trilobite", "harvestman", "scorpion", "yellow garden spider", + "barn spider", "European garden spider", "southern black widow", "tarantula", "wolf spider", + "tick", "centipede", "black grouse", "ptarmigan", "ruffed grouse", "prairie grouse", "peafowl", + "quail", "partridge", "african grey parrot", "macaw", "sulphur-crested cockatoo", "lorikeet", + "coucal", "bee eater", "hornbill", "hummingbird", "jacamar", "toucan", "duck", + "red-breasted merganser", "goose", "black swan", "tusker", "echidna", "platypus", "wallaby", + "koala", "wombat", "jellyfish", "sea anemone", "brain coral", "flatworm", "nematode", "conch", + "snail", "slug", "sea slug", "chiton", "chambered nautilus", "Dungeness crab", "rock crab", + "fiddler crab", "red king crab", "American lobster", "spiny lobster", "crayfish", "hermit crab", + "isopod", "white stork", "black stork", "spoonbill", "flamingo", "little blue heron", + "great egret", "bittern bird", "crane bird", "limpkin", "common gallinule", "American coot", + "bustard", "ruddy turnstone", "dunlin", "common redshank", "dowitcher", "oystercatcher", + "pelican", "king penguin", "albatross", "grey whale", "killer whale", "dugong", "sea lion", + "Chihuahua", "Japanese Chin", "Maltese", "Pekingese", "Shih Tzu", "King Charles Spaniel", + "Papillon", "toy terrier", "Rhodesian Ridgeback", "Afghan Hound", "Basset Hound", "Beagle", + "Bloodhound", "Bluetick Coonhound", "Black and Tan Coonhound", "Treeing Walker Coonhound", + "English foxhound", "Redbone Coonhound", "borzoi", "Irish Wolfhound", "Italian Greyhound", + "Whippet", "Ibizan Hound", "Norwegian Elkhound", "Otterhound", "Saluki", "Scottish Deerhound", + "Weimaraner", "Staffordshire Bull Terrier", "American Staffordshire Terrier", + "Bedlington Terrier", "Border Terrier", "Kerry Blue Terrier", "Irish Terrier", + "Norfolk Terrier", "Norwich Terrier", "Yorkshire Terrier", "Wire Fox Terrier", + "Lakeland Terrier", "Sealyham Terrier", "Airedale Terrier", "Cairn Terrier", + "Australian Terrier", "Dandie Dinmont Terrier", "Boston Terrier", "Miniature Schnauzer", + "Giant Schnauzer", "Standard Schnauzer", "Scottish Terrier", "Tibetan Terrier", + "Australian Silky Terrier", "Soft-coated Wheaten Terrier", "West Highland White Terrier", + "Lhasa Apso", "Flat-Coated Retriever", "Curly-coated Retriever", "Golden Retriever", + "Labrador Retriever", "Chesapeake Bay Retriever", "German Shorthaired Pointer", "Vizsla", + "English Setter", "Irish Setter", "Gordon Setter", "Brittany dog", "Clumber Spaniel", + "English Springer Spaniel", "Welsh Springer Spaniel", "Cocker Spaniel", "Sussex Spaniel", + "Irish Water Spaniel", "Kuvasz", "Schipperke", "Groenendael dog", "Malinois", "Briard", + "Australian Kelpie", "Komondor", "Old English Sheepdog", "Shetland Sheepdog", "collie", + "Border Collie", "Bouvier des Flandres dog", "Rottweiler", "German Shepherd Dog", "Dobermann", + "Miniature Pinscher", "Greater Swiss Mountain Dog", "Bernese Mountain Dog", + "Appenzeller Sennenhund", "Entlebucher Sennenhund", "Boxer", "Bullmastiff", "Tibetan Mastiff", + "French Bulldog", "Great Dane", "St. Bernard", "husky", "Alaskan Malamute", "Siberian Husky", + "Dalmatian", "Affenpinscher", "Basenji", "pug", "Leonberger", "Newfoundland dog", + "Great Pyrenees dog", "Samoyed", "Pomeranian", "Chow Chow", "Keeshond", "brussels griffon", + "Pembroke Welsh Corgi", "Cardigan Welsh Corgi", "Toy Poodle", "Miniature Poodle", + "Standard Poodle", "Mexican hairless dog (xoloitzcuintli)", "grey wolf", "Alaskan tundra wolf", + "red wolf or maned wolf", "coyote", "dingo", "dhole", "African wild dog", "hyena", "red fox", + "kit fox", "Arctic fox", "grey fox", "tabby cat", "tiger cat", "Persian cat", "Siamese cat", + "Egyptian Mau", "cougar", "lynx", "leopard", "snow leopard", "jaguar", "lion", "tiger", + "cheetah", "brown bear", "American black bear", "polar bear", "sloth bear", "mongoose", + "meerkat", "tiger beetle", "ladybug", "ground beetle", "longhorn beetle", "leaf beetle", + "dung beetle", "rhinoceros beetle", "weevil", "fly", "bee", "ant", "grasshopper", + "cricket insect", "stick insect", "cockroach", "praying mantis", "cicada", "leafhopper", + "lacewing", "dragonfly", "damselfly", "red admiral butterfly", "ringlet butterfly", + "monarch butterfly", "small white butterfly", "sulphur butterfly", "gossamer-winged butterfly", + "starfish", "sea urchin", "sea cucumber", "cottontail rabbit", "hare", "Angora rabbit", + "hamster", "porcupine", "fox squirrel", "marmot", "beaver", "guinea pig", "common sorrel horse", + "zebra", "pig", "wild boar", "warthog", "hippopotamus", "ox", "water buffalo", "bison", + "ram (adult male sheep)", "bighorn sheep", "Alpine ibex", "hartebeest", "impala (antelope)", + "gazelle", "arabian camel", "llama", "weasel", "mink", "European polecat", + "black-footed ferret", "otter", "skunk", "badger", "armadillo", "three-toed sloth", "orangutan", + "gorilla", "chimpanzee", "gibbon", "siamang", "guenon", "patas monkey", "baboon", "macaque", + "langur", "black-and-white colobus", "proboscis monkey", "marmoset", "white-headed capuchin", + "howler monkey", "titi monkey", "Geoffroy's spider monkey", "common squirrel monkey", + "ring-tailed lemur", "indri", "Asian elephant", "African bush elephant", "red panda", + "giant panda", "snoek fish", "eel", "silver salmon", "rock beauty fish", "clownfish", + "sturgeon", "gar fish", "lionfish", "pufferfish", "abacus", "abaya", "academic gown", + "accordion", "acoustic guitar", "aircraft carrier", "airliner", "airship", "altar", "ambulance", + "amphibious vehicle", "analog clock", "apiary", "apron", "trash can", "assault rifle", + "backpack", "bakery", "balance beam", "balloon", "ballpoint pen", "Band-Aid", "banjo", + "baluster / handrail", "barbell", "barber chair", "barbershop", "barn", "barometer", "barrel", + "wheelbarrow", "baseball", "basketball", "bassinet", "bassoon", "swimming cap", "bath towel", + "bathtub", "station wagon", "lighthouse", "beaker", "military hat (bearskin or shako)", + "beer bottle", "beer glass", "bell tower", "baby bib", "tandem bicycle", "bikini", + "ring binder", "binoculars", "birdhouse", "boathouse", "bobsleigh", "bolo tie", "poke bonnet", + "bookcase", "bookstore", "bottle cap", "hunting bow", "bow tie", "brass memorial plaque", "bra", + "breakwater", "breastplate", "broom", "bucket", "buckle", "bulletproof vest", + "high-speed train", "butcher shop", "taxicab", "cauldron", "candle", "cannon", "canoe", + "can opener", "cardigan", "car mirror", "carousel", "tool kit", "cardboard box / carton", + "car wheel", "automated teller machine", "cassette", "cassette player", "castle", "catamaran", + "CD player", "cello", "mobile phone", "chain", "chain-link fence", "chain mail", "chainsaw", + "storage chest", "chiffonier", "bell or wind chime", "china cabinet", "Christmas stocking", + "church", "movie theater", "cleaver", "cliff dwelling", "cloak", "clogs", "cocktail shaker", + "coffee mug", "coffeemaker", "spiral or coil", "combination lock", "computer keyboard", + "candy store", "container ship", "convertible", "corkscrew", "cornet", "cowboy boot", + "cowboy hat", "cradle", "construction crane", "crash helmet", "crate", "infant bed", + "Crock Pot", "croquet ball", "crutch", "cuirass", "dam", "desk", "desktop computer", + "rotary dial telephone", "diaper", "digital clock", "digital watch", "dining table", + "dishcloth", "dishwasher", "disc brake", "dock", "dog sled", "dome", "doormat", "drilling rig", + "drum", "drumstick", "dumbbell", "Dutch oven", "electric fan", "electric guitar", + "electric locomotive", "entertainment center", "envelope", "espresso machine", "face powder", + "feather boa", "filing cabinet", "fireboat", "fire truck", "fire screen", "flagpole", "flute", + "folding chair", "football helmet", "forklift", "fountain", "fountain pen", "four-poster bed", + "freight car", "French horn", "frying pan", "fur coat", "garbage truck", + "gas mask or respirator", "gas pump", "goblet", "go-kart", "golf ball", "golf cart", "gondola", + "gong", "gown", "grand piano", "greenhouse", "radiator grille", "grocery store", "guillotine", + "hair clip", "hair spray", "half-track", "hammer", "hamper", "hair dryer", "hand-held computer", + "handkerchief", "hard disk drive", "harmonica", "harp", "combine harvester", "hatchet", + "holster", "home theater", "honeycomb", "hook", "hoop skirt", "gymnastic horizontal bar", + "horse-drawn vehicle", "hourglass", "iPod", "clothes iron", "carved pumpkin", "jeans", "jeep", + "T-shirt", "jigsaw puzzle", "rickshaw", "joystick", "kimono", "knee pad", "knot", "lab coat", + "ladle", "lampshade", "laptop computer", "lawn mower", "lens cap", "letter opener", "library", + "lifeboat", "lighter", "limousine", "ocean liner", "lipstick", "slip-on shoe", "lotion", + "music speaker", "loupe magnifying glass", "sawmill", "magnetic compass", "messenger bag", + "mailbox", "tights", "one-piece bathing suit", "manhole cover", "maraca", "marimba", "mask", + "matchstick", "maypole", "maze", "measuring cup", "medicine cabinet", "megalith", "microphone", + "microwave oven", "military uniform", "milk can", "minibus", "miniskirt", "minivan", "missile", + "mitten", "mixing bowl", "mobile home", "ford model t", "modem", "monastery", "monitor", + "moped", "mortar and pestle", "graduation cap", "mosque", "mosquito net", "vespa", + "mountain bike", "tent", "computer mouse", "mousetrap", "moving van", "muzzle", "metal nail", + "neck brace", "necklace", "baby pacifier", "notebook computer", "obelisk", "oboe", "ocarina", + "odometer", "oil filter", "pipe organ", "oscilloscope", "overskirt", "bullock cart", + "oxygen mask", "product packet / packaging", "paddle", "paddle wheel", "padlock", "paintbrush", + "pajamas", "palace", "pan flute", "paper towel", "parachute", "parallel bars", "park bench", + "parking meter", "railroad car", "patio", "payphone", "pedestal", "pencil case", + "pencil sharpener", "perfume", "Petri dish", "photocopier", "plectrum", "Pickelhaube", + "picket fence", "pickup truck", "pier", "piggy bank", "pill bottle", "pillow", "ping-pong ball", + "pinwheel", "pirate ship", "drink pitcher", "block plane", "planetarium", "plastic bag", + "plate rack", "farm plow", "plunger", "Polaroid camera", "pole", "police van", "poncho", + "pool table", "soda bottle", "plant pot", "potter's wheel", "power drill", "prayer rug", + "printer", "prison", "missile", "projector", "hockey puck", "punching bag", "purse", "quill", + "quilt", "race car", "racket", "radiator", "radio", "radio telescope", "rain barrel", + "recreational vehicle", "fishing casting reel", "reflex camera", "refrigerator", + "remote control", "restaurant", "revolver", "rifle", "rocking chair", "rotisserie", "eraser", + "rugby ball", "ruler measuring stick", "sneaker", "safe", "safety pin", "salt shaker", "sandal", + "sarong", "saxophone", "scabbard", "weighing scale", "school bus", "schooner", "scoreboard", + "CRT monitor", "screw", "screwdriver", "seat belt", "sewing machine", "shield", "shoe store", + "shoji screen / room divider", "shopping basket", "shopping cart", "shovel", "shower cap", + "shower curtain", "ski", "balaclava ski mask", "sleeping bag", "slide rule", "sliding door", + "slot machine", "snorkel", "snowmobile", "snowplow", "soap dispenser", "soccer ball", "sock", + "solar thermal collector", "sombrero", "soup bowl", "keyboard space bar", "space heater", + "space shuttle", "spatula", "motorboat", "spider web", "spindle", "sports car", "spotlight", + "stage", "steam locomotive", "through arch bridge", "steel drum", "stethoscope", "scarf", + "stone wall", "stopwatch", "stove", "strainer", "tram", "stretcher", "couch", "stupa", + "submarine", "suit", "sundial", "sunglasses", "sunglasses", "sunscreen", "suspension bridge", + "mop", "sweatshirt", "swim trunks / shorts", "swing", "electrical switch", "syringe", + "table lamp", "tank", "tape player", "teapot", "teddy bear", "television", "tennis ball", + "thatched roof", "front curtain", "thimble", "threshing machine", "throne", "tile roof", + "toaster", "tobacco shop", "toilet seat", "torch", "totem pole", "tow truck", "toy store", + "tractor", "semi-trailer truck", "tray", "trench coat", "tricycle", "trimaran", "tripod", + "triumphal arch", "trolleybus", "trombone", "hot tub", "turnstile", "typewriter keyboard", + "umbrella", "unicycle", "upright piano", "vacuum cleaner", "vase", "vaulted or arched ceiling", + "velvet fabric", "vending machine", "vestment", "viaduct", "violin", "volleyball", + "waffle iron", "wall clock", "wallet", "wardrobe", "military aircraft", "sink", + "washing machine", "water bottle", "water jug", "water tower", "whiskey jug", "whistle", + "hair wig", "window screen", "window shade", "Windsor tie", "wine bottle", "airplane wing", + "wok", "wooden spoon", "wool", "split-rail fence", "shipwreck", "sailboat", "yurt", "website", + "comic book", "crossword", "traffic or street sign", "traffic light", "dust jacket", "menu", + "plate", "guacamole", "consomme", "hot pot", "trifle", "ice cream", "popsicle", "baguette", + "bagel", "pretzel", "cheeseburger", "hot dog", "mashed potatoes", "cabbage", "broccoli", + "cauliflower", "zucchini", "spaghetti squash", "acorn squash", "butternut squash", "cucumber", + "artichoke", "bell pepper", "cardoon", "mushroom", "Granny Smith apple", "strawberry", "orange", + "lemon", "fig", "pineapple", "banana", "jackfruit", "cherimoya (custard apple)", "pomegranate", + "hay", "carbonara", "chocolate syrup", "dough", "meatloaf", "pizza", "pot pie", "burrito", + "red wine", "espresso", "tea cup", "eggnog", "mountain", "bubble", "cliff", "coral reef", + "geyser", "lakeshore", "promontory", "sandbar", "beach", "valley", "volcano", "baseball player", + "bridegroom", "scuba diver", "rapeseed", "daisy", "yellow lady's slipper", "corn", "acorn", + "rose hip", "horse chestnut seed", "coral fungus", "agaric", "gyromitra", "stinkhorn mushroom", + "earth star fungus", "hen of the woods mushroom", "bolete", "corn cob", "toilet paper"] + + +openai_imagenet_template = [ + lambda c: f'a bad photo of a {c}.', + lambda c: f'a photo of many {c}.', + lambda c: f'a sculpture of a {c}.', + lambda c: f'a photo of the hard to see {c}.', + lambda c: f'a low resolution photo of the {c}.', + lambda c: f'a rendering of a {c}.', + lambda c: f'graffiti of a {c}.', + lambda c: f'a bad photo of the {c}.', + lambda c: f'a cropped photo of the {c}.', + lambda c: f'a tattoo of a {c}.', + lambda c: f'the embroidered {c}.', + lambda c: f'a photo of a hard to see {c}.', + lambda c: f'a bright photo of a {c}.', + lambda c: f'a photo of a clean {c}.', + lambda c: f'a photo of a dirty {c}.', + lambda c: f'a dark photo of the {c}.', + lambda c: f'a drawing of a {c}.', + lambda c: f'a photo of my {c}.', + lambda c: f'the plastic {c}.', + lambda c: f'a photo of the cool {c}.', + lambda c: f'a close-up photo of a {c}.', + lambda c: f'a black and white photo of the {c}.', + lambda c: f'a painting of the {c}.', + lambda c: f'a painting of a {c}.', + lambda c: f'a pixelated photo of the {c}.', + lambda c: f'a sculpture of the {c}.', + lambda c: f'a bright photo of the {c}.', + lambda c: f'a cropped photo of a {c}.', + lambda c: f'a plastic {c}.', + lambda c: f'a photo of the dirty {c}.', + lambda c: f'a jpeg corrupted photo of a {c}.', + lambda c: f'a blurry photo of the {c}.', + lambda c: f'a photo of the {c}.', + lambda c: f'a good photo of the {c}.', + lambda c: f'a rendering of the {c}.', + lambda c: f'a {c} in a video game.', + lambda c: f'a photo of one {c}.', + lambda c: f'a doodle of a {c}.', + lambda c: f'a close-up photo of the {c}.', + lambda c: f'a photo of a {c}.', + lambda c: f'the origami {c}.', + lambda c: f'the {c} in a video game.', + lambda c: f'a sketch of a {c}.', + lambda c: f'a doodle of the {c}.', + lambda c: f'a origami {c}.', + lambda c: f'a low resolution photo of a {c}.', + lambda c: f'the toy {c}.', + lambda c: f'a rendition of the {c}.', + lambda c: f'a photo of the clean {c}.', + lambda c: f'a photo of a large {c}.', + lambda c: f'a rendition of a {c}.', + lambda c: f'a photo of a nice {c}.', + lambda c: f'a photo of a weird {c}.', + lambda c: f'a blurry photo of a {c}.', + lambda c: f'a cartoon {c}.', + lambda c: f'art of a {c}.', + lambda c: f'a sketch of the {c}.', + lambda c: f'a embroidered {c}.', + lambda c: f'a pixelated photo of a {c}.', + lambda c: f'itap of the {c}.', + lambda c: f'a jpeg corrupted photo of the {c}.', + lambda c: f'a good photo of a {c}.', + lambda c: f'a plushie {c}.', + lambda c: f'a photo of the nice {c}.', + lambda c: f'a photo of the small {c}.', + lambda c: f'a photo of the weird {c}.', + lambda c: f'the cartoon {c}.', + lambda c: f'art of the {c}.', + lambda c: f'a drawing of the {c}.', + lambda c: f'a photo of the large {c}.', + lambda c: f'a black and white photo of a {c}.', + lambda c: f'the plushie {c}.', + lambda c: f'a dark photo of a {c}.', + lambda c: f'itap of a {c}.', + lambda c: f'graffiti of the {c}.', + lambda c: f'a toy {c}.', + lambda c: f'itap of my {c}.', + lambda c: f'a photo of a cool {c}.', + lambda c: f'a photo of a small {c}.', + lambda c: f'a tattoo of the {c}.', +] diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/tiny_clip/l0module.py b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/tiny_clip/l0module.py new file mode 100644 index 0000000000000000000000000000000000000000..db391563b04810b058e958d1e3093ab8b06f8adb --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/tiny_clip/l0module.py @@ -0,0 +1,368 @@ +# Adapted from https://github.com/princeton-nlp/CoFiPruning/blob/main/models/l0_module.py +# MIT license +import math +import numpy as np + +import torch +import torch.nn as nn +import torch.nn.functional as F + + +class L0Module(nn.Module): + limit_a, limit_b, epsilon = -.1, 1.1, 1e-6 + all_types = ["hidden_z", "heads_z", "mha_z", "intermediate_z", "ffn_z"] + + def __init__(self, config, + start_sparsity=0.0, + target_sparsity=0.0, + lagrangian_warmup=0, + init_loga=0.5, + temperature=2. / 3., + pruning_type=["hidden", "heads", "intermediate", "layer"], + magical_number=0.8, # from Wang et al. 2020 + ): + super(L0Module, self).__init__() + + self.magical_number = magical_number + self.lagrangian_warmup = lagrangian_warmup + + self.pruning_type = pruning_type + self.start_sparsity = start_sparsity + self.target_sparsity = target_sparsity + self.temperature = temperature + + self.hidden_size = config.hidden_size + self.intermediate_size = config.intermediate_size + self.num_attention_heads = config.num_attention_heads + self.dim_per_head = self.hidden_size // self.num_attention_heads + self.num_hidden_layers = config.num_hidden_layers + + self.params_per_head_layer = self.hidden_size * \ + self.hidden_size * 4 + self.hidden_size * 4 + self.params_per_head = self.params_per_head_layer // self.num_attention_heads + + self.params_per_mlp_layer = self.hidden_size * self.intermediate_size * \ + 2 + self.hidden_size + self.intermediate_size + self.params_per_intermediate_dim = self.params_per_mlp_layer // self.intermediate_size + + # we ignore the parameters in normalization layers (it takes a very small amount) + self.full_model_size = ( + self.params_per_head_layer + self.params_per_mlp_layer) * self.num_hidden_layers + self.prunable_model_size = 0 + + init_loga = init_loga if isinstance(init_loga, float) else 0.5 + self.loga_mean = math.log( + 1.0 - self.epsilon - init_loga) - math.log(init_loga + self.epsilon) + + self.types = [] + self.z_logas = {} + self.parameters_per_dim = {} + self.sizes = {} + self.shapes = {} + + self.hidden_loga = None + self.hidden_type = None + + for t in pruning_type: + self.initialize_one_module(t) + + self.lambda_1 = nn.Parameter(torch.tensor(10.00)) + self.lambda_2 = nn.Parameter(torch.tensor(10.00)) + + def initialize_parameters(self, size, num_layer=None, mean=None): + if num_layer is not None: + loga = nn.Parameter(torch.Tensor(num_layer, size)) + else: + loga = nn.Parameter(torch.Tensor(size)) + mean = mean or self.loga_mean + # loga.data.normal_(mean, 1e-2) + loga.data.normal_(mean, 0) + return loga + + def initialize_one_module(self, module_name): + default_mean = 10 + if module_name == "intermediate": + self.intermediate_loga = self.initialize_parameters( + self.intermediate_size, self.num_hidden_layers, mean=default_mean) + self.add_one_module( + self.intermediate_loga, type_name="intermediate", + parameter_per_dim=self.params_per_intermediate_dim, size=self.intermediate_size, + shape=[self.num_hidden_layers, 1, 1, self.intermediate_size] + ) + self.prunable_model_size += self.params_per_mlp_layer * self.num_hidden_layers + elif module_name == "heads": + self.heads_loga = self.initialize_parameters( + self.num_attention_heads, self.num_hidden_layers, mean=default_mean) + self.add_one_module( + self.heads_loga, type_name="heads", + parameter_per_dim=self.params_per_head, size=self.num_attention_heads, + shape=[self.num_hidden_layers, 1, + self.num_attention_heads, 1, 1] + ) + self.prunable_model_size += self.params_per_head * \ + self.num_hidden_layers * self.num_attention_heads + elif module_name == "hidden": + self.hidden_loga = self.initialize_parameters( + self.hidden_size, mean=default_mean) + self.add_one_module( + self.hidden_loga, type_name="hidden", + parameter_per_dim=self.hidden_size * 4 + self.hidden_size * 4 * 2, + size=self.hidden_size, shape=[self.hidden_size] + ) + elif module_name == "layer": + self.ffn_loga = self.initialize_parameters( + self.num_hidden_layers, mean=default_mean) + self.add_one_module( + self.ffn_loga, type_name="ffn", + parameter_per_dim=self.params_per_mlp_layer, size=1, + shape=[self.num_hidden_layers] + ) + self.mha_loga = self.initialize_parameters( + self.num_hidden_layers, mean=default_mean) + self.add_one_module( + self.mha_loga, type_name="mha", + parameter_per_dim=self.params_per_head * self.num_attention_heads, size=1, + shape=[self.num_hidden_layers] + ) + + # ! init the z_logas + def add_one_module(self, z_loga, type_name, parameter_per_dim, size, shape): + self.types.append(type_name) + self.z_logas[type_name] = z_loga + self.parameters_per_dim[type_name] = parameter_per_dim + self.sizes[type_name] = size + self.shapes[type_name] = shape + + def constrain_parameters(self): + for key in self.z_logas: + self.z_logas[key].data.clamp_( + min=math.log(1e-2), max=math.log(1e2)) + + def cdf_qz(self, x, loga): + """Implements the CDF of the 'stretched' concrete distribution""" + xn = (x - self.limit_a) / (self.limit_b - self.limit_a) + logits = math.log(xn) - math.log(1.0 - xn) + return torch.sigmoid(logits * self.temperature - loga).clamp(min=self.epsilon, max=1 - self.epsilon) + + def score_loga(self, loga): + return 1.0 - self.cdf_qz(0.0, loga) + + def get_num_parameters_and_constraint(self, hidden=False): + num_parameters = 0 + + layers = self.num_hidden_layers + hidden_size = self.hidden_size + heads = self.num_attention_heads + device = self.z_logas[self.types[0]].device + # 12 * 1 * 1 + mha_score = self.score_loga(self.mha_loga).view( + -1, 1, 1) if "mha" in self.types else torch.ones([layers, 1, 1]).to(device) + # 12 * 12 * 1 + heads_score = self.score_loga(self.heads_loga).unsqueeze( + dim=-1) if "heads" in self.types else torch.ones([layers, heads, 1]).to(device) + + if "heads" not in self.parameters_per_dim: + self.parameters_per_dim["heads"] = self.params_per_head + if "intermediate" not in self.parameters_per_dim: + self.parameters_per_dim["intermediate"] = self.params_per_intermediate_dim + + if hidden: + hidden_score = self.score_loga( + self.hidden_loga) if "hidden" in self.types else torch.ones([hidden_size]).to(device) + heads_score = ( + heads_score * mha_score) if mha_score is not None else heads_score # 38+106 + heads_score = heads_score.reshape(-1) + num_parameters += torch.outer(hidden_score, heads_score).sum( + ) * self.parameters_per_dim["heads"] / self.hidden_size + else: + heads_score = heads_score * mha_score + num_parameters += heads_score.sum() * \ + self.parameters_per_dim["heads"] + + # 12 * 1 + if 'ffn' in self.types: + ffn_score = self.score_loga(self.ffn_loga).unsqueeze( + dim=-1) if "ffn" in self.types else torch.ones([layers, 1]).to(device) + else: + ffn_score = 1 + # 12 * 3072 + intermediate_score = self.score_loga(self.intermediate_loga) if "intermediate" in self.types else torch.ones([ + layers, hidden_size * 4]).to(device) + + intermediate_score = intermediate_score * ffn_score + + if hidden: + intermediate_score = intermediate_score.reshape(-1) # 13893+22971 + num_parameters += torch.sum(torch.outer(hidden_score, + intermediate_score)) * 2 + else: + num_parameters += intermediate_score.sum() * \ + self.parameters_per_dim["intermediate"] + + return num_parameters + + def get_target_sparsity(self, pruned_steps): + target_sparsity = (self.target_sparsity - self.start_sparsity) * \ + min(1, pruned_steps / self.lagrangian_warmup) + self.start_sparsity + return target_sparsity + + def lagrangian_regularization(self, pruned_steps): + target_sparsity = self.get_target_sparsity( + pruned_steps) if self.lagrangian_warmup > 0 else self.target_sparsity + expect_sparsity = 1 - self.get_num_parameters_and_constraint( + "hidden" in self.types) / self.prunable_model_size + + # lagrangian_loss = ( + # self.lambda_1 * (expect_sparsity - target_sparsity).abs() + + # self.lambda_2 * (expect_sparsity - target_sparsity).square() + # ) + + zero = torch.tensor(0.0, device=expect_sparsity.device) + lagrangian_loss = ( + self.lambda_1 * torch.maximum(target_sparsity - expect_sparsity, zero) + + self.lambda_2 * + torch.maximum(target_sparsity - expect_sparsity, zero).square() + ) + + return lagrangian_loss, expect_sparsity.detach().item(), target_sparsity + + # during training + def _sample_z(self, loga): + # Uniform random numbers for the concrete distribution + u = torch.zeros_like(loga).uniform_(self.epsilon, 1.0 - self.epsilon) + # quantile concrete + z = torch.sigmoid( + (torch.log(u) - torch.log(1 - u) + loga) / self.temperature) + z = z * (self.limit_b - self.limit_a) + self.limit_a + z = F.hardtanh(z, min_val=0.0, max_val=1.0) + return z + + # during inference + def _deterministic_z(self, size, loga, soft=True): + soft_mask = torch.sigmoid( + loga / self.temperature * self.magical_number) + if not soft: + return soft_mask + expected_num_zeros = size - self.score_loga(loga).sum().item() + num_zeros = round(expected_num_zeros) + if num_zeros > 0: + if soft_mask.ndim == 0: + soft_mask = torch.tensor(0).to(loga.device) + else: + _, indices = torch.topk(soft_mask, k=num_zeros, largest=False) + soft_mask[indices] = 0. + return soft_mask + + def get_z_from_zs(self, zs): + numpified_zs = {} + # for t in self.all_types: + # name = t[:-2] + for t in self.types: + name = t + numpified_zs[name] = (zs[t].squeeze().detach().cpu( + ).numpy() > 0) if t in zs else np.ones(self.shapes[name]) + return numpified_zs + + def calculate_model_size(self, zs): + if zs is None: + return {"pruned_sparsity": 0.0} + + layers = self.num_hidden_layers + hidden_size = self.hidden_size + heads = self.num_attention_heads + device = self.z_logas[self.types[0]].device + + numpified_zs = self.get_z_from_zs(zs) + hidden_z = numpified_zs["hidden"] if "hidden" in numpified_zs.keys() else np.ones([ + hidden_size]) + heads_z = numpified_zs["heads"] if "heads" in numpified_zs.keys() else np.ones([ + layers, 1, heads, 1, 1]) + mha_z = numpified_zs["mha"].reshape(-1, 1, 1, 1, 1) if "mha" in numpified_zs.keys( + ) else np.ones([heads_z.shape[0], 1, 1, 1, 1]) + intermediate_z = numpified_zs["intermediate"] if "intermediate" in numpified_zs.keys( + ) else np.ones([layers, 1, 1, hidden_size * 4]) + ffn_z = numpified_zs["ffn"].reshape(-1, 1, 1, 1) if "ffn" in numpified_zs.keys( + ) else np.ones([heads_z.shape[0], 1, 1, 1]) + + remain_hidden = hidden_z.sum().item() + remain_intermediate = intermediate_z.reshape( + self.num_hidden_layers, self.intermediate_size).sum(-1).tolist() + remain_heads = heads_z.reshape( + self.num_hidden_layers, self.num_attention_heads).sum(-1).tolist() + + heads = np.outer((heads_z * mha_z).reshape(-1), hidden_z).sum().item() + intermediate = np.outer( + (intermediate_z * ffn_z).reshape(-1), hidden_z).sum().item() + + remain_model_size = heads * self.dim_per_head * 4 + intermediate * 2 + + pruned_model_size = self.prunable_model_size - remain_model_size + + results = { + 'mha': mha_z.reshape(-1).astype(int).tolist(), + 'ffn': ffn_z.reshape(-1).astype(int).tolist(), + 'remain_hidden': remain_hidden, + 'remain_intermediate': remain_intermediate, + 'remain_heads': remain_heads, + 'pruned_params': pruned_model_size, + 'remain_params': remain_model_size, + 'pruned_sparsity': pruned_model_size / self.prunable_model_size + } + return results + + def forward(self, soft=True): + zs = {f"{t}_z": [] for t in self.types} + + if self.training: + for i, t in enumerate(self.types): + loga = self.z_logas[t] + z = self._sample_z(loga) + zs[f"{t}_z"] = z.reshape(self.shapes[t]) + else: + for i, t in enumerate(self.types): + if t != "hidden": # hidden is not a per layer sample + tmp = [] + for loga in self.z_logas[t]: + z = self._deterministic_z( + self.sizes[t], loga.detach(), soft=soft) + tmp.append(z.reshape(self.shapes[t][1:])) + zs[f"{t}_z"] = torch.stack(tmp) + else: + zs[f"{t}_z"] = self._deterministic_z( + self.sizes[t], self.hidden_loga.detach(), soft=soft) + return zs + + @torch.no_grad() + def l0_mask(self): + zs = {f"{t}_z": [] for t in self.types} + # self.magical_number = 1.0 + + def get_mask(loga): return torch.sigmoid( + loga / self.temperature * self.magical_number) + for t in self.types: + if t == "hidden": + zs[f"{t}_z"] = get_mask(self.hidden_loga) + else: + tmp = [] + loga_all_layers = self.z_logas[t] + for layer in range(len(loga_all_layers)): + loga = loga_all_layers[layer] + z = get_mask(loga) + tmp.append(z.reshape(self.shapes[t][1:])) + zs[f"{t}_z"] = torch.stack(tmp) + return zs + + +if __name__ == '__main__': + from collections import namedtuple + Config = namedtuple('Config', [ + 'hidden_size', 'intermediate_size', 'num_attention_heads', 'num_hidden_layers']) + config = Config(hidden_size=768, intermediate_size=4 * 768, + num_attention_heads=12, num_hidden_layers=12) + l0_module = L0Module(config, lagrangian_warmup=200, target_sparsity=0.5) + l0_module.train() + zs = l0_module() + l0_module.eval() + zs = l0_module() + result = l0_module.calculate_model_size(zs) + print(result) diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/tiny_clip/loss.py b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/tiny_clip/loss.py new file mode 100644 index 0000000000000000000000000000000000000000..05655cf984d4c5d327fb7719951f12646171527d --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/tiny_clip/loss.py @@ -0,0 +1,165 @@ +import torch +import torch.nn as nn +from torch.nn import functional as F + +try: + import torch.distributed.nn + from torch import distributed as dist + has_distributed = True +except ImportError: + has_distributed = False + +try: + import horovod.torch as hvd +except ImportError: + hvd = None + + +def gather_features( + image_features, + text_features, + local_loss=False, + gather_with_grad=False, + rank=0, + world_size=1, + use_horovod=False +): + assert has_distributed, 'torch.distributed did not import correctly, please use a PyTorch version with support.' + if use_horovod: + assert hvd is not None, 'Please install horovod' + if gather_with_grad: + all_image_features = hvd.allgather(image_features) + all_text_features = hvd.allgather(text_features) + else: + with torch.no_grad(): + all_image_features = hvd.allgather(image_features) + all_text_features = hvd.allgather(text_features) + if not local_loss: + # ensure grads for local rank when all_* features don't have a gradient + gathered_image_features = list( + all_image_features.chunk(world_size, dim=0)) + gathered_text_features = list( + all_text_features.chunk(world_size, dim=0)) + gathered_image_features[rank] = image_features + gathered_text_features[rank] = text_features + all_image_features = torch.cat(gathered_image_features, dim=0) + all_text_features = torch.cat(gathered_text_features, dim=0) + else: + # We gather tensors from all gpus + if gather_with_grad: + all_image_features = torch.cat( + torch.distributed.nn.all_gather(image_features), dim=0) + all_text_features = torch.cat( + torch.distributed.nn.all_gather(text_features), dim=0) + else: + gathered_image_features = [torch.zeros_like( + image_features) for _ in range(world_size)] + gathered_text_features = [torch.zeros_like( + text_features) for _ in range(world_size)] + dist.all_gather(gathered_image_features, image_features) + dist.all_gather(gathered_text_features, text_features) + if not local_loss: + # ensure grads for local rank when all_* features don't have a gradient + gathered_image_features[rank] = image_features + gathered_text_features[rank] = text_features + all_image_features = torch.cat(gathered_image_features, dim=0) + all_text_features = torch.cat(gathered_text_features, dim=0) + + return all_image_features, all_text_features + + +def gather_feature( + image_features, + local_loss=False, + gather_with_grad=False, + rank=0, + world_size=1, + use_horovod=False +): + if use_horovod: + assert hvd is not None, 'Please install horovod' + if gather_with_grad: + all_image_features = hvd.allgather(image_features) + else: + with torch.no_grad(): + all_image_features = hvd.allgather(image_features) + if not local_loss: + # ensure grads for local rank when all_* features don't have a gradient + gathered_image_features = list( + all_image_features.chunk(world_size, dim=0)) + gathered_image_features[rank] = image_features + all_image_features = torch.cat(gathered_image_features, dim=0) + else: + # We gather tensors from all gpus + if gather_with_grad: + all_image_features = torch.cat( + torch.distributed.nn.all_gather(image_features), dim=0) + else: + gathered_image_features = [torch.zeros_like( + image_features) for _ in range(world_size)] + dist.all_gather(gathered_image_features, image_features) + if not local_loss: + # ensure grads for local rank when all_* features don't have a gradient + gathered_image_features[rank] = image_features + all_image_features = torch.cat(gathered_image_features, dim=0) + + return all_image_features + + +class ClipLoss(nn.Module): + + def __init__( + self, + local_loss=False, + gather_with_grad=False, + cache_labels=False, + rank=0, + world_size=1, + use_horovod=False, + ): + super().__init__() + self.local_loss = local_loss + self.gather_with_grad = gather_with_grad + self.cache_labels = cache_labels + self.rank = rank + self.world_size = world_size + self.use_horovod = use_horovod + + # cache state + self.prev_num_logits = 0 + self.labels = {} + + def forward(self, image_features, text_features, logit_scale): + device = image_features.device + if self.world_size > 1: + all_image_features, all_text_features = gather_features( + image_features, text_features, + self.local_loss, self.gather_with_grad, self.rank, self.world_size, self.use_horovod) + + if self.local_loss: + logits_per_image = logit_scale * image_features @ all_text_features.T + logits_per_text = logit_scale * text_features @ all_image_features.T + else: + logits_per_image = logit_scale * all_image_features @ all_text_features.T + logits_per_text = logits_per_image.T + else: + logits_per_image = logit_scale * image_features @ text_features.T + logits_per_text = logit_scale * text_features @ image_features.T + + # calculated ground-truth and cache if enabled + num_logits = logits_per_image.shape[0] + if self.prev_num_logits != num_logits or device not in self.labels: + labels = torch.arange(num_logits, device=device, dtype=torch.long) + if self.world_size > 1 and self.local_loss: + labels = labels + num_logits * self.rank + if self.cache_labels: + self.labels[device] = labels + self.prev_num_logits = num_logits + else: + labels = self.labels[device] + + total_loss = ( + F.cross_entropy(logits_per_image, labels) + + F.cross_entropy(logits_per_text, labels) + ) / 2 + return total_loss diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/tiny_clip/model.py b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/tiny_clip/model.py new file mode 100644 index 0000000000000000000000000000000000000000..77988bff2d8a77a9df0ee4fe3627c4865d9abac9 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/tiny_clip/model.py @@ -0,0 +1,2695 @@ +"""CLIP Model + +Adapted from https://github.com/openai/CLIP. Originally MIT License, Copyright (c) 2021 OpenAI. +""" + +import functools +import inspect +from copy import deepcopy +import os +import random +import copy +from contextlib import nullcontext +from argparse import Namespace + +from dataclasses import dataclass +import functools +import logging +import math +from typing import Tuple, Union, Callable, Optional +from torchvision.ops import roi_align +import numpy as np +import torch +import torch.nn.functional as F +from torch import nn +from torch.utils.checkpoint import checkpoint + +# apply the non-reentrant variant of checkpoint +if "use_reentrant" in inspect.signature(checkpoint).parameters: + checkpoint = functools.partial(checkpoint, use_reentrant=False) + +from .timm_model import TimmModel +from .utils import freeze_batch_norm_2d, to_2tuple +from .resnet import ModifiedResNet +from .l0module import L0Module + + +def load_state_dict(model, state_dict): + model.load_state_dict(state_dict, strict=True) + + +class LayerNorm(nn.LayerNorm): + """Subclass torch's LayerNorm to handle fp16.""" + + def forward(self, x: torch.Tensor, hidden_z=None): + """ + x: (N, L, C) + hidden_z: (C,) + """ + self.hidden_z = hidden_z + orig_type = x.dtype + + if hidden_z is None: + x = F.layer_norm(x, self.normalized_shape, self.weight, self.bias, self.eps) + else: + assert len(self.normalized_shape) == 1 + # [TODO] weighted layer norm + remaining_index = torch.where(hidden_z != 0)[0] + compressed_input = torch.index_select(x, dim=-1, index=remaining_index) + compressed_weight = self.weight[remaining_index] + compressed_bias = self.bias[remaining_index] + normalized_shape = len(remaining_index) + normed_input = F.layer_norm( + compressed_input, + [normalized_shape], + compressed_weight, + compressed_bias, + self.eps, + ) + x = x.new_zeros(x.shape) + x[..., remaining_index] = normed_input.to(orig_type) + + return x.to(orig_type) + + def prune(self): + if self.hidden_z is None: + return self + hidden_z = self.hidden_z + assert len(self.normalized_shape) == 1 + remaining_index = torch.where(hidden_z != 0)[0] + compressed_weight = self.weight[remaining_index] + compressed_bias = self.bias[remaining_index] + # m = self + m = LayerNorm(remaining_index.shape[0]).to(self.weight.device) + m.normalized_shape = (len(remaining_index),) + m.weight.data = compressed_weight.contiguous() + m.bias.data = compressed_bias.contiguous() + return m + + def prune_mul_hidden(self): + if self.hidden_z is None: + return self + hidden_z = self.hidden_z + assert len(self.normalized_shape) == 1 + remaining_index = torch.where(hidden_z != 0)[0] + compressed_weight = self.weight[remaining_index] * hidden_z[remaining_index] + compressed_bias = self.bias[remaining_index] * hidden_z[remaining_index] + m = self + m.normalized_shape = (len(remaining_index),) + m.weight.data = compressed_weight.contiguous() + m.bias.data = compressed_bias.contiguous() + return m + + +class QuickGELU(nn.Module): + # NOTE This is slower than nn.GELU or nn.SiLU and uses more GPU memory + def forward(self, x: torch.Tensor): + return x * torch.sigmoid(1.702 * x) + + +class Mlp(nn.Module): + def __init__(self, d_model, mlp_width, act_layer=nn.GELU, scale_fc=False): + super().__init__() + self.d_model = d_model + self.mlp_width = mlp_width + self.c_fc = nn.Linear(d_model, mlp_width) + assert not scale_fc + # self.ln = LayerNorm(mlp_width) if scale_fc else nn.Identity() + self.act_layer = act_layer + self.scale_fc = scale_fc + self.gelu = act_layer() + self.c_proj = nn.Linear(mlp_width, d_model) + + def forward(self, x, hidden_z=None, intermediate_z=None): + """ + x: (N, L, C) + intermediate_z: (mlp_width,) or (1, 1, mlp_width) + hidden_z: (embed_dim,) or (1, 1, embed_dim) + """ + self.hidden_z = hidden_z + self.intermediate_z = intermediate_z + + x = self.c_fc(x) + x = self.gelu(x) + if intermediate_z is not None: + x = torch.mul(x, intermediate_z) + x = self.c_proj(x) + if hidden_z is not None: + x = torch.mul(x, hidden_z) + return x + + def prune(self): + device = self.c_fc.weight.device + if self.hidden_z is None: + self.hidden_z = torch.ones((self.d_model,), dtype=torch.bool, device=device) + if self.intermediate_z is None: + self.intermediate_z = torch.ones( + (self.mlp_width,), dtype=torch.bool, device=device + ) + hidden_r = torch.where(self.hidden_z != 0)[0] + intermediate_r = torch.where(self.intermediate_z != 0)[0] + d_model = len(hidden_r) + mlp_width = len(intermediate_r) + # m = self + m = copy.deepcopy(self) + m.c_fc = nn.Linear(hidden_r.shape[0], intermediate_r.shape[0]) + m.c_proj = nn.Linear(intermediate_r.shape[0], hidden_r.shape[0]) + m.d_model = d_model + m.mlp_width = mlp_width + m.c_fc.weight = nn.Parameter( + (self.c_fc.weight[intermediate_r][:, hidden_r]).contiguous() + ) + m.c_fc.bias = nn.Parameter((self.c_fc.bias[intermediate_r]).contiguous()) + + m.c_proj.weight = nn.Parameter( + ( + ( + self.c_proj.weight + * self.intermediate_z.view(1, -1) + * self.hidden_z.view(-1, 1) + )[hidden_r][:, intermediate_r] + ).contiguous() + ) + m.c_proj.bias = nn.Parameter( + ((self.c_proj.bias * self.hidden_z)[hidden_r]).contiguous() + ) + return m + + +class MultiheadAttention(nn.MultiheadAttention): + def prune(self): + device = self.in_proj_weight.device + if self.hidden_z is None: + self.hidden_z = torch.ones( + (self.embed_dim,), dtype=torch.bool, device=device + ) + if self.head_z is None: + self.head_z = torch.ones((self.num_heads,), dtype=torch.bool, device=device) + hidden_r = torch.where(self.hidden_z != 0)[0] + head_r = torch.where(self.head_z != 0)[0] + d_model = len(hidden_r) + d_head = len(head_r) + org_num_heads = self.num_heads + org_head_dim = self.head_dim + org_embed_dim = self.embed_dim + mod = self + mod.use_naive_compute = True + mod.embed_dim = d_model + mod.head_dim = self.head_dim + mod.num_heads = d_head + inter_dim = d_head * self.head_dim + mod.in_proj_weight = nn.Parameter( + self.in_proj_weight.view(3, org_num_heads, org_head_dim, org_embed_dim)[ + :, head_r + ][..., hidden_r].reshape(-1, d_model) + ) + if self.in_proj_bias is not None: + mod.in_proj_bias = nn.Parameter( + self.in_proj_bias.view(3, org_num_heads, org_head_dim)[ + :, head_r + ].reshape(-1) + ) + mod.out_proj.weight = nn.Parameter( + ( + (self.out_proj.weight * self.hidden_z.view(-1, 1)).view( + org_embed_dim, org_num_heads, org_head_dim + ) + * self.head_z.view(1, org_num_heads, 1) + )[hidden_r][:, head_r].reshape(d_model, -1) + ) + if self.out_proj.bias is not None: + mod.out_proj.bias = nn.Parameter( + ( + self.out_proj.bias + * self.hidden_z.view( + -1, + ) + ) + .view(org_embed_dim)[hidden_r] + .reshape(-1) + ) + return mod + + +class ResidualAttentionBlock(nn.Module): + def __init__( + self, + d_model: int, + n_head: int, + mlp_ratio: float = 4.0, + act_layer: Callable = nn.GELU, + scale_cosine_attn: bool = False, + scale_heads: bool = False, + scale_attn: bool = False, + scale_fc: bool = False, + ): + super().__init__() + + self.ln_1 = LayerNorm(d_model) + # FIXME torchscript issues need to be resolved for custom attention + # if scale_cosine_attn or scale_heads: + # self.attn = Attention( + # d_model, n_head, + # scaled_cosine=scale_cosine_attn, + # scale_heads=scale_heads, + # ) + self.attn = MultiheadAttention(d_model, n_head) + assert not scale_attn + self.ln_attn = LayerNorm(d_model) if scale_attn else nn.Identity() + + self.ln_2 = LayerNorm(d_model) + mlp_width = int(d_model * mlp_ratio) + self.mlp = Mlp(d_model, mlp_width, act_layer, scale_fc) + + def attention( + self, + x: torch.Tensor, + attn_mask: Optional[torch.Tensor] = None, + *, + head_z: Optional[torch.Tensor] = None, + hidden_z: Optional[torch.Tensor] = None, + ): + + self.attn.head_z = head_z + self.attn.hidden_z = hidden_z + + if ( + head_z is None + and hidden_z is None + and not getattr(self.attn, "use_naive_compute", False) + ): + return self.attn(x, x, x, need_weights=False, attn_mask=attn_mask)[0] + else: + # the following code does not support `attn_mask` + # x: (length, batch_size, embed_dim) + n_head = self.attn.num_heads + length, batch_size, d_model = x.shape + ws = self.attn.in_proj_weight.chunk(3) + bs = self.attn.in_proj_bias.chunk(3) + dim_per_head = len(ws[0]) // n_head + # (length, batch_size, n_head * dim_per_head) + q, k, v = [F.linear(x, w, b) for w, b in zip(ws, bs)] + # (batch_size * n_head, length, d_head) + q = q.reshape(length, batch_size * n_head, -1).transpose(0, 1) + k = k.reshape(length, batch_size * n_head, -1).transpose(0, 1) + v = v.reshape(length, batch_size * n_head, -1).transpose(0, 1) + scale = dim_per_head**-0.5 + q *= scale + # (batch_size * n_head, length, length) + sim = q @ k.transpose(1, 2) + if attn_mask is not None: + sim += attn_mask + sim = torch.softmax(sim, -1) + # (batch_size * n_head, length, head_dim) + out = sim @ v + if head_z is not None: + out = out.view(batch_size, n_head, length, dim_per_head) + # head_z: (1, n_head, 1, 1) + out *= head_z.view(1, -1, 1, 1) + out = out.view(batch_size * n_head, length, dim_per_head) + out = out.transpose(0, 1).reshape(length, batch_size, -1) + out = F.linear(out, self.attn.out_proj.weight, self.attn.out_proj.bias) + if hidden_z is not None: + out = torch.mul(out, hidden_z) + return out + + def forward( + self, + x: torch.Tensor, + attn_mask: Optional[torch.Tensor] = None, + hidden_z: Optional[torch.Tensor] = None, + heads_z: Optional[torch.Tensor] = None, + mha_z: Optional[torch.Tensor] = None, + intermediate_z: Optional[torch.Tensor] = None, + ffn_z: Optional[torch.Tensor] = None, + ): + + self.hidden_z = hidden_z + self.heads_z = heads_z + self.mha_z = mha_z + self.intermediate_z = intermediate_z + self.ffn_z = ffn_z + + # x: (length, batch_size, embed_dim) e.g. 50, 128, 768 for vision + if self.attention is not None: + attn_out = self.attention( + self.ln_1(x, hidden_z=hidden_z), + attn_mask=attn_mask, + head_z=heads_z, + hidden_z=hidden_z, + ) + if mha_z is not None: # a number + attn_out = attn_out.mul(mha_z) + x = x + attn_out + if self.mlp is not None: + ln_2_out = self.ln_2(x, hidden_z=hidden_z) + + mlp_out = self.mlp( + ln_2_out, intermediate_z=intermediate_z, hidden_z=hidden_z + ) + if ffn_z is not None: # a number + mlp_out = mlp_out.mul(ffn_z) + x = x + mlp_out + return x + + def proj_without_attn(self, value, hidden_z=None, mha_z=None): + """ + Project without attention computation (maskclip style). + Directly use value projection, skipping attention computation. + """ + attn_module = self.attn + # Get value projection from in_proj_weight and in_proj_bias + # in_proj_weight is (3*embed_dim, embed_dim), we need the last third (value part) + embed_dim = attn_module.embed_dim + v_weight = attn_module.in_proj_weight[2 * embed_dim:, :] + v_bias = ( + attn_module.in_proj_bias[2 * embed_dim:] + if attn_module.in_proj_bias is not None + else None + ) + value = F.linear(value, v_weight, bias=v_bias) + value = F.linear(value, attn_module.out_proj.weight, bias=attn_module.out_proj.bias) + + # Apply hidden mask and mha_z if needed + if hidden_z is not None: + value = torch.mul(value, hidden_z) + if mha_z is not None: + value = value.mul(mha_z) + + return value + + def forward_without_attn( + self, + q_x, + hidden_z=None, + mha_z=None, + intermediate_z=None, + ffn_z=None, + ): + """ + Forward without attention computation (maskclip style). + Uses proj_without_attn to skip attention, then applies residual connection and MLP. + """ + # Apply LayerNorm and project without attention + ln_1_out = self.ln_1(q_x, hidden_z=hidden_z) + attn_out = self.proj_without_attn(ln_1_out, hidden_z=hidden_z, mha_z=mha_z) + # Residual connection: x = x + attn_out + x = q_x + attn_out + + # Apply MLP with residual connection + if self.mlp is not None: + ln_2_out = self.ln_2(x, hidden_z=hidden_z) + mlp_out = self.mlp(ln_2_out, intermediate_z=intermediate_z, hidden_z=hidden_z) + if ffn_z is not None: + mlp_out = mlp_out.mul(ffn_z) + x = x + mlp_out + + return x + + def prune(self): + mod = self + if (self.mha_z is not None and self.mha_z.item() == 0) or ( + self.heads_z + ).sum() == 0: + mod.ln_1 = None + mod.attn = None + mod.attention = None + else: + mod.ln_1 = mod.ln_1.prune() + mod.attn = mod.attn.prune() + if self.mha_z is not None: + mod.attn.out_proj.weight.data *= self.mha_z + mod.attn.out_proj.bias.data *= self.mha_z + + if self.ffn_z is not None and self.ffn_z.item() == 0: + mod.ln_2 = None + mod.mlp = None + else: + mod.ln_2 = mod.ln_2.prune() + mod.mlp = mod.mlp.prune() + if self.ffn_z is not None: + mod.mlp.c_proj.weight.data *= self.ffn_z + mod.mlp.c_proj.bias.data *= self.ffn_z + return mod + + def csa_attn(self, x, mode, hidden_z=None, heads_z=None, mha_z=None): + """ + Cross-Self Attention: uses both q@q and k@k attention. + """ + x = self.ln_1(x, hidden_z=hidden_z) + attn_layer = self.attn + + # Set attention masks + attn_layer.head_z = heads_z + attn_layer.hidden_z = hidden_z + + num_heads = attn_layer.num_heads + length, bsz, embed_dim = x.size() + head_dim = embed_dim // num_heads + scale = head_dim**-0.5 + + # Get q, k, v + ws = attn_layer.in_proj_weight.chunk(3) + bs = ( + attn_layer.in_proj_bias.chunk(3) + if attn_layer.in_proj_bias is not None + else (None, None, None) + ) + q, k, v = [F.linear(x, w, b) for w, b in zip(ws, bs)] + + # Reshape for multi-head attention + q = q.reshape(length, bsz * num_heads, head_dim).transpose( + 0, 1 + ) # (bsz*num_heads, length, head_dim) + k = k.reshape(length, bsz * num_heads, head_dim).transpose(0, 1) + v = v.reshape(length, bsz * num_heads, head_dim).transpose(0, 1) + + # Compute q@q and k@k attention + q_attn = torch.bmm(q, q.transpose(1, 2)) * scale + k_attn = torch.bmm(k, k.transpose(1, 2)) * scale + attn_weights = F.softmax(q_attn, dim=-1) + F.softmax(k_attn, dim=-1) + + # Apply attention to values + attn_output = torch.bmm(attn_weights, v) + # Apply head mask if needed + if heads_z is not None: + attn_output = attn_output.view(bsz, num_heads, length, head_dim) + attn_output = attn_output * heads_z.view(1, -1, 1, 1) + attn_output = attn_output.view(bsz * num_heads, length, head_dim) + # Reshape back + attn_output = attn_output.transpose(0, 1).reshape(length, bsz, embed_dim) + + # Apply output projection + attn_output = F.linear( + attn_output, attn_layer.out_proj.weight, attn_layer.out_proj.bias + ) + + # Apply hidden mask and mha_z if needed + if hidden_z is not None: + attn_output = torch.mul(attn_output, hidden_z) + if mha_z is not None: + attn_output = attn_output.mul(mha_z) + + if "distill" in mode: + # Return attention output and extra features (q, k excluding class token) + return attn_output, (q[:, 1:], k[:, 1:]) + else: + return attn_output + + def csa_raw_attn( + self, + x, + mode, + hidden_z=None, + heads_z=None, + mha_z=None, + intermediate_z=None, + ffn_z=None, + ): + """ + Cross-Self Attention with residual connection and MLP: uses both q@q and k@k attention, + then applies residual connection, LayerNorm, MLP, and another residual connection. + This is for ablation study using raw weights. + + This implementation is equivalent to open_clip's sclip_attn when ls_init_value=None + (i.e., when LayerScale is not used). The main difference is that this version + supports additional pruning/masking parameters (hidden_z, heads_z, mha_z, etc.) + for TinyCLIP's pruning functionality. + """ + # Store original x for residual connection + x_orig = x + + # Apply LayerNorm and compute CSA attention + x = self.ln_1(x, hidden_z=hidden_z) + attn_layer = self.attn + + # Set attention masks + attn_layer.head_z = heads_z + attn_layer.hidden_z = hidden_z + + num_heads = attn_layer.num_heads + length, bsz, embed_dim = x.size() + head_dim = embed_dim // num_heads + scale = head_dim**-0.5 + + # Get q, k, v + ws = attn_layer.in_proj_weight.chunk(3) + bs = ( + attn_layer.in_proj_bias.chunk(3) + if attn_layer.in_proj_bias is not None + else (None, None, None) + ) + q, k, v = [F.linear(x, w, b) for w, b in zip(ws, bs)] + + # Reshape for multi-head attention + q = q.reshape(length, bsz * num_heads, head_dim).transpose( + 0, 1 + ) # (bsz*num_heads, length, head_dim) + k = k.reshape(length, bsz * num_heads, head_dim).transpose(0, 1) + v = v.reshape(length, bsz * num_heads, head_dim).transpose(0, 1) + + # Compute q@q and k@k attention + q_attn = torch.bmm(q, q.transpose(1, 2)) # scale + k_attn = torch.bmm(k, k.transpose(1, 2)) # scale + attn_weights = F.softmax(q_attn, dim=-1) + F.softmax(k_attn, dim=-1) + + # Apply attention to values + attn_output = torch.bmm(attn_weights, v) + # Apply head mask if needed + if heads_z is not None: + attn_output = attn_output.view(bsz, num_heads, length, head_dim) + attn_output = attn_output * heads_z.view(1, -1, 1, 1) + attn_output = attn_output.view(bsz * num_heads, length, head_dim) + # Reshape back + attn_output = attn_output.transpose(0, 1).reshape(length, bsz, embed_dim) + + # Apply output projection + attn_output = F.linear( + attn_output, attn_layer.out_proj.weight, attn_layer.out_proj.bias + ) + + # Apply hidden mask and mha_z if needed + if hidden_z is not None: + attn_output = torch.mul(attn_output, hidden_z) + if mha_z is not None: + attn_output = attn_output.mul(mha_z) + + # Residual connection: x = x_orig + attn_output + x = x_orig + attn_output + + # Apply MLP with residual connection + if self.mlp is not None: + ln_2_out = self.ln_2(x, hidden_z=hidden_z) + mlp_out = self.mlp( + ln_2_out, intermediate_z=intermediate_z, hidden_z=hidden_z + ) + if ffn_z is not None: # a number + mlp_out = mlp_out.mul(ffn_z) + x = x + mlp_out + + return x + + def ss_attn(self, x, mode, hidden_z=None, heads_z=None, mha_z=None): + """ + Self-Self Attention: uses either q@q or k@k attention based on mode. + """ + x = self.ln_1(x, hidden_z=hidden_z) + attn_layer = self.attn + + # Set attention masks + attn_layer.head_z = heads_z + attn_layer.hidden_z = hidden_z + + num_heads = attn_layer.num_heads + length, bsz, embed_dim = x.size() + head_dim = embed_dim // num_heads + scale = head_dim**-0.5 + + # Get q, k, v + ws = attn_layer.in_proj_weight.chunk(3) + bs = ( + attn_layer.in_proj_bias.chunk(3) + if attn_layer.in_proj_bias is not None + else (None, None, None) + ) + q, k, v = [F.linear(x, w, b) for w, b in zip(ws, bs)] + + # Reshape for multi-head attention + q = q.reshape(length, bsz * num_heads, head_dim).transpose( + 0, 1 + ) # (bsz*num_heads, length, head_dim) + k = k.reshape(length, bsz * num_heads, head_dim).transpose(0, 1) + v = v.reshape(length, bsz * num_heads, head_dim).transpose(0, 1) + + # Compute attention based on mode + if mode == "qq" or mode == "qq_vfm_distill": + q_attn = torch.bmm(q, q.transpose(1, 2)) * scale + attn_weights = F.softmax(q_attn, dim=-1) + extra_feats = q[:, 1:] if "distill" in mode else None + elif mode == "kk" or mode == "kk_vfm_distill": + k_attn = torch.bmm(k, k.transpose(1, 2)) * scale + attn_weights = F.softmax(k_attn, dim=-1) + extra_feats = k[:, 1:] if "distill" in mode else None + else: + raise NotImplementedError( + f"The mode '{mode}' is not implemented for ss_attn." + ) + + # Apply attention to values + attn_output = torch.bmm(attn_weights, v) + + # Apply head mask if needed + if heads_z is not None: + attn_output = attn_output.view(bsz, num_heads, length, head_dim) + attn_output = attn_output * heads_z.view(1, -1, 1, 1) + attn_output = attn_output.view(bsz * num_heads, length, head_dim) + + # Reshape back + attn_output = attn_output.transpose(0, 1).reshape(length, bsz, embed_dim) + + # Apply output projection + attn_output = F.linear( + attn_output, attn_layer.out_proj.weight, attn_layer.out_proj.bias + ) + + # Apply hidden mask and mha_z if needed + if hidden_z is not None: + attn_output = torch.mul(attn_output, hidden_z) + if mha_z is not None: + attn_output = attn_output.mul(mha_z) + + if "distill" in mode: + return attn_output, extra_feats + else: + return attn_output + + def proxyclip_attn( + self, + x, + ex_feats=None, + beta=1.2, + gamma=3.0, + token_size=(16, 16), + hidden_z=None, + heads_z=None, + mha_z=None, + ): + """ + ProxyCLIP attention: uses external features (from VFM like SAM/DINO) to guide attention. + Similar to proxyclip_impl.py's custom_attn method. + """ + x = self.ln_1(x, hidden_z=hidden_z) + attn_layer = self.attn + + # Set attention masks + attn_layer.head_z = heads_z + attn_layer.hidden_z = hidden_z + + num_heads = attn_layer.num_heads + length, bsz, embed_dim = x.size() + head_dim = embed_dim // num_heads + + # Get q, k, v + ws = attn_layer.in_proj_weight.chunk(3) + bs = ( + attn_layer.in_proj_bias.chunk(3) + if attn_layer.in_proj_bias is not None + else (None, None, None) + ) + q, k, v = [F.linear(x, w, b) for w, b in zip(ws, bs)] + + # Reshape v for multi-head attention (matching proxyclip_impl.py's custom_attn) + v = v.contiguous().view(-1, bsz * num_heads, head_dim).transpose(0, 1) + + # Use external features to compute attention weights + # ProxyCLIP approach: Use VFM features at their original resolution to compute attention, + # then interpolate CLIP's v to match VFM resolution + B, C, H, W = ex_feats.shape # VFM feature spatial resolution + + # Use VFM features at original resolution to compute similarity + q_k = F.normalize(ex_feats.flatten(2, 3), dim=1) # (B, C, H*W) + similarity = torch.einsum("b c m, b c n -> b m n", q_k, q_k) # (B, H*W, H*W) + + # Apply beta and gamma scaling + similarity = (similarity - torch.mean(similarity) * beta) * gamma + similarity[similarity < 0.0] = float("-inf") + + # Expand to multi-head format + mask = similarity.to(q.dtype).unsqueeze(1).repeat(1, num_heads, 1, 1) + mask = mask.reshape(bsz * num_heads, mask.shape[2], mask.shape[3]) + attn_weights = F.softmax(mask, dim=-1) + + # Reshape v to CLIP token_size, then interpolate to VFM resolution (matching ProxyCLIP) + v = v[:, 1:, :].reshape(bsz * num_heads, token_size[0], token_size[1], head_dim).permute( + 0, 3, 1, 2 + ) + v = F.interpolate(v, size=(H, W), mode="bilinear", align_corners=False) + v = v.permute(0, 2, 3, 1).reshape(bsz * num_heads, H * W, head_dim) + + # Apply attention + attn_output = torch.bmm(attn_weights, v) + + # Apply head mask if needed + if heads_z is not None: + attn_output = attn_output.view(bsz, num_heads, H * W, head_dim) + attn_output = attn_output * heads_z.view(1, -1, 1, 1) + attn_output = attn_output.view(bsz * num_heads, H * W, head_dim) + + # Reshape back (excluding class token, output at VFM resolution matching ProxyCLIP's custom_attn) + attn_output = attn_output.transpose(0, 1).contiguous().view(H * W, bsz, embed_dim) + + # Apply output projection + attn_output = F.linear( + attn_output, attn_layer.out_proj.weight, attn_layer.out_proj.bias + ) + + # Apply hidden mask and mha_z if needed + if hidden_z is not None: + attn_output = torch.mul(attn_output, hidden_z) + if mha_z is not None: + attn_output = attn_output.mul(mha_z) + + return attn_output + + def forward_with_proxyclip( + self, + x, + ex_feats=None, + beta=1.2, + gamma=3.0, + token_size=(16, 16), + hidden_z=None, + heads_z=None, + mha_z=None, + intermediate_z=None, + ffn_z=None, + ): + """ + Forward with ProxyCLIP attention: uses proxyclip_attn, then applies residual connection and MLP. + This matches ProxyCLIP's behavior where custom_attn is used in the last block. + """ + x_orig = x + + # Apply ProxyCLIP attention + attn_out = self.proxyclip_attn( + x, + ex_feats=ex_feats, + beta=beta, + gamma=gamma, + token_size=token_size, + hidden_z=hidden_z, + heads_z=heads_z, + mha_z=mha_z, + ) + + # Note: In ProxyCLIP's implementation, custom_attn returns attention output without residual + # The residual connection is handled in the forward method of VisionTransformer + # So we don't add residual here, just return the attention output + x = attn_out + + # Apply MLP with residual connection + if self.mlp is not None: + ln_2_out = self.ln_2(x, hidden_z=hidden_z) + mlp_out = self.mlp( + ln_2_out, intermediate_z=intermediate_z, hidden_z=hidden_z + ) + if ffn_z is not None: + mlp_out = mlp_out.mul(ffn_z) + x = x + mlp_out + + return x + + +class Transformer(nn.Module): + def __init__( + self, + width: int, + layers: int, + heads: int, + mlp_ratio: float = 4.0, + act_layer: Callable = nn.GELU, + ): + super().__init__() + self.width = width + self.layers = layers + self.grad_checkpointing = False + + assert width % heads == 0 + self.head_dim = width // heads + self.num_heads = heads + self.mlp_ratio = mlp_ratio + + self.resblocks = nn.ModuleList( + [ + ResidualAttentionBlock(width, heads, mlp_ratio, act_layer=act_layer) + for _ in range(layers) + ] + ) + + def forward( + self, + x: torch.Tensor, + attn_mask: Optional[torch.Tensor] = None, + hidden_z: Optional[torch.Tensor] = None, + heads_z: Optional[torch.Tensor] = None, + mha_z: Optional[torch.Tensor] = None, + intermediate_z: Optional[torch.Tensor] = None, + ffn_z: Optional[torch.Tensor] = None, + ): + + return self.infer_blocks( + x, + attn_mask, + hidden_z=hidden_z, + heads_z=heads_z, + mha_z=mha_z, + intermediate_z=intermediate_z, + ffn_z=ffn_z, + ) + + def infer_blocks( + self, + x: torch.Tensor, + attn_mask: Optional[torch.Tensor] = None, + block_idxs=None, + hidden_z: Optional[torch.Tensor] = None, + heads_z: Optional[torch.Tensor] = None, + mha_z: Optional[torch.Tensor] = None, + intermediate_z: Optional[torch.Tensor] = None, + ffn_z: Optional[torch.Tensor] = None, + ): + + num_layers = self.layers + if hidden_z is not None: + assert hidden_z.shape == (self.width,) + if heads_z is not None: + if heads_z.ndim == 5: + heads_z = heads_z.view(num_layers, self.num_heads) + assert heads_z.shape in [(num_layers, self.num_heads), (self.num_heads,)], ( + heads_z.shape, + (num_layers, self.num_heads), + ) + if mha_z is not None: + assert mha_z.shape == (num_layers,), mha_z.shape + if intermediate_z is not None: + if intermediate_z.ndim == 4: + intermediate_z = intermediate_z.view(num_layers, -1) + assert intermediate_z.shape in [ + (num_layers, self.mlp_ratio * self.width), + (self.mlp_ratio * self.width,), + ], intermediate_z.shape + if ffn_z is not None: + assert ffn_z.shape == (num_layers,), ffn_z.shape + + def _get_zi(z, i, ndim=2): + if z is None: + return None + if z.ndim == ndim: + return z[i] + return z + + block_idxs = block_idxs or list(range(self.layers)) + for i in block_idxs: + r = self.resblocks[i] + + if self.grad_checkpointing and not torch.jit.is_scripting(): + x = checkpoint( + r, + x, + attn_mask, + hidden_z, + _get_zi(heads_z, i), + _get_zi(mha_z, i, ndim=1), + _get_zi(intermediate_z, i), + _get_zi(ffn_z, i, ndim=1), + ) + else: + x = r( + x, + attn_mask=attn_mask, + hidden_z=hidden_z, + heads_z=_get_zi(heads_z, i), + mha_z=_get_zi(mha_z, i, ndim=1), + intermediate_z=_get_zi(intermediate_z, i), + ffn_z=_get_zi(ffn_z, i, ndim=1), + ) + + return x + + @torch.jit.ignore + def set_grad_checkpointing(self, enable=True): + self.grad_checkpointing = enable + + def extra_repr(self): + return f"grad_checkpointing={self.grad_checkpointing}" + + def prune(self): + mod = self + for i in range(len(self.resblocks)): + self.resblocks[i] = self.resblocks[i].prune() + return mod + + def extract_feature_map( + self, + x, + mode="vanilla", + hidden_z=None, + heads_z=None, + mha_z=None, + intermediate_z=None, + ffn_z=None, + ex_feats=None, + beta=1.2, + gamma=3.0, + token_size=(16, 16), + ): + """ + Extract feature map from transformer, supporting different modes. + Supports vanilla, qq, kk, csa, csa_raw, maskclip, clearclip, proxyclip, and their distill variants. + """ + + def _get_zi(z, i, ndim=2): + """Helper function to get z value for layer i""" + if z is None: + return None + if z.ndim == ndim: + return z[i] + return z + + # Process all layers except the last one + for i in range(self.layers - 1): + r = self.resblocks[i] + x = r( + x, + attn_mask=None, + hidden_z=hidden_z, + heads_z=_get_zi(heads_z, i) if heads_z is not None else None, + mha_z=_get_zi(mha_z, i, ndim=1) if mha_z is not None else None, + intermediate_z=( + _get_zi(intermediate_z, i) if intermediate_z is not None else None + ), + ffn_z=_get_zi(ffn_z, i, ndim=1) if ffn_z is not None else None, + ) + + # Process the last layer based on mode + r = self.resblocks[-1] + last_heads_z = ( + _get_zi(heads_z, self.layers - 1) if heads_z is not None else None + ) + last_mha_z = ( + _get_zi(mha_z, self.layers - 1, ndim=1) if mha_z is not None else None + ) + last_intermediate_z = ( + _get_zi(intermediate_z, self.layers - 1) + if intermediate_z is not None + else None + ) + last_ffn_z = ( + _get_zi(ffn_z, self.layers - 1, ndim=1) if ffn_z is not None else None + ) + + if mode == "vanilla": + x = r( + x, + attn_mask=None, + hidden_z=hidden_z, + heads_z=last_heads_z, + mha_z=last_mha_z, + intermediate_z=last_intermediate_z, + ffn_z=last_ffn_z, + ) + return x + elif mode in ["csa", "csa_vfm_distill"]: + # For csa mode, only return attention output without residual connection and MLP + # This matches EVA CLIP's forward_without_rcffn behavior + result = r.csa_attn( + x, mode, hidden_z=hidden_z, heads_z=last_heads_z, mha_z=last_mha_z + ) + if "distill" in mode: + return result[0], result[1] # attn_out, extra_feats + else: + return result # attn_out only + elif mode == "csa_raw": + # For csa_raw mode, use CSA attention with residual connection and MLP + # This is for ablation study using raw weights + x = r.csa_raw_attn( + x, + mode, + hidden_z=hidden_z, + heads_z=last_heads_z, + mha_z=last_mha_z, + intermediate_z=last_intermediate_z, + ffn_z=last_ffn_z, + ) + return x + elif mode in ["qq", "kk", "qq_vfm_distill", "kk_vfm_distill"]: + # For qq/kk mode, only return attention output without residual connection and MLP + # This matches EVA CLIP's forward_without_rcffn behavior + result = r.ss_attn( + x, mode, hidden_z=hidden_z, heads_z=last_heads_z, mha_z=last_mha_z + ) + if "distill" in mode: + return result[0], result[1] # attn_out, extra_feats + else: + return result # attn_out only + elif mode == "maskclip": + # For maskclip mode, use forward_without_attn: skip attention computation, + # directly use value projection, then apply residual connection and MLP + x = r.forward_without_attn( + x, + hidden_z=hidden_z, + mha_z=last_mha_z, + intermediate_z=last_intermediate_z, + ffn_z=last_ffn_z, + ) + return x + elif mode == "clearclip": + # For clearclip mode, use qq attention in the last block, + # without residual connection, second LayerNorm, and MLP + # This is for ablation study: only qq attention, no residual, no ln_2, no MLP + result = r.ss_attn( + x, mode="qq", hidden_z=hidden_z, heads_z=last_heads_z, mha_z=last_mha_z + ) + return result # attn_out only + elif mode == "proxyclip": + # For proxyclip mode, use external features (from VFM) to guide attention + # Only return attention output without residual connection and MLP + # This matches ProxyCLIP's custom_attn behavior + if ex_feats is None: + raise ValueError("ex_feats must be provided for proxyclip mode") + attn_output = r.proxyclip_attn( + x, + ex_feats=ex_feats, + beta=beta, + gamma=gamma, + token_size=token_size, + hidden_z=hidden_z, + heads_z=last_heads_z, + mha_z=last_mha_z, + ) + # proxyclip_attn returns output at VFM resolution (H*W, bsz, embed_dim) without class token + # This matches ProxyCLIP's custom_attn behavior where output is at VFM resolution + # We return attn_output directly without class token, as it's already at VFM resolution + # The encode_dense method will handle this VFM-resolution output specially + return attn_output + else: + raise NotImplementedError(f"The mode '{mode}' is not implemented.") + + +class VisualTransformer(nn.Module): + def __init__( + self, + image_size: int, + patch_size: int, + width: int, + layers: int, + heads: int, + mlp_ratio: float, + output_dim: int, + act_layer: Callable = nn.GELU, + teacher_width: int = -1, + ): + super().__init__() + self.image_size = to_2tuple(image_size) + self.patch_size = to_2tuple(patch_size) + self.grid_size = ( + self.image_size[0] // self.patch_size[0], + self.image_size[1] // self.patch_size[1], + ) + self.output_dim = output_dim + self.embed_dim = width + self.layers = layers + self.conv1 = nn.Conv2d( + in_channels=3, + out_channels=width, + kernel_size=patch_size, + stride=patch_size, + bias=False, + ) + + scale = width**-0.5 + self.class_embedding = nn.Parameter(scale * torch.randn(width)) + self.positional_embedding = nn.Parameter( + scale * torch.randn(self.grid_size[0] * self.grid_size[1] + 1, width) + ) + self.ln_pre = LayerNorm(width) + + self.transformer = Transformer( + width, layers, heads, mlp_ratio, act_layer=act_layer + ) + self.head_dim = width // heads + + self.ln_post = LayerNorm(width) + # image proj + if teacher_width > 0: + self.proj = nn.Parameter( + torch.empty(teacher_width, output_dim), requires_grad=False + ) + else: + self.proj = nn.Parameter(scale * torch.randn(width, output_dim)) + + def lock(self, unlocked_groups=0, freeze_bn_stats=False): + for param in self.parameters(): + param.requires_grad = False + + def _unlock(x): + if isinstance(x, list): + for g in x: + _unlock(g) + else: + if isinstance(x, torch.nn.Parameter): + x.requires_grad = True + else: + for p in x.parameters(): + p.requires_grad = True + + for blk in self.transformer.resblocks[-unlocked_groups:]: + _unlock(blk) + + if freeze_bn_stats: + freeze_batch_norm_2d(self) + + @torch.jit.ignore + def set_grad_checkpointing(self, enable=True): + self.transformer.set_grad_checkpointing(enable) + + def get_proj_feature(self, x): + if self.proj is not None: + x = x @ self.proj + return x + + def extra_repr(self): + return "image_size={}, output_dim={}".format(self.image_size, self.output_dim) + + def prune(self): + hidden_r = torch.where(self.hidden_z != 0)[0] + self.conv1.weight = nn.Parameter( + (self.conv1.weight.data * self.hidden_z.view(-1, 1, 1, 1))[hidden_r] + ) + if self.conv1.bias is not None: + self.conv1.bias = nn.Parameter( + ( + self.conv1.bias + * self.hidden_z.view( + -1, + ) + )[hidden_r] + ) + self.class_embedding = nn.Parameter( + ( + self.class_embedding + * self.hidden_z.view( + -1, + ) + )[hidden_r] + ) + self.positional_embedding = nn.Parameter( + (self.positional_embedding * self.hidden_z.view(1, -1))[:, hidden_r] + ) + self.ln_pre = self.ln_pre.prune() + self.transformer = self.transformer.prune() + self.ln_post = self.ln_post.prune() + if self.embed_dim_z is not None: + embed_dim_r = self.embed_dim_z > 0 + self.proj = nn.Parameter( + (self.proj * self.hidden_z.view(-1, 1) * self.embed_dim_z.view(1, -1))[ + hidden_r + ][:, embed_dim_r] + ) + else: + self.proj = nn.Parameter((self.proj * self.hidden_z.view(-1, 1))[hidden_r]) + return self + + def forward( + self, + x: torch.Tensor, + hidden_z: Optional[torch.Tensor] = None, + heads_z: Optional[torch.Tensor] = None, + mha_z: Optional[torch.Tensor] = None, + intermediate_z: Optional[torch.Tensor] = None, + ffn_z: Optional[torch.Tensor] = None, + embed_dim_z: Optional[torch.Tensor] = None, + ): + + self.hidden_z = hidden_z + self.embed_dim_z = embed_dim_z + + x = x.to(self.conv1.weight.device) + x = self.conv1(x) # shape = [*, width, grid, grid] + # shape = [*, width, grid ** 2] + x = x.reshape(x.shape[0], x.shape[1], -1) + x = x.permute(0, 2, 1) # shape = [*, grid ** 2, width] + # the first token is the class token. + x = torch.cat( + [ + self.class_embedding.to(x.dtype) + + torch.zeros( + x.shape[0], 1, x.shape[-1], dtype=x.dtype, device=x.device + ), + x, + ], + dim=1, + ) # shape = [*, 1 + grid ** 2, width] + x = x + self.positional_embedding.to(x.dtype) # 128, 50, 768 + + if hidden_z is not None: + x = torch.mul(x, hidden_z) + x = self.ln_pre(x, hidden_z=hidden_z) + + x = x.permute(1, 0, 2) # NLD -> LND 50, 128, 768 + x = self.transformer( + x, + hidden_z=hidden_z, + heads_z=heads_z, + mha_z=mha_z, + intermediate_z=intermediate_z, + ffn_z=ffn_z, + ) + + x = x.permute(1, 0, 2) # LND -> NLD + + # select class token + x = self.ln_post(x[:, 0, :], hidden_z=hidden_z) + + if self.proj is not None: + x = self.get_proj_feature(x) + + return x + + def _global_pool(self, x: torch.Tensor): + """Separate class token and patch tokens.""" + return x[:, 0], x[:, 1:] + + def encode_dense( + self, + x, + keep_shape=False, + mode="vanilla", + hidden_z=None, + heads_z=None, + mha_z=None, + intermediate_z=None, + ffn_z=None, + embed_dim_z=None, + ex_feats=None, + beta=1.2, + gamma=3.0, + ): + """ + Encode dense feature map from images. + Similar to OpenAI CLIP's encode_dense but adapted for TinyCLIP. + For proxyclip mode, ex_feats should be provided from VFM (SAM/DINO/DINOv2). + """ + self.hidden_z = hidden_z + self.embed_dim_z = embed_dim_z + x = x.to(self.conv1.weight.device) + x = self.conv1(x) # shape = [*, width, grid, grid] + bs, _, h, w = x.shape + # shape = [*, width, grid ** 2] + x = x.reshape(x.shape[0], x.shape[1], -1) + x = x.permute(0, 2, 1) # shape = [*, grid ** 2, width] + # the first token is the class token. + x = torch.cat( + [ + self.class_embedding.to(x.dtype) + + torch.zeros( + x.shape[0], 1, x.shape[-1], dtype=x.dtype, device=x.device + ), + x, + ], + dim=1, + ) # shape = [*, 1 + grid ** 2, width] + + # Handle positional embedding + if (h, w) == self.grid_size: + pe = self.positional_embedding.to(x.dtype) + else: + pe = self.rescale_positional_embedding(out_size=(h, w), dtype=x.dtype) + + x = x + pe + + if hidden_z is not None: + x = torch.mul(x, hidden_z) + x = self.ln_pre(x, hidden_z=hidden_z) + + x = x.permute(1, 0, 2) # NLD -> LND + # For TinyCLIP, we support vanilla mode, distill modes, and proxyclip mode + token_size = (h, w) # Store token size for proxyclip mode + if "distill" in mode: + x, extra_feats = self.transformer.extract_feature_map( + x, + mode=mode, + hidden_z=hidden_z, + heads_z=heads_z, + mha_z=mha_z, + intermediate_z=intermediate_z, + ffn_z=ffn_z, + ex_feats=ex_feats, + beta=beta, + gamma=gamma, + token_size=token_size, + ) + else: + x = self.transformer.extract_feature_map( + x, + mode=mode, + hidden_z=hidden_z, + heads_z=heads_z, + mha_z=mha_z, + intermediate_z=intermediate_z, + ffn_z=ffn_z, + ex_feats=ex_feats, + beta=beta, + gamma=gamma, + token_size=token_size, + ) + + x = x.permute(1, 0, 2) # LND -> NLD + + # For proxyclip mode, x is already at VFM resolution without class token + # For other modes, x is at CLIP token_size with class token + if mode == "proxyclip": + # proxyclip mode: x shape is (bs, H*W, embed_dim) where H*W is VFM resolution + # No class token, so we use x directly as tokens + tokens = x + # Get VFM resolution from ex_feats + if ex_feats is not None: + _, _, H_vfm, W_vfm = ex_feats.shape + h_vfm, w_vfm = H_vfm, W_vfm + else: + # Fallback to CLIP token_size if ex_feats is None (shouldn't happen) + h_vfm, w_vfm = h, w + else: + # Other modes: x has class token, use _global_pool to separate + _, tokens = self._global_pool(x) + h_vfm, w_vfm = h, w # Use CLIP token_size for other modes + + tokens = self.ln_post(tokens, hidden_z=hidden_z) + + if self.proj is not None: + tokens = tokens @ self.proj + feature_map = tokens.view(bs, h_vfm * w_vfm, -1) + feature_map = F.normalize(feature_map, dim=-1) + + if keep_shape: + feature_map = feature_map.view(bs, h_vfm, w_vfm, -1).permute(0, 3, 1, 2) + + if "distill" in mode: + return feature_map, extra_feats + else: + return feature_map + + def extract_roi_features( + self, + x, + normed_boxes, + mode="vanilla", + size=(1, 1), + hidden_z=None, + heads_z=None, + mha_z=None, + intermediate_z=None, + ffn_z=None, + embed_dim_z=None, + ): + """ + Extract ROI features from images using normalized boxes. + """ + if mode in ["qq_vfm_distill", "kk_vfm_distill", "csa_vfm_distill"]: + x, extra_feats = self.encode_dense( + x, + keep_shape=True, + mode=mode, + hidden_z=hidden_z, + heads_z=heads_z, + mha_z=mha_z, + intermediate_z=intermediate_z, + ffn_z=ffn_z, + embed_dim_z=embed_dim_z, + ) + boxes = self._denormalize_boxes(normed_boxes, x) + + roi_feats = roi_align( + x, + boxes, + output_size=size, + spatial_scale=1.0, + sampling_ratio=-1, + aligned=True, + ) + if size == (1, 1): + roi_feats = roi_feats[..., 0, 0] + else: + roi_feats = ( + roi_feats.flatten(start_dim=-2).transpose(-2, -1).contiguous() + ) + return roi_feats, extra_feats + else: + x = self.encode_dense( + x, + keep_shape=True, + mode=mode, + hidden_z=hidden_z, + heads_z=heads_z, + mha_z=mha_z, + intermediate_z=intermediate_z, + ffn_z=ffn_z, + embed_dim_z=embed_dim_z, + ) + boxes = self._denormalize_boxes(normed_boxes, x) + roi_feats = roi_align( + x, + boxes, + output_size=size, + spatial_scale=1.0, + sampling_ratio=-1, + aligned=True, + ) + if size == (1, 1): + roi_feats = roi_feats[..., 0, 0] + else: + roi_feats = ( + roi_feats.flatten(start_dim=-2).transpose(-2, -1).contiguous() + ) + return roi_feats + + def mask_pool( + self, + x, + masks, + mode="vanilla", + hidden_z=None, + heads_z=None, + mha_z=None, + intermediate_z=None, + ffn_z=None, + embed_dim_z=None, + ): + """ + Pool features using masks. + """ + feature_map = self.encode_dense( + x, + keep_shape=False, + mode=mode, + hidden_z=hidden_z, + heads_z=heads_z, + mha_z=mha_z, + intermediate_z=intermediate_z, + ffn_z=ffn_z, + embed_dim_z=embed_dim_z, + ) + num_masks_per_image = [len(masks_per_image) for masks_per_image in masks] + masks = torch.cat(masks).float().flatten(-2, -1) # bs, h*w + feature_map = torch.repeat_interleave( + feature_map, + torch.tensor(num_masks_per_image, device=feature_map.device), + dim=0, + ) + features = (feature_map * masks.unsqueeze(-1)).sum(1) / ( + masks.sum(1, keepdim=True) + 1e-12 + ) + return features + + @staticmethod + def _denormalize_boxes(normed_boxes, x): + """ + Denormalize boxes from [0, 1] to pixel coordinates. + """ + h, w = x.shape[-2:] + denormed_boxes = [] + for boxes in normed_boxes: + new_boxes = boxes.clone() # FIXME: do not change the value in normed_boxes! + new_boxes[:, [0, 2]] *= w + new_boxes[:, [1, 3]] *= h + denormed_boxes.append(new_boxes) + return denormed_boxes + + def rescale_positional_embedding(self, out_size, dtype): + """ + Rescale positional embedding to match output size. + """ + h, w = out_size + rescaled_positional_embedding = self.positional_embedding.new_zeros( + 1 + h * w, self.positional_embedding.shape[1] + ) + rescaled_positional_embedding[0] = self.positional_embedding[0] + pe_2d = ( + self.positional_embedding[1:].T.contiguous().view(1, -1, *self.grid_size) + ) + pe_2d = F.interpolate( + pe_2d, out_size, mode="bicubic", align_corners=False + ).view(-1, h * w) + rescaled_positional_embedding[1:] = pe_2d.T.contiguous() + return rescaled_positional_embedding.to(dtype=dtype) + + +@dataclass +class CLIPVisionCfg: + layers: Union[Tuple[int, int, int, int], int] = 12 + width: int = 768 + teacher_width: int = -1 + head_width: int = 64 + mlp_ratio: float = 4.0 + patch_size: int = 16 + image_size: Union[Tuple[int, int], int] = 224 + timm_model_name: str = ( + None # a valid model name overrides layers, width, patch_size + ) + # use (imagenet) pretrained weights for named model + timm_model_pretrained: bool = False + # feature pooling for timm model ('abs_attn', 'rot_attn', 'avg', '') + timm_pool: str = "avg" + # linear projection for timm model output ('linear', 'mlp', '') + timm_proj: str = "linear" + + +@dataclass +class CLIPTextCfg: + context_length: int = 77 + vocab_size: int = 49408 + width: int = 512 + teacher_width: int = -1 + heads: int = 8 + layers: int = 12 + + +class ImageEncoder(nn.Module): + def __init__( + self, embed_dim, vision_cfg, quick_gelu, l0_module_image=False, mask_cfg=None + ): + super().__init__() + act_layer = QuickGELU if quick_gelu else nn.GELU + + if vision_cfg.timm_model_name: + self.visual = TimmModel( + vision_cfg.timm_model_name, + pretrained=vision_cfg.timm_model_pretrained, + pool=vision_cfg.timm_pool, + proj=vision_cfg.timm_proj, + embed_dim=embed_dim, + image_size=vision_cfg.image_size, + ) + act_layer = ( + nn.GELU + ) # so that text transformer doesn't use QuickGELU w/ timm models + elif isinstance(vision_cfg.layers, (tuple, list)): + vision_heads = vision_cfg.width * 32 // vision_cfg.head_width + self.visual = ModifiedResNet( + layers=vision_cfg.layers, + output_dim=embed_dim, + heads=vision_heads, + image_size=vision_cfg.image_size, + width=vision_cfg.width, + ) + else: + vision_heads = vision_cfg.width // vision_cfg.head_width + self.visual = VisualTransformer( + image_size=vision_cfg.image_size, + patch_size=vision_cfg.patch_size, + width=vision_cfg.width, + layers=vision_cfg.layers, + heads=vision_heads, + mlp_ratio=vision_cfg.mlp_ratio, + output_dim=embed_dim, + act_layer=act_layer, + teacher_width=vision_cfg.teacher_width, + ) + self.init_parameters() + + if l0_module_image: + logging.info("use l0_module_vision") + config_mask = Namespace() + config_mask.hidden_size = vision_cfg.width + config_mask.intermediate_size = 4 * vision_cfg.width + config_mask.num_attention_heads = vision_heads + config_mask.num_hidden_layers = vision_cfg.layers + config_mask.sparsity_warmup = mask_cfg.sparsity_warmup + config_mask.sparsity = mask_cfg.sparsity + config_mask.start_sparsity = mask_cfg.start_sparsity + self.l0_module = L0Module( + config_mask, + lagrangian_warmup=config_mask.sparsity_warmup, + start_sparsity=config_mask.start_sparsity, + target_sparsity=config_mask.sparsity, + pruning_type=["hidden", "heads", "intermediate"], + ) + else: + self.l0_module = None + + self.mask = None + + def init_parameters(self): + if hasattr(self.visual, "init_parameters"): + self.visual.init_parameters() + + def forward(self, image, normalized=False, **mask): + + if self.l0_module is not None: + mask = self.l0_module.forward() + + self.mask = mask + + image_features = self.visual(image, **mask) + + embed_dim_z = mask.get("embed_dim_z", None) + if embed_dim_z is not None: + image_features = image_features.mul(embed_dim_z) + + if normalized: + image_features = F.normalize(image_features, dim=-1) + return image_features + + def prune(self): + self.visual = self.visual.prune() + return self + + +class TextEncoder(nn.Module): + def __init__(self, embed_dim, text_cfg, quick_gelu, l0_module_text, mask_cfg=None): + super().__init__() + + act_layer = QuickGELU if quick_gelu else nn.GELU + self.context_length = text_cfg.context_length + + if text_cfg.layers > 0: + self.transformer = Transformer( + width=text_cfg.width, + layers=text_cfg.layers, + heads=text_cfg.heads, + act_layer=act_layer, + ) + else: + self.transformer = None + + self.text_projection = None + if text_cfg.layers > 0: + self.vocab_size = text_cfg.vocab_size + self.token_embedding = nn.Embedding(text_cfg.vocab_size, text_cfg.width) + self.positional_embedding = nn.Parameter( + torch.empty(self.context_length, text_cfg.width) + ) + self.ln_final = LayerNorm(text_cfg.width) + if text_cfg.teacher_width > 0: + self.text_projection = nn.Parameter( + torch.empty(text_cfg.width, embed_dim), requires_grad=False + ) + else: + self.text_projection = nn.Parameter( + torch.empty(text_cfg.width, embed_dim) + ) + self.register_buffer( + "attn_mask", self.build_attention_mask(), persistent=False + ) + else: + self.token_embedding = None + self.init_parameters() + + if l0_module_text: + logging.info("use l0_module_text") + config_mask = Namespace() + config_mask.hidden_size = text_cfg.width + config_mask.intermediate_size = 4 * text_cfg.width + config_mask.num_attention_heads = text_cfg.heads + config_mask.num_hidden_layers = text_cfg.layers + config_mask.sparsity_warmup = mask_cfg.sparsity_warmup + config_mask.sparsity = mask_cfg.sparsity + config_mask.start_sparsity = mask_cfg.start_sparsity + self.l0_module = L0Module( + config_mask, + lagrangian_warmup=config_mask.sparsity_warmup, + start_sparsity=config_mask.start_sparsity, + target_sparsity=config_mask.sparsity, + pruning_type=["hidden", "heads", "intermediate"], + ) + else: + self.l0_module = None + + self.mask = None + + def init_parameters(self): + if self.transformer is not None: + nn.init.normal_(self.token_embedding.weight, std=0.02) + nn.init.normal_(self.positional_embedding, std=0.01) + + proj_std = (self.transformer.width**-0.5) * ( + (2 * self.transformer.layers) ** -0.5 + ) + attn_std = self.transformer.width**-0.5 + fc_std = (2 * self.transformer.width) ** -0.5 + for block in self.transformer.resblocks: + nn.init.normal_(block.attn.in_proj_weight, std=attn_std) + nn.init.normal_(block.attn.out_proj.weight, std=proj_std) + nn.init.normal_(block.mlp.c_fc.weight, std=fc_std) + nn.init.normal_(block.mlp.c_proj.weight, std=proj_std) + + if self.text_projection is not None: + nn.init.normal_(self.text_projection, std=self.transformer.width**-0.5) + + def build_attention_mask(self): + # lazily create causal attention mask, with full attention between the vision tokens + # pytorch uses additive attention mask; fill with -inf + mask = torch.empty(self.context_length, self.context_length) + mask.fill_(float("-inf")) + mask.triu_(1) # zero out the lower diagonal + return mask + + def encode_text( + self, + text, + normalized=False, + hidden_z: Optional[torch.Tensor] = None, + heads_z: Optional[torch.Tensor] = None, + mha_z: Optional[torch.Tensor] = None, + intermediate_z: Optional[torch.Tensor] = None, + ffn_z: Optional[torch.Tensor] = None, + embed_dim_z: Optional[torch.Tensor] = None, + ): + self.hidden_z = hidden_z + self.embed_dim_z = embed_dim_z + + text = text.to(self.token_embedding.weight.device) + x = self.token_embedding(text) # [batch_size, n_ctx, d_model] + + x = x + self.positional_embedding + if hidden_z is not None: + x = torch.mul(x, hidden_z) + + x = x.permute(1, 0, 2) # NLD -> LND + x = self.transformer( + x, + attn_mask=self.attn_mask, + hidden_z=hidden_z, + heads_z=heads_z, + mha_z=mha_z, + intermediate_z=intermediate_z, + ffn_z=ffn_z, + ) + x = x.permute(1, 0, 2) # LND -> NLD + x = self.ln_final(x, hidden_z) + + # if hidden_z is not None: + # x = torch.mul(x, hidden_z) + + x = x[torch.arange(x.shape[0]), text.argmax(dim=-1)] + + # x.shape = [batch_size, n_ctx, transformer.width] + # take features from the eot embedding (eot_token is the highest number in each sequence) + x = self.get_proj_feature(x) + if embed_dim_z is not None: + x = x.mul(embed_dim_z) + if normalized: + x = F.normalize(x, dim=-1) + + return x + + def get_proj_feature(self, x): + return x @ self.text_projection + + def forward(self, text, normalized=False): + mask = dict() + + if self.l0_module is not None: + mask = self.l0_module.forward() + + self.mask = mask + + return self.encode_text(text, normalized=normalized, **mask) + + def prune(self): + device = self.token_embedding.weight.device + if self.hidden_z is None: + self.hidden_z = torch.ones(self.text_projection.size(0), device=device) + if self.embed_dim_z is None: + self.embed_dim_z = torch.ones(self.text_projection.size(1), device=device) + mod = self + self_copy = copy.deepcopy(self) + hidden_r = self.hidden_z > 0 + mod.token_embedding = nn.Embedding( + self_copy.token_embedding.weight.shape[0], hidden_r.sum() + ) + mod.positional_embedding = nn.Parameter( + torch.empty(self_copy.context_length, hidden_r.sum()) + ) + mod.token_embedding.weight = nn.Parameter( + (self_copy.token_embedding.weight * self_copy.hidden_z.view(1, -1))[ + :, hidden_r + ] + ) + mod.positional_embedding = nn.Parameter( + (self_copy.positional_embedding * self_copy.hidden_z.view(1, -1))[ + :, hidden_r + ] + ) + mod.transformer = self.transformer.prune() + mod.ln_final = self.ln_final.prune() + embed_dim_r = self.embed_dim_z > 0 + mod.text_projection = nn.Parameter( + ( + self.text_projection + * self.hidden_z.view(-1, 1) + * self.embed_dim_z.view(1, -1) + )[hidden_r][:, embed_dim_r] + ) + return mod + + +class LogitScale(nn.Module): + def __init__(self): + super().__init__() + self.logit_scale = nn.Parameter(torch.ones([]) * np.log(1 / 0.07)) + + def forward(self, dummy): + return self.logit_scale + + +class FNBlock(nn.Module): + def __init__(self, fn): + super().__init__() + self.fn = fn + + def forward(self, *args, **kwargs): + return self.fn(*args, **kwargs) + + +class FakeDDP(nn.Module): + def __init__(self, module): + super().__init__() + self.module = module + + def forward(self, *args, **kwargs): + return self.module(*args, **kwargs) + + +class CLIPBase(nn.Module): + def __init__(self, image_encoder, text_encoder): + super().__init__() + self._image_encoder = image_encoder + self._text_encoder = text_encoder + + self._logit_scale = LogitScale() + + # autocast context + self.image_autocast = nullcontext + self.text_autocast = nullcontext + self.logit_autocast = nullcontext + + # copy the module without ddp + self._without_ddp = [self._image_encoder, self._text_encoder, self._logit_scale] + + self.used_ddp = False + + def set_autocast(self, image_autocast, text_autocast, logit_autocast): + self.image_autocast = image_autocast + self.text_autocast = text_autocast + self.logit_autocast = logit_autocast + + @property + def image_encoder_without_ddp(self): + return self._without_ddp[0] + + @image_encoder_without_ddp.setter + def image_encoder_without_ddp(self, encoder): + assert self.used_ddp is False + self._image_encoder = encoder + self._without_ddp[0] = self._image_encoder + + @property + def text_encoder_without_ddp(self): + return self._without_ddp[1] + + @text_encoder_without_ddp.setter + def text_encoder_without_ddp(self, encoder): + assert self.used_ddp is False + self._text_encoder = encoder + self._without_ddp[1] = self._text_encoder + + @property + def logit_scale_without_ddp(self): + return self._without_ddp[2] + + @logit_scale_without_ddp.setter + def logit_scale_without_ddp(self, logit_scale): + assert self.used_ddp is False + self._logit_scale = logit_scale + self._without_ddp[2] = self._logit_scale + + @property + def visual(self): + return self.image_encoder_without_ddp.visual + + @property + def transformer(self): + return self.text_encoder_without_ddp.transformer + + @property + def text_encoder_without_ddp(self): + return self._without_ddp[1] + + @property + def logit_scale_without_ddp(self): + return self._without_ddp[2] + + def get_teacher(self): + return self.teacher[0] + + def use_teacher_image(self): + def teacher_image_encoder_fn(image, normalized=False): + teacher = self.get_teacher() + with torch.no_grad(): + return teacher.encode_image(image, normalized=normalized) + + self._image_encoder = FNBlock(teacher_image_encoder_fn) + + class EmptyVisual(nn.Module): + def __init__(self): + super().__init__() + self.layers = 0 + + self._image_encoder.visual = EmptyVisual() + self._without_ddp[0] = self._image_encoder + + def use_teacher_text(self): + def teacher_text_encoder_fn(text, normalized=False): + teacher = self.get_teacher() + with torch.no_grad(): + return teacher.encode_text(text, normalized=normalized) + + self._text_encoder = FNBlock(teacher_text_encoder_fn) + + class EmptyTransformer(nn.Module): + def __init__(self): + super().__init__() + self.layers = 0 + + self._text_encoder.transformer = EmptyTransformer() + self._text_encoder.token_embedding = None + self._without_ddp[1] = self._text_encoder + + def ddpify(self, ddp_fn): + def _ddp_fn(module): + cnt = sum([p.numel() for p in module.parameters() if p.requires_grad]) + if cnt > 0: + return ddp_fn(module) + return FakeDDP(module) + + self._image_encoder = _ddp_fn(self.image_encoder_without_ddp) + self._text_encoder = _ddp_fn(self.text_encoder_without_ddp) + self._logit_scale = _ddp_fn(self.logit_scale_without_ddp) + + self.used_ddp = True + + def forward(self, image, text, normalized=True): + image_features = text_features = None + if image is not None: + with self.image_autocast(): + image_features = self._image_encoder(image, normalized=normalized) + if text is not None: + with self.text_autocast(): + text_features = self._text_encoder(text, normalized=normalized) + with self.logit_autocast(): + logit_scale = self._logit_scale(torch.tensor(0)) + return image_features, text_features, logit_scale.exp() + + def encode_image(self, image, normalize=False): + """ + Encode image to features. + Compatible with OpenAI CLIP's encode_image interface. + """ + with self.image_autocast(): + return self._image_encoder(image, normalized=normalize) + + def encode_text(self, text, normalized=False): + with self.text_autocast(): + return self._text_encoder(text, normalized=normalized) + + @property + def logit_scale(self): + return self.logit_scale_without_ddp.logit_scale + + def lock_image_tower(self, unlocked_groups=0, freeze_bn_stats=False): + # lock image tower as per LiT - https://arxiv.org/abs/2111.07991 + self.visual.lock( + unlocked_groups=unlocked_groups, freeze_bn_stats=freeze_bn_stats + ) + + def lock_text_tower(self, unlocked_groups=0, freeze_bn_stats=False): + assert ( + unlocked_groups == 0 + ), "partial locking not currently supported for this model" + tower = self.text_encoder_without_ddp + for param in tower.parameters(): + param.requires_grad = False + if freeze_bn_stats: + freeze_batch_norm_2d(tower) + + @torch.jit.ignore + def set_grad_checkpointing(self, enable=True): + visual = self.image_encoder_without_ddp.visual + transformer = self.text_encoder_without_ddp.transformer + if hasattr(visual, "set_grad_checkpointing"): + visual.set_grad_checkpointing(enable) + if transformer is not None and hasattr(transformer, "set_grad_checkpointing"): + transformer.set_grad_checkpointing(enable) + + def image_named_params(self): + return self._image_encoder.named_parameters() + + def text_named_params(self): + return self._text_encoder.named_parameters() + + def joint_named_params(self): + return self._logit_scale.named_parameters() + + def load_state_dict(self, state_dict, strict=True): + state_dict = convert_to_new_checkpoint(state_dict, self.used_ddp) + if not any(k.startswith("_image_encoder") for k in state_dict.keys()): + self.use_teacher_image() + + for m in ["module.", ""]: + flag = f"_image_encoder.{m}visual.model.head.0.weight" + if flag in state_dict: + # LN + state_dict[f"_image_encoder.{m}visual.ln_post.weight"] = state_dict.pop( + f"_image_encoder.{m}visual.model.head.0.weight" + ) + state_dict[f"_image_encoder.{m}visual.ln_post.bias"] = state_dict.pop( + f"_image_encoder.{m}visual.model.head.0.bias" + ) + # FC + state_dict[f"_image_encoder.{m}visual.proj"] = state_dict.pop( + f"_image_encoder.{m}visual.model.head.1.weight" + ).T + new_state_dict = state_dict.copy() + for k, v in new_state_dict.items(): + if ".module" in k: + state_dict[k.replace(".module", "")] = v + state_dict.pop(k) + return super().load_state_dict(state_dict, strict=strict) + + +class CLIP(CLIPBase): + def __init__( + self, + embed_dim: int, + vision_cfg: CLIPVisionCfg, + text_cfg: CLIPTextCfg, + quick_gelu: bool = False, + mask_image: bool = False, + mask_text: bool = False, + sparsity_warmup: int = 1000, + sparsity: float = 0.25, + start_sparsity: float = 0.0, + freeze_text: bool = True, + ): + vision_ocfg = None + text_ocfg = None + + if isinstance(vision_cfg, dict): + vision_ocfg = vision_cfg.pop("configs", None) + vision_cfg = CLIPVisionCfg(**vision_cfg) + + if isinstance(text_cfg, dict): + text_ocfg = text_cfg.pop("configs", None) + text_cfg = CLIPTextCfg(**text_cfg) + + mask_cfg = Namespace() + mask_cfg.sparsity_warmup = sparsity_warmup + mask_cfg.sparsity = sparsity + mask_cfg.start_sparsity = start_sparsity + + if vision_ocfg is None: + image_encoder = ImageEncoder( + embed_dim, + vision_cfg, + quick_gelu, + l0_module_image=mask_image, + mask_cfg=mask_cfg, + ) + + if text_ocfg is None: + text_encoder = TextEncoder( + embed_dim, + text_cfg, + quick_gelu, + l0_module_text=mask_text, + mask_cfg=mask_cfg, + ) + + super().__init__(image_encoder, text_encoder) + # Freeze text encoder at initialization + if freeze_text: + print(f"Freeze text encoder parameters", flush=True) + self.lock_text_tower() + self.text_encoder_without_ddp.eval() + + def train(self, mode: bool = True): + """Override train() to ensure text encoder stays frozen even in training mode.""" + if not isinstance(mode, bool): + raise ValueError("training mode is expected to be boolean") + self.training = mode + + # Set image encoder to training/eval mode based on mode + if mode: + logging.info(f"========Set image encoder as train mode========") + else: + logging.info(f"========Set image encoder as eval mode========") + self.image_encoder_without_ddp.train(mode) + + # Always keep text encoder in eval mode (frozen) + logging.info(f"========Set text encoder as eval mode (frozen)========") + self.text_encoder_without_ddp.train(False) + + # Ensure text encoder parameters remain frozen + for param in self.text_encoder_without_ddp.parameters(): + param.requires_grad = False + + return self + + def encode_dense( + self, + image, + normalize=False, + keep_shape=False, + mode="vanilla", + ex_feats=None, + beta=1.2, + gamma=3.0, + ): + """ + Encode dense feature map from images. + Compatible with OpenAI CLIP's encode_dense interface. + For proxyclip mode, ex_feats should be provided from VFM (SAM/DINO/DINOv2). + """ + visual = self.visual + if not isinstance(visual, VisualTransformer): + raise NotImplementedError( + "encode_dense is only supported for VisualTransformer" + ) + + # Get mask parameters if available + mask = getattr(self.image_encoder_without_ddp, "mask", None) + if mask is None or not isinstance(mask, dict): + mask = {} + hidden_z = mask.get("hidden_z", None) + heads_z = mask.get("heads_z", None) + mha_z = mask.get("mha_z", None) + intermediate_z = mask.get("intermediate_z", None) + ffn_z = mask.get("ffn_z", None) + embed_dim_z = mask.get("embed_dim_z", None) + + with self.image_autocast(): + if mode in ["qq_vfm_distill", "kk_vfm_distill", "csa_vfm_distill"]: + features, extra_features = visual.encode_dense( + image, + keep_shape=keep_shape, + mode=mode, + hidden_z=hidden_z, + heads_z=heads_z, + mha_z=mha_z, + intermediate_z=intermediate_z, + ffn_z=ffn_z, + embed_dim_z=embed_dim_z, + ex_feats=ex_feats, + beta=beta, + gamma=gamma, + ) + if normalize: + if keep_shape: + features = F.normalize(features, dim=1) + else: + features = F.normalize(features, dim=-1) + return features, extra_features + else: + features = visual.encode_dense( + image, + keep_shape=keep_shape, + mode=mode, + hidden_z=hidden_z, + heads_z=heads_z, + mha_z=mha_z, + intermediate_z=intermediate_z, + ffn_z=ffn_z, + embed_dim_z=embed_dim_z, + ex_feats=ex_feats, + beta=beta, + gamma=gamma, + ) + if normalize: + if keep_shape: + features = F.normalize(features, dim=1) + else: + features = F.normalize(features, dim=-1) + return features + + def encode_pseudo_boxes( + self, image, normed_boxes, normalize=False, mode="vanilla", size=(1, 1) + ): + """ + Encode ROI features from images using normalized boxes. + Compatible with OpenAI CLIP's encode_pseudo_boxes interface. + """ + visual = self.visual + if not isinstance(visual, VisualTransformer): + raise NotImplementedError( + "encode_pseudo_boxes is only supported for VisualTransformer" + ) + + # Get mask parameters if available + mask = getattr(self.image_encoder_without_ddp, "mask", None) + if mask is None or not isinstance(mask, dict): + mask = {} + hidden_z = mask.get("hidden_z", None) + heads_z = mask.get("heads_z", None) + mha_z = mask.get("mha_z", None) + intermediate_z = mask.get("intermediate_z", None) + ffn_z = mask.get("ffn_z", None) + embed_dim_z = mask.get("embed_dim_z", None) + + with self.image_autocast(): + if mode in ["qq_vfm_distill", "kk_vfm_distill", "csa_vfm_distill"]: + box_features, clip_dense_feats = visual.extract_roi_features( + image, + normed_boxes, + mode=mode, + size=size, + hidden_z=hidden_z, + heads_z=heads_z, + mha_z=mha_z, + intermediate_z=intermediate_z, + ffn_z=ffn_z, + embed_dim_z=embed_dim_z, + ) + if normalize: + box_features = F.normalize(box_features, dim=-1) + return box_features, clip_dense_feats + else: + box_features = visual.extract_roi_features( + image, + normed_boxes, + mode=mode, + size=size, + hidden_z=hidden_z, + heads_z=heads_z, + mha_z=mha_z, + intermediate_z=intermediate_z, + ffn_z=ffn_z, + embed_dim_z=embed_dim_z, + ) + + if normalize: + box_features = F.normalize(box_features, dim=-1) + return box_features + + def encode_masks( + self, image, masks, normalize=True, mask_attn=False, mode="vanilla" + ): + """ + Encode mask-pooled features from images. + Compatible with OpenAI CLIP's encode_masks interface. + """ + visual = self.visual + if not isinstance(visual, VisualTransformer): + raise NotImplementedError( + "encode_masks is only supported for VisualTransformer" + ) + + # Get mask parameters if available + mask = getattr(self.image_encoder_without_ddp, "mask", None) + if mask is None or not isinstance(mask, dict): + mask = {} + hidden_z = mask.get("hidden_z", None) + heads_z = mask.get("heads_z", None) + mha_z = mask.get("mha_z", None) + intermediate_z = mask.get("intermediate_z", None) + ffn_z = mask.get("ffn_z", None) + embed_dim_z = mask.get("embed_dim_z", None) + + with self.image_autocast(): + mask_pooled = visual.mask_pool( + image, + masks, + mode=mode, + hidden_z=hidden_z, + heads_z=heads_z, + mha_z=mha_z, + intermediate_z=intermediate_z, + ffn_z=ffn_z, + embed_dim_z=embed_dim_z, + ) + if normalize: + mask_pooled = F.normalize(mask_pooled, dim=-1) + return mask_pooled + + +def convert_to_new_checkpoint(state_dict, used_ddp=False): + if "_logit_scale.module.logit_scale" in state_dict: + if not used_ddp: + new_checkpoint = dict() + for k, v in state_dict.items(): + sp = k.split(".") + assert sp[1] == "module", (sp, state_dict.keys()) + k = ".".join(sp[:1] + sp[2:]) + new_checkpoint[k] = v + state_dict = new_checkpoint + return state_dict + if "_logit_scale.logit_scale" in state_dict: + if used_ddp: + new_checkpoint = dict() + for k, v in state_dict.items(): + sp = k.split(".") + k = ".".join(sp[:1] + ["module"] + sp[1:]) + new_checkpoint[k] = v + state_dict = new_checkpoint + return state_dict + image_prefix = "_image_encoder." + text_prefix = "_text_encoder." + logit_scale_prefix = "_logit_scale." + if used_ddp: + image_prefix += "module." + text_prefix += "module." + logit_scale_prefix += "module." + new_checkpoint = dict() + if "module.logit_scale" in state_dict: + # remove the prefix module + state_dict = {k[len("module.") :]: v for k, v in state_dict.items()} + if "logit_scale" in state_dict: + # old CLIP checkpoint + for k, v in state_dict.items(): + if k.startswith("visual."): + new_checkpoint[image_prefix + k] = v + elif k == "logit_scale": + new_checkpoint[logit_scale_prefix + "logit_scale"] = v + else: + new_checkpoint[text_prefix + k] = v + else: + new_checkpoint = state_dict + return new_checkpoint + + +def convert_weights_to_fp16(model: nn.Module): + """Convert applicable model parameters to fp16""" + + def _convert_weights_to_fp16(l): + if isinstance(l, (nn.Conv1d, nn.Conv2d, nn.Linear)): + l.weight.data = l.weight.data.half() + if l.bias is not None: + l.bias.data = l.bias.data.half() + + if isinstance(l, (nn.MultiheadAttention,)): + for attr in [ + *[f"{s}_proj_weight" for s in ["in", "q", "k", "v"]], + "in_proj_bias", + "bias_k", + "bias_v", + ]: + tensor = getattr(l, attr) + if tensor is not None: + tensor.data = tensor.data.half() + + for name in ["text_projection", "proj"]: + if hasattr(l, name): + attr = getattr(l, name) + if attr is not None: + attr.data = attr.data.half() + + model.apply(_convert_weights_to_fp16) + + +def build_model_from_openai_state_dict(state_dict: dict): + vit = "visual.proj" in state_dict + + if vit: + vision_width = state_dict["visual.conv1.weight"].shape[0] + vision_layers = len( + [ + k + for k in state_dict.keys() + if k.startswith("visual.") and k.endswith(".attn.in_proj_weight") + ] + ) + vision_patch_size = state_dict["visual.conv1.weight"].shape[-1] + grid_size = round( + (state_dict["visual.positional_embedding"].shape[0] - 1) ** 0.5 + ) + image_size = vision_patch_size * grid_size + else: + counts: list = [ + len( + set( + k.split(".")[2] + for k in state_dict + if k.startswith(f"visual.layer{b}") + ) + ) + for b in [1, 2, 3, 4] + ] + vision_layers = tuple(counts) + vision_width = state_dict["visual.layer1.0.conv1.weight"].shape[0] + output_width = round( + (state_dict["visual.attnpool.positional_embedding"].shape[0] - 1) ** 0.5 + ) + vision_patch_size = None + assert ( + output_width**2 + 1 + == state_dict["visual.attnpool.positional_embedding"].shape[0] + ) + image_size = output_width * 32 + + embed_dim = state_dict["text_projection"].shape[1] + context_length = state_dict["positional_embedding"].shape[0] + vocab_size = state_dict["token_embedding.weight"].shape[0] + transformer_width = state_dict["ln_final.weight"].shape[0] + transformer_heads = transformer_width // 64 + transformer_layers = len( + set( + k.split(".")[2] + for k in state_dict + if k.startswith(f"transformer.resblocks") + ) + ) + + vision_cfg = CLIPVisionCfg( + layers=vision_layers, + width=vision_width, + patch_size=vision_patch_size, + image_size=image_size, + ) + text_cfg = CLIPTextCfg( + context_length=context_length, + vocab_size=vocab_size, + width=transformer_width, + heads=transformer_heads, + layers=transformer_layers, + ) + model = CLIP( + embed_dim, + vision_cfg=vision_cfg, + text_cfg=text_cfg, + quick_gelu=True, # OpenAI models were trained with QuickGELU + ) + + for key in ["input_resolution", "context_length", "vocab_size"]: + state_dict.pop(key, None) + + convert_weights_to_fp16(model) + model.load_state_dict(state_dict) + return model.eval() + + +def trace_model(model, batch_size=256, device=torch.device("cpu")): + model.eval() + image_size = model.visual.image_size + example_images = torch.ones((batch_size, 3, image_size, image_size), device=device) + example_text = torch.zeros( + (batch_size, model.context_length), dtype=torch.int, device=device + ) + model = torch.jit.trace_module( + model, + inputs=dict( + forward=(example_images, example_text), + encode_text=(example_text,), + encode_image=(example_images,), + ), + ) + model.visual.image_size = image_size + return model + + +def resize_pos_embed(state_dict, model, interpolation: str = "bicubic", seq_dim=1): + # Rescale the grid of position embeddings when loading from state_dict + old_pos_embed = state_dict.get("visual.positional_embedding", None) + if old_pos_embed is None or not hasattr(model.visual, "grid_size"): + return + grid_size = to_2tuple(model.visual.grid_size) + # FIXME detect different token configs (ie no class token, or more) + extra_tokens = 1 + new_seq_len = grid_size[0] * grid_size[1] + extra_tokens + if new_seq_len == old_pos_embed.shape[0]: + return + + if extra_tokens: + pos_emb_tok, pos_emb_img = ( + old_pos_embed[:extra_tokens], + old_pos_embed[extra_tokens:], + ) + else: + pos_emb_tok, pos_emb_img = None, old_pos_embed + old_grid_size = to_2tuple(int(math.sqrt(len(pos_emb_img)))) + + logging.info( + "Resizing position embedding grid-size from %s to %s", old_grid_size, grid_size + ) + pos_emb_img = pos_emb_img.reshape( + 1, old_grid_size[0], old_grid_size[1], -1 + ).permute(0, 3, 1, 2) + pos_emb_img = F.interpolate( + pos_emb_img, + size=grid_size, + mode=interpolation, + align_corners=True, + ) + pos_emb_img = pos_emb_img.permute(0, 2, 3, 1).reshape( + 1, grid_size[0] * grid_size[1], -1 + )[0] + if pos_emb_tok is not None: + new_pos_embed = torch.cat([pos_emb_tok, pos_emb_img], dim=0) + else: + new_pos_embed = pos_emb_img + state_dict["visual.positional_embedding"] = new_pos_embed + + +@torch.no_grad() +def load_pruned_model(model, pruned_state_dict, strict=True): + """ + A full model loads the pruned state dict. + + Inputs: + model_state_dict: the full model weights + pruned_state_dict: the pruned model weights + """ + + def _copy_to_full_weight(dst, src): + assert dst.ndim == src.ndim, (dst.ndim, src.ndim) + dst.zero_() + dims = src.shape + if len(dims) == 0: + dst.copy_(src) + else: + slices = [slice(0, d) for d in dims] + dst[slices].copy_(src) + + for _ in range(2): + pruned_state_dict = { + k.replace("module.", ""): v for k, v in pruned_state_dict.items() + } + + lambda_init_value = 10.0 + model_state_dict = model.state_dict() + head_dim = model.transformer.head_dim + + pruned_state_dict = { + k.replace("image_encoder_without_ddp", "_image_encoder").replace( + "text_encoder_without_ddp", "_text_encoder" + ): v + for k, v in pruned_state_dict.items() + } + + for name, dst in model_state_dict.items(): + # auto weight inheritance model weight prefix + dst_shape = dst.shape + + # copy weights + if name in pruned_state_dict: + src = pruned_state_dict[name] + if "attn.in_proj_weight" in name: + # reshape: (3 * num_heads * head_dim, embed_dim) -> (3, num_heads, head_dim, embed_dim) + assert len(src.shape) == 2 + _copy_to_full_weight( + dst.view(3, -1, head_dim, dst_shape[-1]), + src.view(3, -1, head_dim, src.shape[-1]), + ) + elif "attn.in_proj_bias" in name: + # reshape: (3 * num_heads * head_dim,) -> (3, num_heads, head_dim) + assert len(src.shape) == 1 + _copy_to_full_weight( + dst.view(3, -1, head_dim), src.view(3, -1, head_dim) + ) + else: + _copy_to_full_weight(dst, src) + else: + if ".resblocks." in name: + # the layer has been pruned. + dst.zero_() + + model_state_dict["_logit_scale.logit_scale"] = pruned_state_dict[ + "_logit_scale.logit_scale" + ] + + # prune hidden dimensions + encoder_names = ["_image_encoder", "_text_encoder"] + hidden_size_img = pruned_state_dict["_image_encoder.visual.ln_pre.weight"].shape[0] + hidden_size_txt = pruned_state_dict["_text_encoder.positional_embedding"].shape[1] + hidden_sizes = [hidden_size_img, hidden_size_txt] + + for ename, hidden_size in zip(encoder_names, hidden_sizes): + # reset lambda in l0 module + model_state_dict[f"{ename}.l0_module.lambda_1"].fill_(lambda_init_value) + model_state_dict[f"{ename}.l0_module.lambda_2"].fill_(lambda_init_value) + # prune the last dimensions + model_state_dict[f"{ename}.l0_module.hidden_loga"][hidden_size:].fill_( + -lambda_init_value + ) + + def _get_layer_id(name): + return int(name.split("resblocks.")[1].split(".")[0]) + + for ename in encoder_names: + # get the depth of the encoder + encoder_keys = list(k for k in model_state_dict.keys() if ename in k) + encoder_depth = ( + max(_get_layer_id(k) for k in encoder_keys if "resblocks" in k) + 1 + ) + pruned_encoder_keys = list(k for k in pruned_state_dict.keys() if ename in k) + in_proj_weight_shapes = [None for _ in range(encoder_depth)] + mlp_c_fc_shapes = [None for _ in range(encoder_depth)] + for k in pruned_encoder_keys: + if "in_proj_weight" in k: + d = _get_layer_id(k) + in_proj_weight_shapes[d] = pruned_state_dict[k].shape + elif "mlp.c_fc.weight" in k: + d = _get_layer_id(k) + mlp_c_fc_shapes[d] = pruned_state_dict[k].shape + + for d in range(encoder_depth): + # set heads_loga + if in_proj_weight_shapes[d] is not None: + num_heads = in_proj_weight_shapes[d][0] // head_dim // 3 + model_state_dict[f"{ename}.l0_module.heads_loga"][d, num_heads:].fill_( + -lambda_init_value + ) + else: + # all heads have been pruned + model_state_dict[f"{ename}.l0_module.heads_loga"][d, :].fill_( + -lambda_init_value + ) + + # set intermediate_loga + if mlp_c_fc_shapes[d] is not None: + inter_size = mlp_c_fc_shapes[d][0] + model_state_dict[f"{ename}.l0_module.intermediate_loga"][ + d, inter_size: + ].fill_(-lambda_init_value) + else: + # all intermediate dimensions have been pruned + model_state_dict[f"{ename}.l0_module.intermediate_loga"][d, :].fill_( + -lambda_init_value + ) + + return model.load_state_dict(model_state_dict, strict=strict) + + +def prune_model(model): + device = next(model.parameters()).device + + with torch.no_grad(): + model.image_encoder_without_ddp.eval() + image_size = (1, 3) + model.image_encoder_without_ddp.visual.image_size + image = torch.randn(image_size, device=device) + 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 + + with torch.no_grad(): + model.text_encoder_without_ddp.eval() + context_length = model.text_encoder_without_ddp.context_length + text = torch.zeros((1, context_length), dtype=torch.long, device=device) + 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 + + return model diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/tiny_clip/model_configs/RN50.json b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/tiny_clip/model_configs/RN50.json new file mode 100644 index 0000000000000000000000000000000000000000..33aa884d54fee0076c33676831e49d5e1ffcb8f2 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/tiny_clip/model_configs/RN50.json @@ -0,0 +1,21 @@ +{ + "embed_dim": 1024, + "vision_cfg": { + "image_size": 224, + "layers": [ + 3, + 4, + 6, + 3 + ], + "width": 64, + "patch_size": null + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 512, + "heads": 8, + "layers": 12 + } +} \ No newline at end of file diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/tiny_clip/model_configs/TinyCLIP-ResNet-19M-Text-19M.json b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/tiny_clip/model_configs/TinyCLIP-ResNet-19M-Text-19M.json new file mode 100644 index 0000000000000000000000000000000000000000..0c51ad8bfb5ed23f7ecc2b39c2ffa83140aa1620 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/tiny_clip/model_configs/TinyCLIP-ResNet-19M-Text-19M.json @@ -0,0 +1,21 @@ +{ + "embed_dim": 1024, + "vision_cfg": { + "image_size": 224, + "layers": [ + 3, + 4, + 6, + 3 + ], + "width": 44, + "patch_size": null + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 512, + "heads": 8, + "layers": 6 + } +} \ No newline at end of file diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/tiny_clip/model_configs/TinyCLIP-ResNet-30M-Text-29M.json b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/tiny_clip/model_configs/TinyCLIP-ResNet-30M-Text-29M.json new file mode 100644 index 0000000000000000000000000000000000000000..ee1c8e675d083721900ed4be16aab28134a4364b --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/tiny_clip/model_configs/TinyCLIP-ResNet-30M-Text-29M.json @@ -0,0 +1,21 @@ +{ + "embed_dim": 1024, + "vision_cfg": { + "image_size": 224, + "layers": [ + 3, + 4, + 6, + 3 + ], + "width": 56, + "patch_size": null + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 512, + "heads": 8, + "layers": 9 + } +} \ No newline at end of file diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/tiny_clip/model_configs/TinyCLIP-ViT-39M-16-Text-19M.json b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/tiny_clip/model_configs/TinyCLIP-ViT-39M-16-Text-19M.json new file mode 100644 index 0000000000000000000000000000000000000000..cda162a5daab7ff56ea9c158ce4d28f0fcc3d84e --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/tiny_clip/model_configs/TinyCLIP-ViT-39M-16-Text-19M.json @@ -0,0 +1,16 @@ +{ + "embed_dim": 512, + "vision_cfg": { + "image_size": 224, + "layers": 12, + "width": 512, + "patch_size": 16 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 512, + "heads": 8, + "layers": 6 + } +} diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/tiny_clip/model_configs/TinyCLIP-ViT-40M-32-Text-19M.json b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/tiny_clip/model_configs/TinyCLIP-ViT-40M-32-Text-19M.json new file mode 100644 index 0000000000000000000000000000000000000000..6c61930a2e78c952a6cd4269c6ecc4f0359eeb04 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/tiny_clip/model_configs/TinyCLIP-ViT-40M-32-Text-19M.json @@ -0,0 +1,16 @@ +{ + "embed_dim": 512, + "vision_cfg": { + "image_size": 224, + "layers": 12, + "width": 512, + "patch_size": 32 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 512, + "heads": 8, + "layers": 6 + } +} diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/tiny_clip/model_configs/TinyCLIP-ViT-61M-32-Text-29M.json b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/tiny_clip/model_configs/TinyCLIP-ViT-61M-32-Text-29M.json new file mode 100644 index 0000000000000000000000000000000000000000..f58211a2d4ae61c2cd51e6cade812dfedd77af45 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/tiny_clip/model_configs/TinyCLIP-ViT-61M-32-Text-29M.json @@ -0,0 +1,16 @@ +{ + "embed_dim": 512, + "vision_cfg": { + "image_size": 224, + "layers": 12, + "width": 640, + "patch_size": 32 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 512, + "heads": 8, + "layers": 9 + } +} diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/tiny_clip/model_configs/TinyCLIP-ViT-8M-16-Text-3M.json b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/tiny_clip/model_configs/TinyCLIP-ViT-8M-16-Text-3M.json new file mode 100644 index 0000000000000000000000000000000000000000..f73483282a3447901775351a5eed728a8a905fef --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/tiny_clip/model_configs/TinyCLIP-ViT-8M-16-Text-3M.json @@ -0,0 +1,16 @@ +{ + "embed_dim": 512, + "vision_cfg": { + "image_size": 224, + "layers": 10, + "width": 256, + "patch_size": 16 + }, + "text_cfg": { + "context_length": 77, + "vocab_size": 49408, + "width": 256, + "heads": 4, + "layers": 3 + } +} diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/tiny_clip/model_configs/TinyCLIP-auto-ViT-22M-32-Text-10M.json b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/tiny_clip/model_configs/TinyCLIP-auto-ViT-22M-32-Text-10M.json new file mode 100644 index 0000000000000000000000000000000000000000..bb568bb9e046b411b60a2ce601dd6de3aa1ca54b --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/tiny_clip/model_configs/TinyCLIP-auto-ViT-22M-32-Text-10M.json @@ -0,0 +1,19 @@ +{ + "mask_image": true, + "mask_text": true, + + "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 + } +} diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/tiny_clip/model_configs/TinyCLIP-auto-ViT-45M-32-Text-18M.json b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/tiny_clip/model_configs/TinyCLIP-auto-ViT-45M-32-Text-18M.json new file mode 100644 index 0000000000000000000000000000000000000000..bb568bb9e046b411b60a2ce601dd6de3aa1ca54b --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/tiny_clip/model_configs/TinyCLIP-auto-ViT-45M-32-Text-18M.json @@ -0,0 +1,19 @@ +{ + "mask_image": true, + "mask_text": true, + + "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 + } +} diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/tiny_clip/model_configs/TinyCLIP-auto-ViT-63M-32-Text-31M.json b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/tiny_clip/model_configs/TinyCLIP-auto-ViT-63M-32-Text-31M.json new file mode 100644 index 0000000000000000000000000000000000000000..bb568bb9e046b411b60a2ce601dd6de3aa1ca54b --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/tiny_clip/model_configs/TinyCLIP-auto-ViT-63M-32-Text-31M.json @@ -0,0 +1,19 @@ +{ + "mask_image": true, + "mask_text": true, + + "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 + } +} diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/tiny_clip/model_configs/ViT-B-16.json b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/tiny_clip/model_configs/ViT-B-16.json new file mode 100644 index 0000000000000000000000000000000000000000..9afeef0fbc807f130f2b2bc65c1dd85abc9eba72 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/tiny_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/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/tiny_clip/model_configs/ViT-B-32.json b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/tiny_clip/model_configs/ViT-B-32.json new file mode 100644 index 0000000000000000000000000000000000000000..07c8e28eb06fa1813ba932fe4eec668262d1c47f --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/tiny_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/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/tiny_clip/openai.py b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/tiny_clip/openai.py new file mode 100644 index 0000000000000000000000000000000000000000..23a44e004d7d69148a886d7ddc9a1d298bd332d8 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/tiny_clip/openai.py @@ -0,0 +1,138 @@ +""" OpenAI pretrained model functions + +Adapted from https://github.com/openai/CLIP. Originally MIT License, Copyright (c) 2021 OpenAI. +""" + +import os +import warnings +from typing import Union, List + +import torch + +from .model import build_model_from_openai_state_dict +from .pretrained import get_pretrained_url, list_pretrained_tag_models, download_pretrained_from_url + +__all__ = ["list_openai_models", "load_openai_model"] + + +def list_openai_models() -> List[str]: + """Returns the names of available CLIP models""" + return list_pretrained_tag_models('openai') + + +def load_openai_model( + name: str, + device: Union[str, torch.device] = "cuda" if torch.cuda.is_available( + ) else "cpu", + jit=True, + cache_dir=None, +): + """Load a CLIP model + + Parameters + ---------- + name : str + A model name listed by `clip.available_models()`, or the path to a model checkpoint containing the state_dict + device : Union[str, torch.device] + The device to put the loaded model + jit : bool + Whether to load the optimized JIT model (default) or more hackable non-JIT model. + cache_dir : Optional[str] + The directory to cache the downloaded model weights + + Returns + ------- + model : torch.nn.Module + The CLIP model + preprocess : Callable[[PIL.Image], torch.Tensor] + A torchvision transform that converts a PIL image into a tensor that the returned model can take as its input + """ + if get_pretrained_url(name, 'openai'): + model_path = download_pretrained_from_url( + get_pretrained_url(name, 'openai'), cache_dir=cache_dir) + elif os.path.isfile(name): + model_path = name + else: + raise RuntimeError( + f"Model {name} not found; available models = {list_openai_models()}") + + try: + # loading JIT archive + model = torch.jit.load( + model_path, map_location=device if jit else "cpu").eval() + state_dict = None + except RuntimeError: + # loading saved state dict + if jit: + warnings.warn( + f"File {model_path} is not a JIT archive. Loading as a state dict instead") + jit = False + state_dict = torch.load(model_path, map_location="cpu") + + if not jit: + try: + model = build_model_from_openai_state_dict( + state_dict or model.state_dict()).to(device) + except KeyError: + sd = {k[7:]: v for k, v in state_dict["state_dict"].items()} + model = build_model_from_openai_state_dict(sd).to(device) + + if str(device) == "cpu": + model.float() + return model + + # patch the device names + device_holder = torch.jit.trace(lambda: torch.ones( + []).to(torch.device(device)), example_inputs=[]) + device_node = [n for n in device_holder.graph.findAllNodes( + "prim::Constant") if "Device" in repr(n)][-1] + + def patch_device(module): + try: + graphs = [module.graph] if hasattr(module, "graph") else [] + except RuntimeError: + graphs = [] + + if hasattr(module, "forward1"): + graphs.append(module.forward1.graph) + + for graph in graphs: + for node in graph.findAllNodes("prim::Constant"): + if "value" in node.attributeNames() and str(node["value"]).startswith("cuda"): + node.copyAttributes(device_node) + + model.apply(patch_device) + patch_device(model.encode_image) + patch_device(model.encode_text) + + # patch dtype to float32 on CPU + if str(device) == "cpu": + float_holder = torch.jit.trace( + lambda: torch.ones([]).float(), example_inputs=[]) + float_input = list(float_holder.graph.findNode("aten::to").inputs())[1] + float_node = float_input.node() + + def patch_float(module): + try: + graphs = [module.graph] if hasattr(module, "graph") else [] + except RuntimeError: + graphs = [] + + if hasattr(module, "forward1"): + graphs.append(module.forward1.graph) + + for graph in graphs: + for node in graph.findAllNodes("aten::to"): + inputs = list(node.inputs()) + for i in [1, 2]: # dtype can be the second or third argument to aten::to() + if inputs[i].node()["value"] == 5: + inputs[i].node().copyAttributes(float_node) + + model.apply(patch_float) + patch_float(model.encode_image) + patch_float(model.encode_text) + model.float() + + # ensure image_size attr available at consistent location for both jit and non-jit + model.visual.image_size = model.input_resolution.item() + return model diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/tiny_clip/pretrained.py b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/tiny_clip/pretrained.py new file mode 100644 index 0000000000000000000000000000000000000000..4a89069557b1e1ae32dd5bfc09b9ab8a2062d827 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/tiny_clip/pretrained.py @@ -0,0 +1,411 @@ +import hashlib +import os +import time +import urllib +import warnings +from functools import partial +from typing import Dict, Union + +from tqdm import tqdm + +from .version import __version__ + +try: + from huggingface_hub import hf_hub_download + hf_hub_download = partial( + hf_hub_download, library_name="open_clip", library_version=__version__) + _has_hf_hub = True +except ImportError: + hf_hub_download = None + _has_hf_hub = False + + +def _pcfg(url='', hf_hub='', mean=None, std=None): + return dict( + url=url, + hf_hub=hf_hub, + mean=mean, + std=std, + ) + + +_RN50 = dict( + openai=_pcfg( + "https://openaipublic.azureedge.net/clip/models/afeb0e10f9e5a86da6080e35cf09123aca3b358a0c3e3b6c78a7b63bc04b6762/RN50.pt"), + yfcc15m=_pcfg( + "https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/rn50-quickgelu-yfcc15m-455df137.pt"), + cc12m=_pcfg( + "https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/rn50-quickgelu-cc12m-f000538c.pt"), +) + +_RN50_quickgelu = dict( + openai=_pcfg( + "https://openaipublic.azureedge.net/clip/models/afeb0e10f9e5a86da6080e35cf09123aca3b358a0c3e3b6c78a7b63bc04b6762/RN50.pt"), + yfcc15m=_pcfg( + "https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/rn50-quickgelu-yfcc15m-455df137.pt"), + cc12m=_pcfg( + "https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/rn50-quickgelu-cc12m-f000538c.pt"), +) + +_RN101 = dict( + openai=_pcfg( + "https://openaipublic.azureedge.net/clip/models/8fa8567bab74a42d41c5915025a8e4538c3bdbe8804a470a72f30b0d94fab599/RN101.pt"), + yfcc15m=_pcfg( + "https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/rn101-quickgelu-yfcc15m-3e04b30e.pt"), +) + +_RN101_quickgelu = dict( + openai=_pcfg( + "https://openaipublic.azureedge.net/clip/models/8fa8567bab74a42d41c5915025a8e4538c3bdbe8804a470a72f30b0d94fab599/RN101.pt"), + yfcc15m=_pcfg( + "https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/rn101-quickgelu-yfcc15m-3e04b30e.pt"), +) + +_RN50x4 = dict( + openai=_pcfg( + "https://openaipublic.azureedge.net/clip/models/7e526bd135e493cef0776de27d5f42653e6b4c8bf9e0f653bb11773263205fdd/RN50x4.pt"), +) + +_RN50x16 = dict( + openai=_pcfg( + "https://openaipublic.azureedge.net/clip/models/52378b407f34354e150460fe41077663dd5b39c54cd0bfd2b27167a4a06ec9aa/RN50x16.pt"), +) + +_RN50x64 = dict( + openai=_pcfg( + "https://openaipublic.azureedge.net/clip/models/be1cfb55d75a9666199fb2206c106743da0f6468c9d327f3e0d0a543a9919d9c/RN50x64.pt"), +) + +_VITB32 = dict( + openai=_pcfg( + "https://openaipublic.azureedge.net/clip/models/40d365715913c9da98579312b702a82c18be219cc2a73407c4526f58eba950af/ViT-B-32.pt"), + laion400m_e31=_pcfg( + "https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/vit_b_32-quickgelu-laion400m_e31-d867053b.pt"), + laion400m_e32=_pcfg( + "https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/vit_b_32-quickgelu-laion400m_e32-46683a32.pt"), + laion2b_e16=_pcfg( + "https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/vit_b_32-laion2b_e16-af8dbd0c.pth"), + laion2b_s34b_b79k=_pcfg(hf_hub='laion/CLIP-ViT-B-32-laion2B-s34B-b79K/') +) + +_VITB32_quickgelu = dict( + openai=_pcfg( + "https://openaipublic.azureedge.net/clip/models/40d365715913c9da98579312b702a82c18be219cc2a73407c4526f58eba950af/ViT-B-32.pt"), + laion400m_e31=_pcfg( + "https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/vit_b_32-quickgelu-laion400m_e31-d867053b.pt"), + laion400m_e32=_pcfg( + "https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/vit_b_32-quickgelu-laion400m_e32-46683a32.pt"), +) + +_VITB16 = dict( + openai=_pcfg( + "https://openaipublic.azureedge.net/clip/models/5806e77cd80f8b59890b7e101eabd078d9fb84e6937f9e85e4ecb61988df416f/ViT-B-16.pt"), + laion400m_e31=_pcfg( + "https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/vit_b_16-laion400m_e31-00efa78f.pt"), + laion400m_e32=_pcfg( + "https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/vit_b_16-laion400m_e32-55e67d44.pt"), + # laion400m_32k=_pcfg( + # url="", + # mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5)), + # laion400m_64k=_pcfg( + # url="", + # mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5)), + laion2b_s34b_b88k=_pcfg(hf_hub='laion/CLIP-ViT-B-16-laion2B-s34B-b88K/'), +) + +_VITB16_PLUS_240 = dict( + laion400m_e31=_pcfg( + "https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/vit_b_16_plus_240-laion400m_e31-8fb26589.pt"), + laion400m_e32=_pcfg( + "https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/vit_b_16_plus_240-laion400m_e32-699c4b84.pt"), +) + +_VITL14 = dict( + openai=_pcfg( + "https://openaipublic.azureedge.net/clip/models/b8cca3fd41ae0c99ba7e8951adf17d267cdb84cd88be6f7c2e0eca1737a03836/ViT-L-14.pt"), + laion400m_e31=_pcfg( + "https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/vit_l_14-laion400m_e31-69988bb6.pt"), + laion400m_e32=_pcfg( + "https://github.com/mlfoundations/open_clip/releases/download/v0.2-weights/vit_l_14-laion400m_e32-3d133497.pt"), + laion2b_s32b_b82k=_pcfg( + hf_hub='laion/CLIP-ViT-L-14-laion2B-s32B-b82K/', + mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5)), +) + +_VITL14_336 = dict( + openai=_pcfg( + "https://openaipublic.azureedge.net/clip/models/3035c92b350959924f9f00213499208652fc7ea050643e8b385c2dac08641f02/ViT-L-14-336px.pt"), +) + +_VITH14 = dict( + laion2b_s32b_b79k=_pcfg(hf_hub='laion/CLIP-ViT-H-14-laion2B-s32B-b79K/'), +) + +_VITg14 = dict( + laion2b_s12b_b42k=_pcfg(hf_hub='laion/CLIP-ViT-g-14-laion2B-s12B-b42K/'), +) + +# TinyCLIP + +# manual weight inheritance + +_TINYCLIP_VIT_39M_16_TEXT_19M = { + "YFCC15M": _pcfg( + "https://github.com/wkcn/TinyCLIP-model-zoo/releases/download/checkpoints/TinyCLIP-ViT-39M-16-Text-19M-YFCC15M.pt", + ), +} + +_TINYCLIP_VIT_8M_16_TEXT_3M = { + "YFCC15M": _pcfg( + "https://github.com/wkcn/TinyCLIP-model-zoo/releases/download/checkpoints/TinyCLIP-ViT-8M-16-Text-3M-YFCC15M.pt", + ), +} + +_TINYCLIP_RESNET_30M_TEXT_29M = { + "LAION400M": _pcfg( + "https://github.com/wkcn/TinyCLIP-model-zoo/releases/download/checkpoints/TinyCLIP-ResNet-30M-Text-29M-LAION400M.pt", + ), +} + +_TINYCLIP_RESNET_19M_TEXT_19M = { + "LAION400M": _pcfg( + "https://github.com/wkcn/TinyCLIP-model-zoo/releases/download/checkpoints/TinyCLIP-ResNet-19M-Text-19M-LAION400M.pt", + ), +} + +_TINYCLIP_VIT_61M_32_TEXT_29M = { + "LAION400M": _pcfg( + "https://github.com/wkcn/TinyCLIP-model-zoo/releases/download/checkpoints/TinyCLIP-ViT-61M-32-Text-29M-LAION400M.pt", + ), +} + +_TINYCLIP_VIT_40M_32_TEXT_19M = { + "LAION400M": _pcfg( + "https://github.com/wkcn/TinyCLIP-model-zoo/releases/download/checkpoints/TinyCLIP-ViT-40M-32-Text-19M-LAION400M.pt", + ), +} + +# auto weight inheritance + +_TINYCLIP_AUTO_VIT_63M_32_TEXT_31M = { + "LAION400M": _pcfg( + "https://github.com/wkcn/TinyCLIP-model-zoo/releases/download/checkpoints/TinyCLIP-auto-ViT-63M-32-Text-31M-LAION400M.pt", + ), + "LAIONYFCC400M": _pcfg( + "https://github.com/wkcn/TinyCLIP-model-zoo/releases/download/checkpoints/TinyCLIP-auto-ViT-63M-32-Text-31M-LAIONYFCC400M.pt", + ), +} + +_TINYCLIP_AUTO_VIT_45M_32_TEXT_18M = { + "LAION400M": _pcfg( + "https://github.com/wkcn/TinyCLIP-model-zoo/releases/download/checkpoints/TinyCLIP-auto-ViT-45M-32-Text-18M-LAION400M.pt", + ), + "LAIONYFCC400M": _pcfg( + "https://github.com/wkcn/TinyCLIP-model-zoo/releases/download/checkpoints/TinyCLIP-auto-ViT-45M-32-Text-18M-LAIONYFCC400M.pt", + ), +} + +_TINYCLIP_AUTO_VIT_22M_32_TEXT_10M = { + "LAION400M": _pcfg( + "https://github.com/wkcn/TinyCLIP-model-zoo/releases/download/checkpoints/TinyCLIP-auto-ViT-22M-32-Text-10M-LAION400M.pt", + ), +} + +_PRETRAINED = { + "RN50": _RN50, + "RN50-quickgelu": _RN50_quickgelu, + "RN101": _RN101, + "RN101-quickgelu": _RN101_quickgelu, + "RN50x4": _RN50x4, + "RN50x16": _RN50x16, + "RN50x64": _RN50x64, + "ViT-B-32": _VITB32, + "ViT-B-32-quickgelu": _VITB32_quickgelu, + "ViT-B-16": _VITB16, + "ViT-B-16-plus-240": _VITB16_PLUS_240, + "ViT-L-14": _VITL14, + "ViT-L-14-336": _VITL14_336, + "ViT-H-14": _VITH14, + "ViT-g-14": _VITg14, + + "TinyCLIP-ViT-39M-16-Text-19M": _TINYCLIP_VIT_39M_16_TEXT_19M, + "TinyCLIP-ViT-8M-16-Text-3M": _TINYCLIP_VIT_8M_16_TEXT_3M, + "TinyCLIP-ResNet-30M-Text-29M": _TINYCLIP_RESNET_30M_TEXT_29M, + "TinyCLIP-ResNet-19M-Text-19M": _TINYCLIP_RESNET_19M_TEXT_19M, + "TinyCLIP-ViT-61M-32-Text-29M": _TINYCLIP_VIT_61M_32_TEXT_29M, + "TinyCLIP-ViT-40M-32-Text-19M": _TINYCLIP_VIT_40M_32_TEXT_19M, + + "TinyCLIP-auto-ViT-63M-32-Text-31M": _TINYCLIP_AUTO_VIT_63M_32_TEXT_31M, + "TinyCLIP-auto-ViT-45M-32-Text-18M": _TINYCLIP_AUTO_VIT_45M_32_TEXT_18M, + "TinyCLIP-auto-ViT-22M-32-Text-10M": _TINYCLIP_AUTO_VIT_22M_32_TEXT_10M, +} + + +def list_pretrained(as_str: bool = False): + """ returns list of pretrained models + Returns a tuple (model_name, pretrain_tag) by default or 'name:tag' if as_str == True + """ + return [':'.join([k, t]) if as_str else (k, t) for k in _PRETRAINED.keys() for t in _PRETRAINED[k].keys()] + + +def list_pretrained_tag_models(tag: str): + """ return all models having the specified pretrain tag """ + models = [] + for k in _PRETRAINED.keys(): + if tag in _PRETRAINED[k]: + models.append(k) + return models + + +def list_pretrained_model_tags(model: str): + """ return all pretrain tags for the specified model architecture """ + tags = [] + if model in _PRETRAINED: + tags.extend(_PRETRAINED[model].keys()) + return tags + + +def is_pretrained_cfg(model: str, tag: str): + if model not in _PRETRAINED: + return False + return tag.lower() in _PRETRAINED[model] + + +def get_pretrained_cfg(model: str, tag: str): + if model not in _PRETRAINED: + return {} + model_pretrained = _PRETRAINED[model] + if tag in model_pretrained: + return model_pretrained[tag] + return model_pretrained.get(tag.lower(), {}) + + +def get_pretrained_url(model: str, tag: str): + cfg = get_pretrained_cfg(model, tag) + return cfg.get('url', '') + + +def is_local_master(): + return int(os.getenv('LOCAL_RANK', 0)) == 0 + + +def download_pretrained_from_url( + url: str = os.path.expanduser("~/.cache/clip"), + cache_dir: Union[str, None] = None, +): + + if not cache_dir: + cache_dir = os.path.expanduser("~/.cache/clip") + os.makedirs(cache_dir, exist_ok=True) + + filename = os.path.basename(url) + download_target = os.path.join(cache_dir, filename) + if is_local_master(): + for _ in range(20): + try: + return _download_pretrained(url, cache_dir) + except Exception as e: + print(f'Download pretrained: {url}, {cache_dir}, {e}') + time.sleep(10) + else: + while not os.path.exists(download_target): + time.sleep(1) + return download_target + + +def _download_pretrained(url: str, root: str = os.path.expanduser("~/.cache/clip")): + os.makedirs(root, exist_ok=True) + filename = os.path.basename(url) + + if 'openaipublic' in url: + expected_sha256 = url.split("/")[-2] + else: + expected_sha256 = '' + + download_target = os.path.join(root, filename) + + if os.path.exists(download_target) and not os.path.isfile(download_target): + raise RuntimeError( + f"{download_target} exists and is not a regular file") + + if os.path.isfile(download_target): + if expected_sha256: + if hashlib.sha256(open(download_target, "rb").read()).hexdigest() == expected_sha256: + return download_target + else: + warnings.warn( + f"{download_target} exists, but the SHA256 checksum does not match; re-downloading the file") + else: + return download_target + + download_target_tmp = download_target + ".tmp" + with urllib.request.urlopen(url) as source, open(download_target_tmp, "wb") as output: + with tqdm(total=int(source.info().get("Content-Length")), ncols=80, unit='iB', unit_scale=True) as loop: + while True: + buffer = source.read(8192) + if not buffer: + break + + output.write(buffer) + loop.update(len(buffer)) + + if expected_sha256 and hashlib.sha256(open(download_target_tmp, "rb").read()).hexdigest() != expected_sha256: + os.remove(download_target_tmp) + raise RuntimeError( + f"Model has been downloaded but the SHA256 checksum does not not match") + + os.rename(download_target_tmp, download_target) + return download_target + + +def has_hf_hub(necessary=False): + if not _has_hf_hub and necessary: + # if no HF Hub module installed, and it is necessary to continue, raise error + raise RuntimeError( + 'Hugging Face hub model specified but package not installed. Run `pip install huggingface_hub`.') + return _has_hf_hub + + +def download_pretrained_from_hf( + model_id: str, + filename: str = 'open_clip_pytorch_model.bin', + revision=None, + cache_dir: Union[str, None] = None, +): + has_hf_hub(True) + cached_file = hf_hub_download( + model_id, filename, revision=revision, cache_dir=cache_dir) + return cached_file + + +def download_pretrained( + cfg: Dict, + force_hf_hub: bool = False, + cache_dir: Union[str, None] = None, +): + target = '' + if not cfg: + return target + + download_url = cfg.get('url', '') + download_hf_hub = cfg.get('hf_hub', '') + if download_hf_hub and force_hf_hub: + # use HF hub even if url exists + download_url = '' + + if download_url: + target = download_pretrained_from_url( + download_url, cache_dir=cache_dir) + elif download_hf_hub: + has_hf_hub(True) + # we assume the hf_hub entries in pretrained config combine model_id + filename in + # 'org/model_name/filename.pt' form. To specify just the model id w/o filename and + # use 'open_clip_pytorch_model.bin' default, there must be a trailing slash 'org/model_name/'. + model_id, filename = os.path.split(download_hf_hub) + if filename: + target = download_pretrained_from_hf( + model_id, filename=filename, cache_dir=cache_dir) + else: + target = download_pretrained_from_hf(model_id, cache_dir=cache_dir) + + return target diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/tiny_clip/resnet.py b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/tiny_clip/resnet.py new file mode 100644 index 0000000000000000000000000000000000000000..081a794c49da8b0ab61a7dbf88436adb3b9d0c49 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/tiny_clip/resnet.py @@ -0,0 +1,187 @@ +import torch +from torch import nn +import torch.nn.functional as F +from collections import OrderedDict + + +class Bottleneck(nn.Module): + expansion = 4 + + def __init__(self, inplanes, planes, stride=1): + super().__init__() + + # all conv layers have stride 1. an avgpool is performed after the second convolution when stride > 1 + self.conv1 = nn.Conv2d(inplanes, planes, 1, bias=False) + self.bn1 = nn.BatchNorm2d(planes) + self.act1 = nn.ReLU(inplace=True) + + self.conv2 = nn.Conv2d(planes, planes, 3, padding=1, bias=False) + self.bn2 = nn.BatchNorm2d(planes) + self.act2 = nn.ReLU(inplace=True) + + self.avgpool = nn.AvgPool2d(stride) if stride > 1 else nn.Identity() + + self.conv3 = nn.Conv2d(planes, planes * self.expansion, 1, bias=False) + self.bn3 = nn.BatchNorm2d(planes * self.expansion) + self.act3 = nn.ReLU(inplace=True) + + self.downsample = None + self.stride = stride + + if stride > 1 or inplanes != planes * Bottleneck.expansion: + # downsampling layer is prepended with an avgpool, and the subsequent convolution has stride 1 + self.downsample = nn.Sequential(OrderedDict([ + ("-1", nn.AvgPool2d(stride)), + ("0", nn.Conv2d(inplanes, planes * + self.expansion, 1, stride=1, bias=False)), + ("1", nn.BatchNorm2d(planes * self.expansion)) + ])) + + def forward(self, x: torch.Tensor): + identity = x + + out = self.act1(self.bn1(self.conv1(x))) + out = self.act2(self.bn2(self.conv2(out))) + out = self.avgpool(out) + out = self.bn3(self.conv3(out)) + + if self.downsample is not None: + identity = self.downsample(x) + + out += identity + out = self.act3(out) + return out + + +class AttentionPool2d(nn.Module): + def __init__(self, spacial_dim: int, embed_dim: int, num_heads: int, output_dim: int = None): + super().__init__() + self.positional_embedding = nn.Parameter(torch.randn( + spacial_dim ** 2 + 1, embed_dim) / embed_dim ** 0.5) + self.k_proj = nn.Linear(embed_dim, embed_dim) + self.q_proj = nn.Linear(embed_dim, embed_dim) + self.v_proj = nn.Linear(embed_dim, embed_dim) + self.c_proj = nn.Linear(embed_dim, output_dim or embed_dim) + self.num_heads = num_heads + + def forward(self, x): + x = x.reshape(x.shape[0], x.shape[1], x.shape[2] + * x.shape[3]).permute(2, 0, 1) # NCHW -> (HW)NC + x = torch.cat([x.mean(dim=0, keepdim=True), x], dim=0) # (HW+1)NC + x = x + self.positional_embedding[:, None, :].to(x.dtype) # (HW+1)NC + x, _ = F.multi_head_attention_forward( + query=x, key=x, value=x, + embed_dim_to_check=x.shape[-1], + num_heads=self.num_heads, + q_proj_weight=self.q_proj.weight, + k_proj_weight=self.k_proj.weight, + v_proj_weight=self.v_proj.weight, + in_proj_weight=None, + in_proj_bias=torch.cat( + [self.q_proj.bias, self.k_proj.bias, self.v_proj.bias]), + bias_k=None, + bias_v=None, + add_zero_attn=False, + dropout_p=0, + out_proj_weight=self.c_proj.weight, + out_proj_bias=self.c_proj.bias, + use_separate_proj_weight=True, + training=self.training, + need_weights=False + ) + + return x[0] + + +class ModifiedResNet(nn.Module): + """ + A ResNet class that is similar to torchvision's but contains the following changes: + - There are now 3 "stem" convolutions as opposed to 1, with an average pool instead of a max pool. + - Performs anti-aliasing strided convolutions, where an avgpool is prepended to convolutions with stride > 1 + - The final pooling layer is a QKV attention instead of an average pool + """ + + def __init__(self, layers, output_dim, heads, image_size=224, width=64): + super().__init__() + self.output_dim = output_dim + self.image_size = image_size + + # the 3-layer stem + self.conv1 = nn.Conv2d(3, width // 2, kernel_size=3, + stride=2, padding=1, bias=False) + self.bn1 = nn.BatchNorm2d(width // 2) + self.act1 = nn.ReLU(inplace=True) + self.conv2 = nn.Conv2d(width // 2, width // 2, + kernel_size=3, padding=1, bias=False) + self.bn2 = nn.BatchNorm2d(width // 2) + self.act2 = nn.ReLU(inplace=True) + self.conv3 = nn.Conv2d( + width // 2, width, kernel_size=3, padding=1, bias=False) + self.bn3 = nn.BatchNorm2d(width) + self.act3 = nn.ReLU(inplace=True) + self.avgpool = nn.AvgPool2d(2) + + # residual layers + self._inplanes = width # this is a *mutable* variable used during construction + self.layer1 = self._make_layer(width, layers[0]) + self.layer2 = self._make_layer(width * 2, layers[1], stride=2) + self.layer3 = self._make_layer(width * 4, layers[2], stride=2) + self.layer4 = self._make_layer(width * 8, layers[3], stride=2) + + embed_dim = width * 32 # the ResNet feature dimension + self.head_dim = embed_dim // heads + self.attnpool = AttentionPool2d( + image_size // 32, embed_dim, heads, output_dim) + + self.init_parameters() + + def _make_layer(self, planes, blocks, stride=1): + layers = [Bottleneck(self._inplanes, planes, stride)] + + self._inplanes = planes * Bottleneck.expansion + for _ in range(1, blocks): + layers.append(Bottleneck(self._inplanes, planes)) + + return nn.Sequential(*layers) + + def init_parameters(self): + if self.attnpool is not None: + std = self.attnpool.c_proj.in_features ** -0.5 + nn.init.normal_(self.attnpool.q_proj.weight, std=std) + nn.init.normal_(self.attnpool.k_proj.weight, std=std) + nn.init.normal_(self.attnpool.v_proj.weight, std=std) + nn.init.normal_(self.attnpool.c_proj.weight, std=std) + + for resnet_block in [self.layer1, self.layer2, self.layer3, self.layer4]: + for name, param in resnet_block.named_parameters(): + if name.endswith("bn3.weight"): + nn.init.zeros_(param) + + def lock(self, unlocked_groups=0, freeze_bn_stats=False): + assert unlocked_groups == 0, 'partial locking not currently supported for this model' + for param in self.parameters(): + param.requires_grad = False + if freeze_bn_stats: + freeze_batch_norm_2d(self) + + @torch.jit.ignore + def set_grad_checkpointing(self, enable=True): + # FIXME support for non-transformer + pass + + def stem(self, x): + x = self.act1(self.bn1(self.conv1(x))) + x = self.act2(self.bn2(self.conv2(x))) + x = self.act3(self.bn3(self.conv3(x))) + x = self.avgpool(x) + return x + + def forward(self, x): + x = self.stem(x) + x = self.layer1(x) + x = self.layer2(x) + x = self.layer3(x) + x = self.layer4(x) + x = self.attnpool(x) + + return x diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/tiny_clip/timm_model.py b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/tiny_clip/timm_model.py new file mode 100644 index 0000000000000000000000000000000000000000..068acfd254e898655719d5e1a09f3a4e1c612ddf --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/tiny_clip/timm_model.py @@ -0,0 +1,122 @@ +""" timm model adapter + +Wraps timm (https://github.com/rwightman/pytorch-image-models) models for use as a vision tower in CLIP model. +""" +from collections import OrderedDict + +import torch.nn as nn + +try: + import timm + from timm.models.layers import Mlp, to_2tuple +except: + timm = None +try: + from timm.models.layers.attention_pool2d import RotAttentionPool2d + from timm.models.layers.attention_pool2d import AttentionPool2d as AbsAttentionPool2d +except: + pass + +try: + from .utils import freeze_batch_norm_2d +except: + from utils import freeze_batch_norm_2d + + +class TimmModel(nn.Module): + """ timm model adapter + # FIXME this adapter is a work in progress, may change in ways that break weight compat + """ + + def __init__( + self, + model_name, + embed_dim, + image_size=224, + pool='avg', + proj='linear', + drop=0., + pretrained=False): + super().__init__() + if timm is None: + raise RuntimeError("Please `pip install timm` to use timm models.") + + self.image_size = to_2tuple(image_size) + self.trunk = timm.create_model(model_name, pretrained=pretrained) + feat_size = self.trunk.default_cfg.get('pool_size', None) + feature_ndim = 1 if not feat_size else 2 + if pool in ('abs_attn', 'rot_attn'): + assert feature_ndim == 2 + # if attn pooling used, remove both classifier and default pool + self.trunk.reset_classifier(0, global_pool='') + else: + # reset global pool if pool config set, otherwise leave as network default + reset_kwargs = dict(global_pool=pool) if pool else {} + self.trunk.reset_classifier(0, **reset_kwargs) + prev_chs = self.trunk.num_features + + head_layers = OrderedDict() + if pool == 'abs_attn': + head_layers['pool'] = AbsAttentionPool2d( + prev_chs, feat_size=feat_size, out_features=embed_dim) + prev_chs = embed_dim + elif pool == 'rot_attn': + head_layers['pool'] = RotAttentionPool2d( + prev_chs, out_features=embed_dim) + prev_chs = embed_dim + else: + assert proj, 'projection layer needed if non-attention pooling is used.' + + # NOTE attention pool ends with a projection layer, so proj should usually be set to '' if such pooling is used + if proj == 'linear': + head_layers['drop'] = nn.Dropout(drop) + head_layers['proj'] = nn.Linear(prev_chs, embed_dim) + elif proj == 'mlp': + head_layers['mlp'] = Mlp( + prev_chs, 2 * embed_dim, embed_dim, drop=drop) + + self.head = nn.Sequential(head_layers) + + def lock(self, unlocked_groups=0, freeze_bn_stats=False): + """ lock modules + Args: + unlocked_groups (int): leave last n layer groups unlocked (default: 0) + """ + if not unlocked_groups: + # lock full model + for param in self.trunk.parameters(): + param.requires_grad = False + if freeze_bn_stats: + freeze_batch_norm_2d(self.trunk) + else: + # NOTE: partial freeze requires latest timm (master) branch and is subject to change + try: + # FIXME import here until API stable and in an official release + from timm.models.helpers import group_parameters, group_modules + except ImportError: + raise RuntimeError( + 'Please install latest timm `pip install git+https://github.com/rwightman/pytorch-image-models`') + matcher = self.trunk.group_matcher() + gparams = group_parameters(self.trunk, matcher) + max_layer_id = max(gparams.keys()) + max_layer_id = max_layer_id - unlocked_groups + for group_idx in range(max_layer_id + 1): + group = gparams[group_idx] + for param in group: + self.trunk.get_parameter(param).requires_grad = False + if freeze_bn_stats: + gmodules = group_modules(self.trunk, matcher, reverse=True) + gmodules = {k for k, v in gmodules.items() if v <= + max_layer_id} + freeze_batch_norm_2d(self.trunk, gmodules) + + def forward(self, x): + x = self.trunk(x) + x = self.head(x) + return x + + +if __name__ == '__main__': + model = TimmModel('vit_base_patch32_224_in21k', + 512, pool='', pretrained=False) + print(model) diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/tiny_clip/tokenizer.py b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/tiny_clip/tokenizer.py new file mode 100644 index 0000000000000000000000000000000000000000..59ad0dce4ba1b86001205e650c38857ed7468cdf --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/tiny_clip/tokenizer.py @@ -0,0 +1,215 @@ +""" CLIP tokenizer + +Copied from https://github.com/openai/CLIP. Originally MIT License, Copyright (c) 2021 OpenAI. +""" +import gzip +import html +import os +from functools import lru_cache +from typing import Union, List + +import ftfy +import regex as re +import torch + + +@lru_cache() +def default_bpe(): + return os.path.join(os.path.dirname(os.path.abspath(__file__)), "bpe_simple_vocab_16e6.txt.gz") + + +@lru_cache() +def bytes_to_unicode(): + """ + Returns list of utf-8 byte and a corresponding list of unicode strings. + The reversible bpe codes work on unicode strings. + This means you need a large # of unicode characters in your vocab if you want to avoid UNKs. + When you're at something like a 10B token dataset you end up needing around 5K for decent coverage. + This is a signficant percentage of your normal, say, 32K bpe vocab. + To avoid that, we want lookup tables between utf-8 bytes and unicode strings. + And avoids mapping to whitespace/control characters the bpe code barfs on. + """ + bs = list(range(ord("!"), ord("~") + 1)) + list(range(ord("¡"), + ord("¬") + 1)) + list(range(ord("®"), ord("ÿ") + 1)) + cs = bs[:] + n = 0 + for b in range(2**8): + if b not in bs: + bs.append(b) + cs.append(2**8 + n) + n += 1 + cs = [chr(n) for n in cs] + return dict(zip(bs, cs)) + + +def get_pairs(word): + """Return set of symbol pairs in a word. + Word is represented as tuple of symbols (symbols being variable-length strings). + """ + pairs = set() + prev_char = word[0] + for char in word[1:]: + pairs.add((prev_char, char)) + prev_char = char + return pairs + + +def basic_clean(text): + text = ftfy.fix_text(text) + text = html.unescape(html.unescape(text)) + return text.strip() + + +def whitespace_clean(text): + text = re.sub(r'\s+', ' ', text) + text = text.strip() + return text + + +class SimpleTokenizer(object): + def __init__(self, bpe_path: str = default_bpe(), special_tokens=None): + self.byte_encoder = bytes_to_unicode() + self.byte_decoder = {v: k for k, v in self.byte_encoder.items()} + merges = gzip.open(bpe_path).read().decode("utf-8").split('\n') + merges = merges[1:49152 - 256 - 2 + 1] + merges = [tuple(merge.split()) for merge in merges] + vocab = list(bytes_to_unicode().values()) + vocab = vocab + [v + '' for v in vocab] + for merge in merges: + vocab.append(''.join(merge)) + if not special_tokens: + special_tokens = ['', ''] + else: + special_tokens = ['', + ''] + special_tokens + vocab.extend(special_tokens) + self.encoder = dict(zip(vocab, range(len(vocab)))) + self.decoder = {v: k for k, v in self.encoder.items()} + self.bpe_ranks = dict(zip(merges, range(len(merges)))) + self.cache = {t: t for t in special_tokens} + special = "|".join(special_tokens) + self.pat = re.compile( + special + r"""|'s|'t|'re|'ve|'m|'ll|'d|[\p{L}]+|[\p{N}]|[^\s\p{L}\p{N}]+""", re.IGNORECASE) + + self.vocab_size = len(self.encoder) + self.all_special_ids = [self.encoder[t] for t in special_tokens] + + def bpe(self, token): + if token in self.cache: + return self.cache[token] + word = tuple(token[:-1]) + (token[-1] + '',) + pairs = get_pairs(word) + + if not pairs: + return token + '' + + while True: + bigram = min(pairs, key=lambda pair: self.bpe_ranks.get( + pair, float('inf'))) + if bigram not in self.bpe_ranks: + break + first, second = bigram + new_word = [] + i = 0 + while i < len(word): + try: + j = word.index(first, i) + new_word.extend(word[i:j]) + i = j + except: + new_word.extend(word[i:]) + break + + if word[i] == first and i < len(word) - 1 and word[i + 1] == second: + new_word.append(first + second) + i += 2 + else: + new_word.append(word[i]) + i += 1 + new_word = tuple(new_word) + word = new_word + if len(word) == 1: + break + else: + pairs = get_pairs(word) + word = ' '.join(word) + self.cache[token] = word + return word + + def encode(self, text): + bpe_tokens = [] + text = whitespace_clean(basic_clean(text)).lower() + for token in re.findall(self.pat, text): + token = ''.join(self.byte_encoder[b] + for b in token.encode('utf-8')) + bpe_tokens.extend(self.encoder[bpe_token] + for bpe_token in self.bpe(token).split(' ')) + return bpe_tokens + + def decode(self, tokens): + text = ''.join([self.decoder[token] for token in tokens]) + text = bytearray([self.byte_decoder[c] for c in text]).decode( + 'utf-8', errors="replace").replace('', ' ') + return text + + +_tokenizer = SimpleTokenizer() + + +def tokenize(texts: Union[str, List[str]], context_length: int = 77) -> torch.LongTensor: + """ + Returns the tokenized representation of given input string(s) + + Parameters + ---------- + texts : Union[str, List[str]] + An input string or a list of input strings to tokenize + context_length : int + The context length to use; all CLIP models use 77 as the context length + + Returns + ------- + A two-dimensional tensor containing the resulting tokens, shape = [number of input strings, context_length] + """ + if isinstance(texts, str): + texts = [texts] + + sot_token = _tokenizer.encoder[""] + eot_token = _tokenizer.encoder[""] + all_tokens = [[sot_token] + + _tokenizer.encode(text) + [eot_token] for text in texts] + result = torch.zeros(len(all_tokens), context_length, dtype=torch.long) + + for i, tokens in enumerate(all_tokens): + if len(tokens) > context_length: + tokens = tokens[:context_length] # Truncate + tokens[-1] = eot_token + result[i, :len(tokens)] = torch.tensor(tokens) + + return result + + +class HFTokenizer: + """HuggingFace tokenizer wrapper""" + + def __init__(self, tokenizer_name: str): + from transformers import AutoTokenizer + self.tokenizer = AutoTokenizer.from_pretrained(tokenizer_name) + + def save_pretrained(self, dest): + self.tokenizer.save_pretrained(dest) + + def __call__(self, texts: Union[str, List[str]], context_length: int = 77) -> torch.Tensor: + # same cleaning as for default tokenizer, except lowercasing + # adding lower (for case-sensitive tokenizers) will make it more robust but less sensitive to nuance + if isinstance(texts, str): + texts = [texts] + texts = [whitespace_clean(basic_clean(text)) for text in texts] + input_ids = self.tokenizer( + texts, + return_tensors='pt', + max_length=context_length, + padding='max_length', + truncation=True, + ).input_ids + return input_ids diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/tiny_clip/transform.py b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/tiny_clip/transform.py new file mode 100644 index 0000000000000000000000000000000000000000..f6780eed3cd3ab84cfb1221c567f20a758e88c79 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/tiny_clip/transform.py @@ -0,0 +1,123 @@ +from typing import Optional, Sequence, Tuple + +import torch +import torch.nn as nn +import torchvision.transforms.functional as F + +from torchvision.transforms import Normalize, Compose, RandomResizedCrop, InterpolationMode, ToTensor, Resize, \ + CenterCrop + +from .constants import OPENAI_DATASET_MEAN, OPENAI_DATASET_STD + + +class ResizeMaxSize(nn.Module): + + def __init__(self, max_size, interpolation=InterpolationMode.BICUBIC, fn='max', fill=0): + super().__init__() + if not isinstance(max_size, int): + raise TypeError(f"Size should be int. Got {type(max_size)}") + self.max_size = max_size + self.interpolation = interpolation + self.fn = min if fn == 'min' else min + self.fill = fill + + def forward(self, img): + if isinstance(img, torch.Tensor): + height, width = img.shape[:2] + else: + width, height = img.size + scale = self.max_size / float(max(height, width)) + if scale != 1.0: + new_size = tuple(round(dim * scale) for dim in (height, width)) + img = F.resize(img, new_size, self.interpolation) + pad_h = self.max_size - new_size[0] + pad_w = self.max_size - new_size[1] + img = F.pad(img, padding=[ + pad_w // 2, pad_h // 2, pad_w - pad_w // 2, pad_h - pad_h // 2], fill=self.fill) + return img + + +class ResizeMaxSize(nn.Module): + + def __init__(self, max_size, interpolation=InterpolationMode.BICUBIC, fn='max', fill=0): + super().__init__() + if not isinstance(max_size, int): + raise TypeError(f"Size should be int. Got {type(max_size)}") + self.max_size = max_size + self.interpolation = interpolation + self.fn = min if fn == 'min' else min + self.fill = fill + + def forward(self, img): + if isinstance(img, torch.Tensor): + height, width = img.shape[:2] + else: + width, height = img.size + scale = self.max_size / float(max(height, width)) + if scale != 1.0: + new_size = tuple(round(dim * scale) for dim in (height, width)) + img = F.resize(img, new_size, self.interpolation) + pad_h = self.max_size - new_size[0] + pad_w = self.max_size - new_size[1] + img = F.pad(img, padding=[ + pad_w // 2, pad_h // 2, pad_w - pad_w // 2, pad_h - pad_h // 2], fill=self.fill) + return img + + +def _convert_to_rgb(image): + return image.convert('RGB') + + +def image_transform( + image_size: int, + is_train: bool, + mean: Optional[Tuple[float, ...]] = None, + std: Optional[Tuple[float, ...]] = None, + resize_longest_max: bool = False, + fill_color: int = 0, + val_keep_ratio: bool = True, +): + + mean = mean or OPENAI_DATASET_MEAN + if not isinstance(mean, (list, tuple)): + mean = (mean,) * 3 + + std = std or OPENAI_DATASET_STD + if not isinstance(std, (list, tuple)): + std = (std,) * 3 + + if isinstance(image_size, (list, tuple)) and image_size[0] == image_size[1]: + # for square size, pass size as int so that Resize() uses aspect preserving shortest edge + image_size = image_size[0] + + normalize = Normalize(mean=mean, std=std) + if is_train: + return Compose([ + RandomResizedCrop(image_size, scale=(0.9, 1.0), + interpolation=InterpolationMode.BICUBIC), + _convert_to_rgb, + ToTensor(), + normalize, + ]) + else: + if resize_longest_max: + transforms = [ + ResizeMaxSize(image_size, fill=fill_color) + ] + else: + if val_keep_ratio: + transforms = [ + Resize(image_size, interpolation=InterpolationMode.BICUBIC), + CenterCrop(image_size), + ] + else: + transforms = [ + Resize((image_size, image_size), + interpolation=InterpolationMode.BICUBIC), + ] + transforms.extend([ + _convert_to_rgb, + ToTensor(), + normalize, + ]) + return Compose(transforms) diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/tiny_clip/utils.py b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/tiny_clip/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..e2ff1fdada90142a35dede8788034b2d9f739b4e --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/tiny_clip/utils.py @@ -0,0 +1,62 @@ +from itertools import repeat +import collections.abc + +from torch import nn as nn +from torchvision.ops.misc import FrozenBatchNorm2d + + +def freeze_batch_norm_2d(module, module_match={}, name=''): + """ + Converts all `BatchNorm2d` and `SyncBatchNorm` layers of provided module into `FrozenBatchNorm2d`. If `module` is + itself an instance of either `BatchNorm2d` or `SyncBatchNorm`, it is converted into `FrozenBatchNorm2d` and + returned. Otherwise, the module is walked recursively and submodules are converted in place. + + Args: + module (torch.nn.Module): Any PyTorch module. + module_match (dict): Dictionary of full module names to freeze (all if empty) + name (str): Full module name (prefix) + + Returns: + torch.nn.Module: Resulting module + + Inspired by https://github.com/pytorch/pytorch/blob/a5895f85be0f10212791145bfedc0261d364f103/torch/nn/modules/batchnorm.py#L762 + """ + res = module + is_match = True + if module_match: + is_match = name in module_match + if is_match and isinstance(module, (nn.modules.batchnorm.BatchNorm2d, nn.modules.batchnorm.SyncBatchNorm)): + res = FrozenBatchNorm2d(module.num_features) + res.num_features = module.num_features + res.affine = module.affine + if module.affine: + res.weight.data = module.weight.data.clone().detach() + res.bias.data = module.bias.data.clone().detach() + res.running_mean.data = module.running_mean.data + res.running_var.data = module.running_var.data + res.eps = module.eps + else: + for child_name, child in module.named_children(): + full_child_name = '.'.join( + [name, child_name]) if name else child_name + new_child = freeze_batch_norm_2d( + child, module_match, full_child_name) + if new_child is not child: + res.add_module(child_name, new_child) + return res + + +# From PyTorch internals +def _ntuple(n): + def parse(x): + if isinstance(x, collections.abc.Iterable): + return x + return tuple(repeat(x, n)) + return parse + + +to_1tuple = _ntuple(1) +to_2tuple = _ntuple(2) +to_3tuple = _ntuple(3) +to_4tuple = _ntuple(4) +def to_ntuple(n, x): return _ntuple(n)(x) diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/tiny_clip/version.py b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/tiny_clip/version.py new file mode 100644 index 0000000000000000000000000000000000000000..668c3446ee12c61dc54e5f9cacdd3b778505118c --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/tiny_clip/version.py @@ -0,0 +1 @@ +__version__ = '2.0.2' diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/tiny_clip/weight_inherit.py b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/tiny_clip/weight_inherit.py new file mode 100644 index 0000000000000000000000000000000000000000..b10c968a9922db089df144ea33eb34b204cf3dfb --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/open_clip/tiny_clip/weight_inherit.py @@ -0,0 +1,203 @@ +import torch +import re +from collections import defaultdict + + +BLOCKS_PATTERNS = [ + # blocks... + (re.compile(r"visual.blocks\.(\d+)\.(\d+)\.(.*?)$"), 'visual.blocks.{}.{}.{}'), + # TinyViT + (re.compile(r"layers.(\d+)\.blocks\.(\d+)\.(.*?)$"), 'layers.{}.blocks.{}.{}'), + # ResNet + (re.compile(r'visual.layer(\d+).(\d+).(.*?)$'), 'visual.layer{}.{}.{}'), +] + +TRANS_PATTENS = [ + (re.compile(r"resblocks\.(\d+)\.(.*?)$"), 'resblocks.{}.{}'), +] + + +def get_depth_state(state_dict): + state = defaultdict(list) + tstr = None + for k, v in state_dict.items(): + # k is the name of the parameter `v` + for pts in [BLOCKS_PATTERNS, TRANS_PATTENS]: + for pt, s in pts: + match = pt.search(k) + if match is not None: + if tstr is not None: + assert tstr == s, (tstr, s) + else: + tstr = s + groups = match.groups() + if len(groups) == 3: + stage_id, block_id = map(int, groups[:2]) + postname = groups[2] + new_name = tstr.format(stage_id, block_id, postname) + else: + stage_id = 0 + block_id = int(groups[0]) + postname = groups[1] + new_name = tstr.format(block_id, postname) + assert k.endswith(new_name) + prename = k[:-len(new_name)] + stage = state[stage_id] + if block_id >= len(stage): + stage.extend([list()] * (block_id - len(stage) + 1)) + + stage[block_id].append((v, (prename, postname))) + assert tstr is not None + return state, tstr + + +def prune_param(param, shape): + if param.numel() == 1: + return param + # select the front param + sl = [slice(0, s) for s in shape] + param = param[sl] + assert param.shape == shape, (param.shape, shape) + return param + + +def compute_dict_params(state_dict): + params = 0 + for v in state_dict.values(): + params += v.numel() + return params + + +def weight_inherit(student_state_dict, teacher_state_dict, head_dim): + # the function will overwrite student_state_dict + student_depth_state, tstr = get_depth_state(student_state_dict) + teacher_depth_state, tstr2 = get_depth_state(teacher_state_dict) + assert tstr == tstr2 + assert len(student_depth_state) == len(teacher_depth_state) + # remap depth + vised = set() + for si in sorted(student_depth_state.keys()): + student_depth = len(student_depth_state[si]) + teacher_depth = len(teacher_depth_state[si]) + # interval_front + encoder_type = 'interval_front' + step = teacher_depth // max(student_depth, 1) + idx = list(range(0, student_depth * step, step)) + print( + f'sample_method for {encoder_type}: stage: {si} depth: {teacher_depth} -> {student_depth}, idx: {idx}') + + for i, j in enumerate(idx): + for v, (prename, postname) in teacher_depth_state[si][j]: + try: + new_name = prename + tstr.format(si, i, postname) + except: + new_name = '' + if new_name not in student_state_dict: + # transformer + assert si == 0 + new_name = prename + tstr.format(i, postname) + + assert new_name in student_state_dict, new_name + if '.qkv.' in new_name or '.attn.in_proj_' in new_name: + # qkv shape: (out_dim[q, k, v], in_dim) + # out - q - n_heads * head_dim + student_v = student_state_dict[new_name] + student_head = student_v.size(0) // (3 * head_dim) + teacher_head = v.size(0) // (3 * head_dim) + if new_name.endswith('.qkv.weight') or new_name.endswith('.attn.in_proj_weight'): + # (3 * H * head_dim, in_dim) + student_dim = student_v.size(1) + teacher_dim = v.size(1) + student_state_dict[new_name] = v.view(3, teacher_head, head_dim, teacher_dim)[ + :, :student_head, :, :student_dim].reshape(3 * student_head * head_dim, student_dim) + else: + assert new_name.endswith( + '.qkv.bias') or new_name.endswith('.attn.in_proj_bias') + student_state_dict[new_name] = v.view(3, teacher_head, head_dim)[ + :, :student_head].reshape(-1,) + else: + try: + student_state_dict[new_name] = prune_param( + v, student_state_dict[new_name].shape) + except: + print(new_name, v.shape) + raise + vised.add(new_name) + other_param_names = set(student_state_dict.keys()) - vised + print('OTHER Pruned Params:', other_param_names) + for k in other_param_names: + student_state_dict[k] = prune_param( + teacher_state_dict[k], student_state_dict[k].shape) + vised.add(k) + assert vised == set(student_state_dict.keys()), set( + student_state_dict.keys()) - vised + student_num_params = compute_dict_params(student_state_dict) + teacher_num_params = compute_dict_params(teacher_state_dict) + print( + f'Weight Inherit: {teacher_num_params} -> {student_num_params}, {student_num_params / teacher_num_params * 100:.2f}%') + return student_state_dict + + +if __name__ == '__main__': + def weight_inherit_for_tinyvit(): + from tiny_vit import tiny_vit_5m_224, tiny_vit_21m_224 + student_model = tiny_vit_5m_224() + teacher_model = tiny_vit_21m_224() + + student_state_dict = student_model.state_dict() + teacher_state_dict = teacher_model.state_dict() + + weight_inherit(student_state_dict, teacher_state_dict) + + # load inherited weights + student_model.load_state_dict(student_state_dict) + + def weight_inherit_for_open_clip_transformer(): + from open_clip.model import Transformer + student_model = Transformer(width=256, layers=3, heads=256 // 64) + teacher_model = Transformer(width=512, layers=12, heads=512 // 64) + + student_state_dict = student_model.state_dict() + teacher_state_dict = teacher_model.state_dict() + + weight_inherit(student_state_dict, teacher_state_dict, head_dim=64) + + # load inherited weights + student_model.load_state_dict(student_state_dict) + + def weight_inherit_for_open_clip_vision(): + from open_clip.model import ImageEncoder, CLIPVisionCfg + student_cfg = CLIPVisionCfg(layers=3, width=256) + teacher_cfg = CLIPVisionCfg(layers=6, width=512) + student_model = ImageEncoder(256, student_cfg, quick_gelu=False) + teacher_model = ImageEncoder(512, teacher_cfg, quick_gelu=False) + + student_state_dict = student_model.state_dict() + teacher_state_dict = teacher_model.state_dict() + + weight_inherit(student_state_dict, teacher_state_dict, head_dim=64) + + # load inherited weights + student_model.load_state_dict(student_state_dict) + + def weight_inherit_for_open_clip_resnet(): + from open_clip.model import ImageEncoder, CLIPVisionCfg + # layers to identify ResNet + student_cfg = CLIPVisionCfg(image_size=224, layers=[ + 1, 1, 1, 1], width=64, patch_size=None) + teacher_cfg = CLIPVisionCfg(image_size=224, layers=[ + 2, 2, 6, 2], width=64, patch_size=None) + student_model = ImageEncoder(64, student_cfg, quick_gelu=False) + teacher_model = ImageEncoder(64, teacher_cfg, quick_gelu=False) + + student_state_dict = student_model.state_dict() + teacher_state_dict = teacher_model.state_dict() + + weight_inherit(student_state_dict, teacher_state_dict, head_dim=64) + + # weight_inherit_for_tinyvit() + weight_inherit_for_open_clip_transformer() + weight_inherit_for_open_clip_vision() + weight_inherit_for_open_clip_resnet() + + print("OVER") diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/segment_anything/__init__.py b/downstream/ProxyCLIP_TPAMI/clipself/src/segment_anything/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..34383d83f5e76bc801f31b20e5651e383be348b6 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/segment_anything/__init__.py @@ -0,0 +1,15 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +from .build_sam import ( + build_sam, + build_sam_vit_h, + build_sam_vit_l, + build_sam_vit_b, + sam_model_registry, +) +from .predictor import SamPredictor +from .automatic_mask_generator import SamAutomaticMaskGenerator diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/segment_anything/automatic_mask_generator.py b/downstream/ProxyCLIP_TPAMI/clipself/src/segment_anything/automatic_mask_generator.py new file mode 100644 index 0000000000000000000000000000000000000000..d5a8c969207f119feff7087f94e044403acdff00 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/segment_anything/automatic_mask_generator.py @@ -0,0 +1,372 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import numpy as np +import torch +from torchvision.ops.boxes import batched_nms, box_area # type: ignore + +from typing import Any, Dict, List, Optional, Tuple + +from .modeling import Sam +from .predictor import SamPredictor +from .utils.amg import ( + MaskData, + area_from_rle, + batch_iterator, + batched_mask_to_box, + box_xyxy_to_xywh, + build_all_layer_point_grids, + calculate_stability_score, + coco_encode_rle, + generate_crop_boxes, + is_box_near_crop_edge, + mask_to_rle_pytorch, + remove_small_regions, + rle_to_mask, + uncrop_boxes_xyxy, + uncrop_masks, + uncrop_points, +) + + +class SamAutomaticMaskGenerator: + def __init__( + self, + model: Sam, + points_per_side: Optional[int] = 32, + points_per_batch: int = 64, + pred_iou_thresh: float = 0.88, + stability_score_thresh: float = 0.95, + stability_score_offset: float = 1.0, + box_nms_thresh: float = 0.7, + crop_n_layers: int = 0, + crop_nms_thresh: float = 0.7, + crop_overlap_ratio: float = 512 / 1500, + crop_n_points_downscale_factor: int = 1, + point_grids: Optional[List[np.ndarray]] = None, + min_mask_region_area: int = 0, + output_mode: str = "binary_mask", + ) -> None: + """ + Using a SAM model, generates masks for the entire image. + Generates a grid of point prompts over the image, then filters + low quality and duplicate masks. The default settings are chosen + for SAM with a ViT-H backbone. + + Arguments: + model (Sam): The SAM model to use for mask prediction. + points_per_side (int or None): The number of points to be sampled + along one side of the image. The total number of points is + points_per_side**2. If None, 'point_grids' must provide explicit + point sampling. + points_per_batch (int): Sets the number of points run simultaneously + by the model. Higher numbers may be faster but use more GPU memory. + pred_iou_thresh (float): A filtering threshold in [0,1], using the + model's predicted mask quality. + stability_score_thresh (float): A filtering threshold in [0,1], using + the stability of the mask under changes to the cutoff used to binarize + the model's mask predictions. + stability_score_offset (float): The amount to shift the cutoff when + calculated the stability score. + box_nms_thresh (float): The box IoU cutoff used by non-maximal + suppression to filter duplicate masks. + crop_n_layers (int): If >0, mask prediction will be run again on + crops of the image. Sets the number of layers to run, where each + layer has 2**i_layer number of image crops. + crop_nms_thresh (float): The box IoU cutoff used by non-maximal + suppression to filter duplicate masks between different crops. + crop_overlap_ratio (float): Sets the degree to which crops overlap. + In the first crop layer, crops will overlap by this fraction of + the image length. Later layers with more crops scale down this overlap. + crop_n_points_downscale_factor (int): The number of points-per-side + sampled in layer n is scaled down by crop_n_points_downscale_factor**n. + point_grids (list(np.ndarray) or None): A list over explicit grids + of points used for sampling, normalized to [0,1]. The nth grid in the + list is used in the nth crop layer. Exclusive with points_per_side. + min_mask_region_area (int): If >0, postprocessing will be applied + to remove disconnected regions and holes in masks with area smaller + than min_mask_region_area. Requires opencv. + output_mode (str): The form masks are returned in. Can be 'binary_mask', + 'uncompressed_rle', or 'coco_rle'. 'coco_rle' requires pycocotools. + For large resolutions, 'binary_mask' may consume large amounts of + memory. + """ + + assert (points_per_side is None) != ( + point_grids is None + ), "Exactly one of points_per_side or point_grid must be provided." + if points_per_side is not None: + self.point_grids = build_all_layer_point_grids( + points_per_side, + crop_n_layers, + crop_n_points_downscale_factor, + ) + elif point_grids is not None: + self.point_grids = point_grids + else: + raise ValueError("Can't have both points_per_side and point_grid be None.") + + assert output_mode in [ + "binary_mask", + "uncompressed_rle", + "coco_rle", + ], f"Unknown output_mode {output_mode}." + if output_mode == "coco_rle": + from pycocotools import mask as mask_utils # type: ignore # noqa: F401 + + if min_mask_region_area > 0: + import cv2 # type: ignore # noqa: F401 + + self.predictor = SamPredictor(model) + self.points_per_batch = points_per_batch + self.pred_iou_thresh = pred_iou_thresh + self.stability_score_thresh = stability_score_thresh + self.stability_score_offset = stability_score_offset + self.box_nms_thresh = box_nms_thresh + self.crop_n_layers = crop_n_layers + self.crop_nms_thresh = crop_nms_thresh + self.crop_overlap_ratio = crop_overlap_ratio + self.crop_n_points_downscale_factor = crop_n_points_downscale_factor + self.min_mask_region_area = min_mask_region_area + self.output_mode = output_mode + + @torch.no_grad() + def generate(self, image: np.ndarray) -> List[Dict[str, Any]]: + """ + Generates masks for the given image. + + Arguments: + image (np.ndarray): The image to generate masks for, in HWC uint8 format. + + Returns: + list(dict(str, any)): A list over records for masks. Each record is + a dict containing the following keys: + segmentation (dict(str, any) or np.ndarray): The mask. If + output_mode='binary_mask', is an array of shape HW. Otherwise, + is a dictionary containing the RLE. + bbox (list(float)): The box around the mask, in XYWH format. + area (int): The area in pixels of the mask. + predicted_iou (float): The model's own prediction of the mask's + quality. This is filtered by the pred_iou_thresh parameter. + point_coords (list(list(float))): The point coordinates input + to the model to generate this mask. + stability_score (float): A measure of the mask's quality. This + is filtered on using the stability_score_thresh parameter. + crop_box (list(float)): The crop of the image used to generate + the mask, given in XYWH format. + """ + + # Generate masks + mask_data = self._generate_masks(image) + + # Filter small disconnected regions and holes in masks + if self.min_mask_region_area > 0: + mask_data = self.postprocess_small_regions( + mask_data, + self.min_mask_region_area, + max(self.box_nms_thresh, self.crop_nms_thresh), + ) + + # Encode masks + if self.output_mode == "coco_rle": + mask_data["segmentations"] = [coco_encode_rle(rle) for rle in mask_data["rles"]] + elif self.output_mode == "binary_mask": + mask_data["segmentations"] = [rle_to_mask(rle) for rle in mask_data["rles"]] + else: + mask_data["segmentations"] = mask_data["rles"] + + # Write mask records + curr_anns = [] + for idx in range(len(mask_data["segmentations"])): + ann = { + "segmentation": mask_data["segmentations"][idx], + "area": area_from_rle(mask_data["rles"][idx]), + "bbox": box_xyxy_to_xywh(mask_data["boxes"][idx]).tolist(), + "predicted_iou": mask_data["iou_preds"][idx].item(), + "point_coords": [mask_data["points"][idx].tolist()], + "stability_score": mask_data["stability_score"][idx].item(), + "crop_box": box_xyxy_to_xywh(mask_data["crop_boxes"][idx]).tolist(), + } + curr_anns.append(ann) + + return curr_anns + + def _generate_masks(self, image: np.ndarray) -> MaskData: + orig_size = image.shape[:2] + crop_boxes, layer_idxs = generate_crop_boxes( + orig_size, self.crop_n_layers, self.crop_overlap_ratio + ) + + # Iterate over image crops + data = MaskData() + for crop_box, layer_idx in zip(crop_boxes, layer_idxs): + crop_data = self._process_crop(image, crop_box, layer_idx, orig_size) + data.cat(crop_data) + + # Remove duplicate masks between crops + if len(crop_boxes) > 1: + # Prefer masks from smaller crops + scores = 1 / box_area(data["crop_boxes"]) + scores = scores.to(data["boxes"].device) + keep_by_nms = batched_nms( + data["boxes"].float(), + scores, + torch.zeros_like(data["boxes"][:, 0]), # categories + iou_threshold=self.crop_nms_thresh, + ) + data.filter(keep_by_nms) + + data.to_numpy() + return data + + def _process_crop( + self, + image: np.ndarray, + crop_box: List[int], + crop_layer_idx: int, + orig_size: Tuple[int, ...], + ) -> MaskData: + # Crop the image and calculate embeddings + x0, y0, x1, y1 = crop_box + cropped_im = image[y0:y1, x0:x1, :] + cropped_im_size = cropped_im.shape[:2] + self.predictor.set_image(cropped_im) + + # Get points for this crop + points_scale = np.array(cropped_im_size)[None, ::-1] + points_for_image = self.point_grids[crop_layer_idx] * points_scale + + # Generate masks for this crop in batches + data = MaskData() + for (points,) in batch_iterator(self.points_per_batch, points_for_image): + batch_data = self._process_batch(points, cropped_im_size, crop_box, orig_size) + data.cat(batch_data) + del batch_data + self.predictor.reset_image() + + # Remove duplicates within this crop. + keep_by_nms = batched_nms( + data["boxes"].float(), + data["iou_preds"], + torch.zeros_like(data["boxes"][:, 0]), # categories + iou_threshold=self.box_nms_thresh, + ) + data.filter(keep_by_nms) + + # Return to the original image frame + data["boxes"] = uncrop_boxes_xyxy(data["boxes"], crop_box) + data["points"] = uncrop_points(data["points"], crop_box) + data["crop_boxes"] = torch.tensor([crop_box for _ in range(len(data["rles"]))]) + + return data + + def _process_batch( + self, + points: np.ndarray, + im_size: Tuple[int, ...], + crop_box: List[int], + orig_size: Tuple[int, ...], + ) -> MaskData: + orig_h, orig_w = orig_size + + # Run model on this batch + transformed_points = self.predictor.transform.apply_coords(points, im_size) + in_points = torch.as_tensor(transformed_points, device=self.predictor.device) + in_labels = torch.ones(in_points.shape[0], dtype=torch.int, device=in_points.device) + masks, iou_preds, _ = self.predictor.predict_torch( + in_points[:, None, :], + in_labels[:, None], + multimask_output=True, + return_logits=True, + ) + + # Serialize predictions and store in MaskData + data = MaskData( + masks=masks.flatten(0, 1), + iou_preds=iou_preds.flatten(0, 1), + points=torch.as_tensor(points.repeat(masks.shape[1], axis=0)), + ) + del masks + + # Filter by predicted IoU + if self.pred_iou_thresh > 0.0: + keep_mask = data["iou_preds"] > self.pred_iou_thresh + data.filter(keep_mask) + + # Calculate stability score + data["stability_score"] = calculate_stability_score( + data["masks"], self.predictor.model.mask_threshold, self.stability_score_offset + ) + if self.stability_score_thresh > 0.0: + keep_mask = data["stability_score"] >= self.stability_score_thresh + data.filter(keep_mask) + + # Threshold masks and calculate boxes + data["masks"] = data["masks"] > self.predictor.model.mask_threshold + data["boxes"] = batched_mask_to_box(data["masks"]) + + # Filter boxes that touch crop boundaries + keep_mask = ~is_box_near_crop_edge(data["boxes"], crop_box, [0, 0, orig_w, orig_h]) + if not torch.all(keep_mask): + data.filter(keep_mask) + + # Compress to RLE + data["masks"] = uncrop_masks(data["masks"], crop_box, orig_h, orig_w) + data["rles"] = mask_to_rle_pytorch(data["masks"]) + del data["masks"] + + return data + + @staticmethod + def postprocess_small_regions( + mask_data: MaskData, min_area: int, nms_thresh: float + ) -> MaskData: + """ + Removes small disconnected regions and holes in masks, then reruns + box NMS to remove any new duplicates. + + Edits mask_data in place. + + Requires open-cv as a dependency. + """ + if len(mask_data["rles"]) == 0: + return mask_data + + # Filter small disconnected regions and holes + new_masks = [] + scores = [] + for rle in mask_data["rles"]: + mask = rle_to_mask(rle) + + mask, changed = remove_small_regions(mask, min_area, mode="holes") + unchanged = not changed + mask, changed = remove_small_regions(mask, min_area, mode="islands") + unchanged = unchanged and not changed + + new_masks.append(torch.as_tensor(mask).unsqueeze(0)) + # Give score=0 to changed masks and score=1 to unchanged masks + # so NMS will prefer ones that didn't need postprocessing + scores.append(float(unchanged)) + + # Recalculate boxes and remove any new duplicates + masks = torch.cat(new_masks, dim=0) + boxes = batched_mask_to_box(masks) + keep_by_nms = batched_nms( + boxes.float(), + torch.as_tensor(scores), + torch.zeros_like(boxes[:, 0]), # categories + iou_threshold=nms_thresh, + ) + + # Only recalculate RLEs for masks that have changed + for i_mask in keep_by_nms: + if scores[i_mask] == 0.0: + mask_torch = masks[i_mask].unsqueeze(0) + mask_data["rles"][i_mask] = mask_to_rle_pytorch(mask_torch)[0] + mask_data["boxes"][i_mask] = boxes[i_mask] # update res directly + mask_data.filter(keep_by_nms) + + return mask_data diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/segment_anything/build_sam.py b/downstream/ProxyCLIP_TPAMI/clipself/src/segment_anything/build_sam.py new file mode 100644 index 0000000000000000000000000000000000000000..37cd245124079e7cdd0d047ef9dde077db99efcc --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/segment_anything/build_sam.py @@ -0,0 +1,107 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import torch + +from functools import partial + +from .modeling import ImageEncoderViT, MaskDecoder, PromptEncoder, Sam, TwoWayTransformer + + +def build_sam_vit_h(checkpoint=None): + return _build_sam( + encoder_embed_dim=1280, + encoder_depth=32, + encoder_num_heads=16, + encoder_global_attn_indexes=[7, 15, 23, 31], + checkpoint=checkpoint, + ) + + +build_sam = build_sam_vit_h + + +def build_sam_vit_l(checkpoint=None): + return _build_sam( + encoder_embed_dim=1024, + encoder_depth=24, + encoder_num_heads=16, + encoder_global_attn_indexes=[5, 11, 17, 23], + checkpoint=checkpoint, + ) + + +def build_sam_vit_b(checkpoint=None): + return _build_sam( + encoder_embed_dim=768, + encoder_depth=12, + encoder_num_heads=12, + encoder_global_attn_indexes=[2, 5, 8, 11], + checkpoint=checkpoint, + ) + + +sam_model_registry = { + "default": build_sam_vit_h, + "vit_h": build_sam_vit_h, + "vit_l": build_sam_vit_l, + "vit_b": build_sam_vit_b, +} + + +def _build_sam( + encoder_embed_dim, + encoder_depth, + encoder_num_heads, + encoder_global_attn_indexes, + checkpoint=None, +): + prompt_embed_dim = 256 + image_size = 1024 + vit_patch_size = 16 + image_embedding_size = image_size // vit_patch_size + sam = Sam( + image_encoder=ImageEncoderViT( + depth=encoder_depth, + embed_dim=encoder_embed_dim, + img_size=image_size, + mlp_ratio=4, + norm_layer=partial(torch.nn.LayerNorm, eps=1e-6), + num_heads=encoder_num_heads, + patch_size=vit_patch_size, + qkv_bias=True, + use_rel_pos=True, + global_attn_indexes=encoder_global_attn_indexes, + window_size=14, + out_chans=prompt_embed_dim, + ), + prompt_encoder=PromptEncoder( + embed_dim=prompt_embed_dim, + image_embedding_size=(image_embedding_size, image_embedding_size), + input_image_size=(image_size, image_size), + mask_in_chans=16, + ), + mask_decoder=MaskDecoder( + num_multimask_outputs=3, + transformer=TwoWayTransformer( + depth=2, + embedding_dim=prompt_embed_dim, + mlp_dim=2048, + num_heads=8, + ), + transformer_dim=prompt_embed_dim, + iou_head_depth=3, + iou_head_hidden_dim=256, + ), + pixel_mean=[123.675, 116.28, 103.53], + pixel_std=[58.395, 57.12, 57.375], + ) + sam.eval() + if checkpoint is not None: + with open(checkpoint, "rb") as f: + state_dict = torch.load(f) + sam.load_state_dict(state_dict) + return sam diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/segment_anything/modeling/__init__.py b/downstream/ProxyCLIP_TPAMI/clipself/src/segment_anything/modeling/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..38e906243d898d7fc071c0fe218338c5cace3ea1 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/segment_anything/modeling/__init__.py @@ -0,0 +1,11 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +from .sam import Sam +from .image_encoder import ImageEncoderViT +from .mask_decoder import MaskDecoder +from .prompt_encoder import PromptEncoder +from .transformer import TwoWayTransformer diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/segment_anything/modeling/common.py b/downstream/ProxyCLIP_TPAMI/clipself/src/segment_anything/modeling/common.py new file mode 100644 index 0000000000000000000000000000000000000000..2bf15236a3eb24d8526073bc4fa2b274cccb3f96 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/segment_anything/modeling/common.py @@ -0,0 +1,43 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import torch +import torch.nn as nn + +from typing import Type + + +class MLPBlock(nn.Module): + def __init__( + self, + embedding_dim: int, + mlp_dim: int, + act: Type[nn.Module] = nn.GELU, + ) -> None: + super().__init__() + self.lin1 = nn.Linear(embedding_dim, mlp_dim) + self.lin2 = nn.Linear(mlp_dim, embedding_dim) + self.act = act() + + def forward(self, x: torch.Tensor) -> torch.Tensor: + return self.lin2(self.act(self.lin1(x))) + + +# From https://github.com/facebookresearch/detectron2/blob/main/detectron2/layers/batch_norm.py # noqa +# Itself from https://github.com/facebookresearch/ConvNeXt/blob/d1fa8f6fef0a165b27399986cc2bdacc92777e40/models/convnext.py#L119 # noqa +class LayerNorm2d(nn.Module): + def __init__(self, num_channels: int, eps: float = 1e-6) -> None: + super().__init__() + self.weight = nn.Parameter(torch.ones(num_channels)) + self.bias = nn.Parameter(torch.zeros(num_channels)) + self.eps = eps + + def forward(self, x: torch.Tensor) -> torch.Tensor: + u = x.mean(1, keepdim=True) + s = (x - u).pow(2).mean(1, keepdim=True) + x = (x - u) / torch.sqrt(s + self.eps) + x = self.weight[:, None, None] * x + self.bias[:, None, None] + return x diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/segment_anything/modeling/image_encoder.py b/downstream/ProxyCLIP_TPAMI/clipself/src/segment_anything/modeling/image_encoder.py new file mode 100644 index 0000000000000000000000000000000000000000..7030c033aa3147e9a30fb9a137cc7829e786993c --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/segment_anything/modeling/image_encoder.py @@ -0,0 +1,395 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import torch +import torch.nn as nn +import torch.nn.functional as F + +from typing import Optional, Tuple, Type + +from .common import LayerNorm2d, MLPBlock + + +# This class and its supporting functions below lightly adapted from the ViTDet backbone available at: https://github.com/facebookresearch/detectron2/blob/main/detectron2/modeling/backbone/vit.py # noqa +class ImageEncoderViT(nn.Module): + def __init__( + self, + img_size: int = 1024, + patch_size: int = 16, + in_chans: int = 3, + embed_dim: int = 768, + depth: int = 12, + num_heads: int = 12, + mlp_ratio: float = 4.0, + out_chans: int = 256, + qkv_bias: bool = True, + norm_layer: Type[nn.Module] = nn.LayerNorm, + act_layer: Type[nn.Module] = nn.GELU, + use_abs_pos: bool = True, + use_rel_pos: bool = False, + rel_pos_zero_init: bool = True, + window_size: int = 0, + global_attn_indexes: Tuple[int, ...] = (), + ) -> None: + """ + Args: + img_size (int): Input image size. + patch_size (int): Patch size. + in_chans (int): Number of input image channels. + embed_dim (int): Patch embedding dimension. + depth (int): Depth of ViT. + num_heads (int): Number of attention heads in each ViT block. + mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. + qkv_bias (bool): If True, add a learnable bias to query, key, value. + norm_layer (nn.Module): Normalization layer. + act_layer (nn.Module): Activation layer. + use_abs_pos (bool): If True, use absolute positional embeddings. + use_rel_pos (bool): If True, add relative positional embeddings to the attention map. + rel_pos_zero_init (bool): If True, zero initialize relative positional parameters. + window_size (int): Window size for window attention blocks. + global_attn_indexes (list): Indexes for blocks using global attention. + """ + super().__init__() + self.img_size = img_size + + self.patch_embed = PatchEmbed( + kernel_size=(patch_size, patch_size), + stride=(patch_size, patch_size), + in_chans=in_chans, + embed_dim=embed_dim, + ) + + self.pos_embed: Optional[nn.Parameter] = None + if use_abs_pos: + # Initialize absolute positional embedding with pretrain image size. + self.pos_embed = nn.Parameter( + torch.zeros(1, img_size // patch_size, img_size // patch_size, embed_dim) + ) + + self.blocks = nn.ModuleList() + for i in range(depth): + block = Block( + dim=embed_dim, + num_heads=num_heads, + mlp_ratio=mlp_ratio, + qkv_bias=qkv_bias, + norm_layer=norm_layer, + act_layer=act_layer, + use_rel_pos=use_rel_pos, + rel_pos_zero_init=rel_pos_zero_init, + window_size=window_size if i not in global_attn_indexes else 0, + input_size=(img_size // patch_size, img_size // patch_size), + ) + self.blocks.append(block) + + self.neck = nn.Sequential( + nn.Conv2d( + embed_dim, + out_chans, + kernel_size=1, + bias=False, + ), + LayerNorm2d(out_chans), + nn.Conv2d( + out_chans, + out_chans, + kernel_size=3, + padding=1, + bias=False, + ), + LayerNorm2d(out_chans), + ) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + x = self.patch_embed(x) + if self.pos_embed is not None: + x = x + self.pos_embed + + for blk in self.blocks: + x = blk(x) + + x = self.neck(x.permute(0, 3, 1, 2)) + + return x + + +class Block(nn.Module): + """Transformer blocks with support of window attention and residual propagation blocks""" + + def __init__( + self, + dim: int, + num_heads: int, + mlp_ratio: float = 4.0, + qkv_bias: bool = True, + norm_layer: Type[nn.Module] = nn.LayerNorm, + act_layer: Type[nn.Module] = nn.GELU, + use_rel_pos: bool = False, + rel_pos_zero_init: bool = True, + window_size: int = 0, + input_size: Optional[Tuple[int, int]] = None, + ) -> None: + """ + Args: + dim (int): Number of input channels. + num_heads (int): Number of attention heads in each ViT block. + mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. + qkv_bias (bool): If True, add a learnable bias to query, key, value. + norm_layer (nn.Module): Normalization layer. + act_layer (nn.Module): Activation layer. + use_rel_pos (bool): If True, add relative positional embeddings to the attention map. + rel_pos_zero_init (bool): If True, zero initialize relative positional parameters. + window_size (int): Window size for window attention blocks. If it equals 0, then + use global attention. + input_size (tuple(int, int) or None): Input resolution for calculating the relative + positional parameter size. + """ + super().__init__() + self.norm1 = norm_layer(dim) + self.attn = Attention( + dim, + num_heads=num_heads, + qkv_bias=qkv_bias, + use_rel_pos=use_rel_pos, + rel_pos_zero_init=rel_pos_zero_init, + input_size=input_size if window_size == 0 else (window_size, window_size), + ) + + self.norm2 = norm_layer(dim) + self.mlp = MLPBlock(embedding_dim=dim, mlp_dim=int(dim * mlp_ratio), act=act_layer) + + self.window_size = window_size + + def forward(self, x: torch.Tensor) -> torch.Tensor: + shortcut = x + x = self.norm1(x) + # Window partition + if self.window_size > 0: + H, W = x.shape[1], x.shape[2] + x, pad_hw = window_partition(x, self.window_size) + + x = self.attn(x) + # Reverse window partition + if self.window_size > 0: + x = window_unpartition(x, self.window_size, pad_hw, (H, W)) + + x = shortcut + x + x = x + self.mlp(self.norm2(x)) + + return x + + +class Attention(nn.Module): + """Multi-head Attention block with relative position embeddings.""" + + def __init__( + self, + dim: int, + num_heads: int = 8, + qkv_bias: bool = True, + use_rel_pos: bool = False, + rel_pos_zero_init: bool = True, + input_size: Optional[Tuple[int, int]] = None, + ) -> None: + """ + Args: + dim (int): Number of input channels. + num_heads (int): Number of attention heads. + qkv_bias (bool): If True, add a learnable bias to query, key, value. + rel_pos (bool): If True, add relative positional embeddings to the attention map. + rel_pos_zero_init (bool): If True, zero initialize relative positional parameters. + input_size (tuple(int, int) or None): Input resolution for calculating the relative + positional parameter size. + """ + super().__init__() + self.num_heads = num_heads + head_dim = dim // num_heads + self.scale = head_dim**-0.5 + + self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) + self.proj = nn.Linear(dim, dim) + + self.use_rel_pos = use_rel_pos + if self.use_rel_pos: + assert ( + input_size is not None + ), "Input size must be provided if using relative positional encoding." + # initialize relative positional embeddings + self.rel_pos_h = nn.Parameter(torch.zeros(2 * input_size[0] - 1, head_dim)) + self.rel_pos_w = nn.Parameter(torch.zeros(2 * input_size[1] - 1, head_dim)) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + B, H, W, _ = x.shape + # qkv with shape (3, B, nHead, H * W, C) + qkv = self.qkv(x).reshape(B, H * W, 3, self.num_heads, -1).permute(2, 0, 3, 1, 4) + # q, k, v with shape (B * nHead, H * W, C) + q, k, v = qkv.reshape(3, B * self.num_heads, H * W, -1).unbind(0) + + attn = (q * self.scale) @ k.transpose(-2, -1) + + if self.use_rel_pos: + attn = add_decomposed_rel_pos(attn, q, self.rel_pos_h, self.rel_pos_w, (H, W), (H, W)) + + attn = attn.softmax(dim=-1) + x = (attn @ v).view(B, self.num_heads, H, W, -1).permute(0, 2, 3, 1, 4).reshape(B, H, W, -1) + x = self.proj(x) + + return x + + +def window_partition(x: torch.Tensor, window_size: int) -> Tuple[torch.Tensor, Tuple[int, int]]: + """ + Partition into non-overlapping windows with padding if needed. + Args: + x (tensor): input tokens with [B, H, W, C]. + window_size (int): window size. + + Returns: + windows: windows after partition with [B * num_windows, window_size, window_size, C]. + (Hp, Wp): padded height and width before partition + """ + B, H, W, C = x.shape + + pad_h = (window_size - H % window_size) % window_size + pad_w = (window_size - W % window_size) % window_size + if pad_h > 0 or pad_w > 0: + x = F.pad(x, (0, 0, 0, pad_w, 0, pad_h)) + Hp, Wp = H + pad_h, W + pad_w + + x = x.view(B, Hp // window_size, window_size, Wp // window_size, window_size, C) + windows = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C) + return windows, (Hp, Wp) + + +def window_unpartition( + windows: torch.Tensor, window_size: int, pad_hw: Tuple[int, int], hw: Tuple[int, int] +) -> torch.Tensor: + """ + Window unpartition into original sequences and removing padding. + Args: + windows (tensor): input tokens with [B * num_windows, window_size, window_size, C]. + window_size (int): window size. + pad_hw (Tuple): padded height and width (Hp, Wp). + hw (Tuple): original height and width (H, W) before padding. + + Returns: + x: unpartitioned sequences with [B, H, W, C]. + """ + Hp, Wp = pad_hw + H, W = hw + B = windows.shape[0] // (Hp * Wp // window_size // window_size) + x = windows.view(B, Hp // window_size, Wp // window_size, window_size, window_size, -1) + x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, Hp, Wp, -1) + + if Hp > H or Wp > W: + x = x[:, :H, :W, :].contiguous() + return x + + +def get_rel_pos(q_size: int, k_size: int, rel_pos: torch.Tensor) -> torch.Tensor: + """ + Get relative positional embeddings according to the relative positions of + query and key sizes. + Args: + q_size (int): size of query q. + k_size (int): size of key k. + rel_pos (Tensor): relative position embeddings (L, C). + + Returns: + Extracted positional embeddings according to relative positions. + """ + max_rel_dist = int(2 * max(q_size, k_size) - 1) + # Interpolate rel pos if needed. + if rel_pos.shape[0] != max_rel_dist: + # Interpolate rel pos. + rel_pos_resized = F.interpolate( + rel_pos.reshape(1, rel_pos.shape[0], -1).permute(0, 2, 1), + size=max_rel_dist, + mode="linear", + ) + rel_pos_resized = rel_pos_resized.reshape(-1, max_rel_dist).permute(1, 0) + else: + rel_pos_resized = rel_pos + + # Scale the coords with short length if shapes for q and k are different. + q_coords = torch.arange(q_size)[:, None] * max(k_size / q_size, 1.0) + k_coords = torch.arange(k_size)[None, :] * max(q_size / k_size, 1.0) + relative_coords = (q_coords - k_coords) + (k_size - 1) * max(q_size / k_size, 1.0) + + return rel_pos_resized[relative_coords.long()] + + +def add_decomposed_rel_pos( + attn: torch.Tensor, + q: torch.Tensor, + rel_pos_h: torch.Tensor, + rel_pos_w: torch.Tensor, + q_size: Tuple[int, int], + k_size: Tuple[int, int], +) -> torch.Tensor: + """ + Calculate decomposed Relative Positional Embeddings from :paper:`mvitv2`. + https://github.com/facebookresearch/mvit/blob/19786631e330df9f3622e5402b4a419a263a2c80/mvit/models/attention.py # noqa B950 + Args: + attn (Tensor): attention map. + q (Tensor): query q in the attention layer with shape (B, q_h * q_w, C). + rel_pos_h (Tensor): relative position embeddings (Lh, C) for height axis. + rel_pos_w (Tensor): relative position embeddings (Lw, C) for width axis. + q_size (Tuple): spatial sequence size of query q with (q_h, q_w). + k_size (Tuple): spatial sequence size of key k with (k_h, k_w). + + Returns: + attn (Tensor): attention map with added relative positional embeddings. + """ + q_h, q_w = q_size + k_h, k_w = k_size + Rh = get_rel_pos(q_h, k_h, rel_pos_h) + Rw = get_rel_pos(q_w, k_w, rel_pos_w) + + B, _, dim = q.shape + r_q = q.reshape(B, q_h, q_w, dim) + rel_h = torch.einsum("bhwc,hkc->bhwk", r_q, Rh) + rel_w = torch.einsum("bhwc,wkc->bhwk", r_q, Rw) + + attn = ( + attn.view(B, q_h, q_w, k_h, k_w) + rel_h[:, :, :, :, None] + rel_w[:, :, :, None, :] + ).view(B, q_h * q_w, k_h * k_w) + + return attn + + +class PatchEmbed(nn.Module): + """ + Image to Patch Embedding. + """ + + def __init__( + self, + kernel_size: Tuple[int, int] = (16, 16), + stride: Tuple[int, int] = (16, 16), + padding: Tuple[int, int] = (0, 0), + in_chans: int = 3, + embed_dim: int = 768, + ) -> None: + """ + Args: + kernel_size (Tuple): kernel size of the projection layer. + stride (Tuple): stride of the projection layer. + padding (Tuple): padding size of the projection layer. + in_chans (int): Number of input image channels. + embed_dim (int): Patch embedding dimension. + """ + super().__init__() + + self.proj = nn.Conv2d( + in_chans, embed_dim, kernel_size=kernel_size, stride=stride, padding=padding + ) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + x = self.proj(x) + # B C H W -> B H W C + x = x.permute(0, 2, 3, 1) + return x \ No newline at end of file diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/segment_anything/modeling/mask_decoder.py b/downstream/ProxyCLIP_TPAMI/clipself/src/segment_anything/modeling/mask_decoder.py new file mode 100644 index 0000000000000000000000000000000000000000..5d2fdb03d535a91fa725d1ec4e92a7a1f217dfe0 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/segment_anything/modeling/mask_decoder.py @@ -0,0 +1,176 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import torch +from torch import nn +from torch.nn import functional as F + +from typing import List, Tuple, Type + +from .common import LayerNorm2d + + +class MaskDecoder(nn.Module): + def __init__( + self, + *, + transformer_dim: int, + transformer: nn.Module, + num_multimask_outputs: int = 3, + activation: Type[nn.Module] = nn.GELU, + iou_head_depth: int = 3, + iou_head_hidden_dim: int = 256, + ) -> None: + """ + Predicts masks given an image and prompt embeddings, using a + transformer architecture. + + Arguments: + transformer_dim (int): the channel dimension of the transformer + transformer (nn.Module): the transformer used to predict masks + num_multimask_outputs (int): the number of masks to predict + when disambiguating masks + activation (nn.Module): the type of activation to use when + upscaling masks + iou_head_depth (int): the depth of the MLP used to predict + mask quality + iou_head_hidden_dim (int): the hidden dimension of the MLP + used to predict mask quality + """ + super().__init__() + self.transformer_dim = transformer_dim + self.transformer = transformer + + self.num_multimask_outputs = num_multimask_outputs + + self.iou_token = nn.Embedding(1, transformer_dim) + self.num_mask_tokens = num_multimask_outputs + 1 + self.mask_tokens = nn.Embedding(self.num_mask_tokens, transformer_dim) + + self.output_upscaling = nn.Sequential( + nn.ConvTranspose2d(transformer_dim, transformer_dim // 4, kernel_size=2, stride=2), + LayerNorm2d(transformer_dim // 4), + activation(), + nn.ConvTranspose2d(transformer_dim // 4, transformer_dim // 8, kernel_size=2, stride=2), + activation(), + ) + self.output_hypernetworks_mlps = nn.ModuleList( + [ + MLP(transformer_dim, transformer_dim, transformer_dim // 8, 3) + for i in range(self.num_mask_tokens) + ] + ) + + self.iou_prediction_head = MLP( + transformer_dim, iou_head_hidden_dim, self.num_mask_tokens, iou_head_depth + ) + + def forward( + self, + image_embeddings: torch.Tensor, + image_pe: torch.Tensor, + sparse_prompt_embeddings: torch.Tensor, + dense_prompt_embeddings: torch.Tensor, + multimask_output: bool, + ) -> Tuple[torch.Tensor, torch.Tensor]: + """ + Predict masks given image and prompt embeddings. + + Arguments: + image_embeddings (torch.Tensor): the embeddings from the image encoder + image_pe (torch.Tensor): positional encoding with the shape of image_embeddings + sparse_prompt_embeddings (torch.Tensor): the embeddings of the points and boxes + dense_prompt_embeddings (torch.Tensor): the embeddings of the mask inputs + multimask_output (bool): Whether to return multiple masks or a single + mask. + + Returns: + torch.Tensor: batched predicted masks + torch.Tensor: batched predictions of mask quality + """ + masks, iou_pred = self.predict_masks( + image_embeddings=image_embeddings, + image_pe=image_pe, + sparse_prompt_embeddings=sparse_prompt_embeddings, + dense_prompt_embeddings=dense_prompt_embeddings, + ) + + # Select the correct mask or masks for output + if multimask_output: + mask_slice = slice(1, None) + else: + mask_slice = slice(0, 1) + masks = masks[:, mask_slice, :, :] + iou_pred = iou_pred[:, mask_slice] + + # Prepare output + return masks, iou_pred + + def predict_masks( + self, + image_embeddings: torch.Tensor, + image_pe: torch.Tensor, + sparse_prompt_embeddings: torch.Tensor, + dense_prompt_embeddings: torch.Tensor, + ) -> Tuple[torch.Tensor, torch.Tensor]: + """Predicts masks. See 'forward' for more details.""" + # Concatenate output tokens + output_tokens = torch.cat([self.iou_token.weight, self.mask_tokens.weight], dim=0) + output_tokens = output_tokens.unsqueeze(0).expand(sparse_prompt_embeddings.size(0), -1, -1) + tokens = torch.cat((output_tokens, sparse_prompt_embeddings), dim=1) + + # Expand per-image data in batch direction to be per-mask + src = torch.repeat_interleave(image_embeddings, tokens.shape[0], dim=0) + src = src + dense_prompt_embeddings + pos_src = torch.repeat_interleave(image_pe, tokens.shape[0], dim=0) + b, c, h, w = src.shape + + # Run the transformer + hs, src = self.transformer(src, pos_src, tokens) + iou_token_out = hs[:, 0, :] + mask_tokens_out = hs[:, 1 : (1 + self.num_mask_tokens), :] + + # Upscale mask embeddings and predict masks using the mask tokens + src = src.transpose(1, 2).view(b, c, h, w) + upscaled_embedding = self.output_upscaling(src) + hyper_in_list: List[torch.Tensor] = [] + for i in range(self.num_mask_tokens): + hyper_in_list.append(self.output_hypernetworks_mlps[i](mask_tokens_out[:, i, :])) + hyper_in = torch.stack(hyper_in_list, dim=1) + b, c, h, w = upscaled_embedding.shape + masks = (hyper_in @ upscaled_embedding.view(b, c, h * w)).view(b, -1, h, w) + + # Generate mask quality predictions + iou_pred = self.iou_prediction_head(iou_token_out) + + return masks, iou_pred + + +# Lightly adapted from +# https://github.com/facebookresearch/MaskFormer/blob/main/mask_former/modeling/transformer/transformer_predictor.py # noqa +class MLP(nn.Module): + def __init__( + self, + input_dim: int, + hidden_dim: int, + output_dim: int, + num_layers: int, + sigmoid_output: bool = False, + ) -> None: + super().__init__() + self.num_layers = num_layers + h = [hidden_dim] * (num_layers - 1) + self.layers = nn.ModuleList( + nn.Linear(n, k) for n, k in zip([input_dim] + h, h + [output_dim]) + ) + self.sigmoid_output = sigmoid_output + + def forward(self, x): + for i, layer in enumerate(self.layers): + x = F.relu(layer(x)) if i < self.num_layers - 1 else layer(x) + if self.sigmoid_output: + x = F.sigmoid(x) + return x diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/segment_anything/modeling/prompt_encoder.py b/downstream/ProxyCLIP_TPAMI/clipself/src/segment_anything/modeling/prompt_encoder.py new file mode 100644 index 0000000000000000000000000000000000000000..c3143f4f8e02ddd7ca8587b40ff5d47c3a6b7ef3 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/segment_anything/modeling/prompt_encoder.py @@ -0,0 +1,214 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import numpy as np +import torch +from torch import nn + +from typing import Any, Optional, Tuple, Type + +from .common import LayerNorm2d + + +class PromptEncoder(nn.Module): + def __init__( + self, + embed_dim: int, + image_embedding_size: Tuple[int, int], + input_image_size: Tuple[int, int], + mask_in_chans: int, + activation: Type[nn.Module] = nn.GELU, + ) -> None: + """ + Encodes prompts for input to SAM's mask decoder. + + Arguments: + embed_dim (int): The prompts' embedding dimension + image_embedding_size (tuple(int, int)): The spatial size of the + image embedding, as (H, W). + input_image_size (int): The padded size of the image as input + to the image encoder, as (H, W). + mask_in_chans (int): The number of hidden channels used for + encoding input masks. + activation (nn.Module): The activation to use when encoding + input masks. + """ + super().__init__() + self.embed_dim = embed_dim + self.input_image_size = input_image_size + self.image_embedding_size = image_embedding_size + self.pe_layer = PositionEmbeddingRandom(embed_dim // 2) + + self.num_point_embeddings: int = 4 # pos/neg point + 2 box corners + point_embeddings = [nn.Embedding(1, embed_dim) for i in range(self.num_point_embeddings)] + self.point_embeddings = nn.ModuleList(point_embeddings) + self.not_a_point_embed = nn.Embedding(1, embed_dim) + + self.mask_input_size = (4 * image_embedding_size[0], 4 * image_embedding_size[1]) + self.mask_downscaling = nn.Sequential( + nn.Conv2d(1, mask_in_chans // 4, kernel_size=2, stride=2), + LayerNorm2d(mask_in_chans // 4), + activation(), + nn.Conv2d(mask_in_chans // 4, mask_in_chans, kernel_size=2, stride=2), + LayerNorm2d(mask_in_chans), + activation(), + nn.Conv2d(mask_in_chans, embed_dim, kernel_size=1), + ) + self.no_mask_embed = nn.Embedding(1, embed_dim) + + def get_dense_pe(self) -> torch.Tensor: + """ + Returns the positional encoding used to encode point prompts, + applied to a dense set of points the shape of the image encoding. + + Returns: + torch.Tensor: Positional encoding with shape + 1x(embed_dim)x(embedding_h)x(embedding_w) + """ + return self.pe_layer(self.image_embedding_size).unsqueeze(0) + + def _embed_points( + self, + points: torch.Tensor, + labels: torch.Tensor, + pad: bool, + ) -> torch.Tensor: + """Embeds point prompts.""" + points = points + 0.5 # Shift to center of pixel + if pad: + padding_point = torch.zeros((points.shape[0], 1, 2), device=points.device) + padding_label = -torch.ones((labels.shape[0], 1), device=labels.device) + points = torch.cat([points, padding_point], dim=1) + labels = torch.cat([labels, padding_label], dim=1) + point_embedding = self.pe_layer.forward_with_coords(points, self.input_image_size) + point_embedding[labels == -1] = 0.0 + point_embedding[labels == -1] += self.not_a_point_embed.weight + point_embedding[labels == 0] += self.point_embeddings[0].weight + point_embedding[labels == 1] += self.point_embeddings[1].weight + return point_embedding + + def _embed_boxes(self, boxes: torch.Tensor) -> torch.Tensor: + """Embeds box prompts.""" + boxes = boxes + 0.5 # Shift to center of pixel + coords = boxes.reshape(-1, 2, 2) + corner_embedding = self.pe_layer.forward_with_coords(coords, self.input_image_size) + corner_embedding[:, 0, :] += self.point_embeddings[2].weight + corner_embedding[:, 1, :] += self.point_embeddings[3].weight + return corner_embedding + + def _embed_masks(self, masks: torch.Tensor) -> torch.Tensor: + """Embeds mask inputs.""" + mask_embedding = self.mask_downscaling(masks) + return mask_embedding + + def _get_batch_size( + self, + points: Optional[Tuple[torch.Tensor, torch.Tensor]], + boxes: Optional[torch.Tensor], + masks: Optional[torch.Tensor], + ) -> int: + """ + Gets the batch size of the output given the batch size of the input prompts. + """ + if points is not None: + return points[0].shape[0] + elif boxes is not None: + return boxes.shape[0] + elif masks is not None: + return masks.shape[0] + else: + return 1 + + def _get_device(self) -> torch.device: + return self.point_embeddings[0].weight.device + + def forward( + self, + points: Optional[Tuple[torch.Tensor, torch.Tensor]], + boxes: Optional[torch.Tensor], + masks: Optional[torch.Tensor], + ) -> Tuple[torch.Tensor, torch.Tensor]: + """ + Embeds different types of prompts, returning both sparse and dense + embeddings. + + Arguments: + points (tuple(torch.Tensor, torch.Tensor) or none): point coordinates + and labels to embed. + boxes (torch.Tensor or none): boxes to embed + masks (torch.Tensor or none): masks to embed + + Returns: + torch.Tensor: sparse embeddings for the points and boxes, with shape + BxNx(embed_dim), where N is determined by the number of input points + and boxes. + torch.Tensor: dense embeddings for the masks, in the shape + Bx(embed_dim)x(embed_H)x(embed_W) + """ + bs = self._get_batch_size(points, boxes, masks) + sparse_embeddings = torch.empty((bs, 0, self.embed_dim), device=self._get_device()) + if points is not None: + coords, labels = points + point_embeddings = self._embed_points(coords, labels, pad=(boxes is None)) + sparse_embeddings = torch.cat([sparse_embeddings, point_embeddings], dim=1) + if boxes is not None: + box_embeddings = self._embed_boxes(boxes) + sparse_embeddings = torch.cat([sparse_embeddings, box_embeddings], dim=1) + + if masks is not None: + dense_embeddings = self._embed_masks(masks) + else: + dense_embeddings = self.no_mask_embed.weight.reshape(1, -1, 1, 1).expand( + bs, -1, self.image_embedding_size[0], self.image_embedding_size[1] + ) + + return sparse_embeddings, dense_embeddings + + +class PositionEmbeddingRandom(nn.Module): + """ + Positional encoding using random spatial frequencies. + """ + + def __init__(self, num_pos_feats: int = 64, scale: Optional[float] = None) -> None: + super().__init__() + if scale is None or scale <= 0.0: + scale = 1.0 + self.register_buffer( + "positional_encoding_gaussian_matrix", + scale * torch.randn((2, num_pos_feats)), + ) + + def _pe_encoding(self, coords: torch.Tensor) -> torch.Tensor: + """Positionally encode points that are normalized to [0,1].""" + # assuming coords are in [0, 1]^2 square and have d_1 x ... x d_n x 2 shape + coords = 2 * coords - 1 + coords = coords @ self.positional_encoding_gaussian_matrix + coords = 2 * np.pi * coords + # outputs d_1 x ... x d_n x C shape + return torch.cat([torch.sin(coords), torch.cos(coords)], dim=-1) + + def forward(self, size: Tuple[int, int]) -> torch.Tensor: + """Generate positional encoding for a grid of the specified size.""" + h, w = size + device: Any = self.positional_encoding_gaussian_matrix.device + grid = torch.ones((h, w), device=device, dtype=torch.float32) + y_embed = grid.cumsum(dim=0) - 0.5 + x_embed = grid.cumsum(dim=1) - 0.5 + y_embed = y_embed / h + x_embed = x_embed / w + + pe = self._pe_encoding(torch.stack([x_embed, y_embed], dim=-1)) + return pe.permute(2, 0, 1) # C x H x W + + def forward_with_coords( + self, coords_input: torch.Tensor, image_size: Tuple[int, int] + ) -> torch.Tensor: + """Positionally encode points that are not normalized to [0,1].""" + coords = coords_input.clone() + coords[:, :, 0] = coords[:, :, 0] / image_size[1] + coords[:, :, 1] = coords[:, :, 1] / image_size[0] + return self._pe_encoding(coords.to(torch.float)) # B x N x C diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/segment_anything/modeling/sam.py b/downstream/ProxyCLIP_TPAMI/clipself/src/segment_anything/modeling/sam.py new file mode 100644 index 0000000000000000000000000000000000000000..8074cff6b40addc6b66f7ab4962218eef20da13c --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/segment_anything/modeling/sam.py @@ -0,0 +1,174 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import torch +from torch import nn +from torch.nn import functional as F + +from typing import Any, Dict, List, Tuple + +from .image_encoder import ImageEncoderViT +from .mask_decoder import MaskDecoder +from .prompt_encoder import PromptEncoder + + +class Sam(nn.Module): + mask_threshold: float = 0.0 + image_format: str = "RGB" + + def __init__( + self, + image_encoder: ImageEncoderViT, + prompt_encoder: PromptEncoder, + mask_decoder: MaskDecoder, + pixel_mean: List[float] = [123.675, 116.28, 103.53], + pixel_std: List[float] = [58.395, 57.12, 57.375], + ) -> None: + """ + SAM predicts object masks from an image and input prompts. + + Arguments: + image_encoder (ImageEncoderViT): The backbone used to encode the + image into image embeddings that allow for efficient mask prediction. + prompt_encoder (PromptEncoder): Encodes various types of input prompts. + mask_decoder (MaskDecoder): Predicts masks from the image embeddings + and encoded prompts. + pixel_mean (list(float)): Mean values for normalizing pixels in the input image. + pixel_std (list(float)): Std values for normalizing pixels in the input image. + """ + super().__init__() + self.image_encoder = image_encoder + self.prompt_encoder = prompt_encoder + self.mask_decoder = mask_decoder + self.register_buffer("pixel_mean", torch.Tensor(pixel_mean).view(-1, 1, 1), False) + self.register_buffer("pixel_std", torch.Tensor(pixel_std).view(-1, 1, 1), False) + + @property + def device(self) -> Any: + return self.pixel_mean.device + + @torch.no_grad() + def forward( + self, + batched_input: List[Dict[str, Any]], + multimask_output: bool, + ) -> List[Dict[str, torch.Tensor]]: + """ + Predicts masks end-to-end from provided images and prompts. + If prompts are not known in advance, using SamPredictor is + recommended over calling the model directly. + + Arguments: + batched_input (list(dict)): A list over input images, each a + dictionary with the following keys. A prompt key can be + excluded if it is not present. + 'image': The image as a torch tensor in 3xHxW format, + already transformed for input to the model. + 'original_size': (tuple(int, int)) The original size of + the image before transformation, as (H, W). + 'point_coords': (torch.Tensor) Batched point prompts for + this image, with shape BxNx2. Already transformed to the + input frame of the model. + 'point_labels': (torch.Tensor) Batched labels for point prompts, + with shape BxN. + 'boxes': (torch.Tensor) Batched box inputs, with shape Bx4. + Already transformed to the input frame of the model. + 'mask_inputs': (torch.Tensor) Batched mask inputs to the model, + in the form Bx1xHxW. + multimask_output (bool): Whether the model should predict multiple + disambiguating masks, or return a single mask. + + Returns: + (list(dict)): A list over input images, where each element is + as dictionary with the following keys. + 'masks': (torch.Tensor) Batched binary mask predictions, + with shape BxCxHxW, where B is the number of input prompts, + C is determined by multimask_output, and (H, W) is the + original size of the image. + 'iou_predictions': (torch.Tensor) The model's predictions + of mask quality, in shape BxC. + 'low_res_logits': (torch.Tensor) Low resolution logits with + shape BxCxHxW, where H=W=256. Can be passed as mask input + to subsequent iterations of prediction. + """ + input_images = torch.stack([self.preprocess(x["image"]) for x in batched_input], dim=0) + image_embeddings = self.image_encoder(input_images) + + outputs = [] + for image_record, curr_embedding in zip(batched_input, image_embeddings): + if "point_coords" in image_record: + points = (image_record["point_coords"], image_record["point_labels"]) + else: + points = None + sparse_embeddings, dense_embeddings = self.prompt_encoder( + points=points, + boxes=image_record.get("boxes", None), + masks=image_record.get("mask_inputs", None), + ) + low_res_masks, iou_predictions = self.mask_decoder( + image_embeddings=curr_embedding.unsqueeze(0), + image_pe=self.prompt_encoder.get_dense_pe(), + sparse_prompt_embeddings=sparse_embeddings, + dense_prompt_embeddings=dense_embeddings, + multimask_output=multimask_output, + ) + masks = self.postprocess_masks( + low_res_masks, + input_size=image_record["image"].shape[-2:], + original_size=image_record["original_size"], + ) + masks = masks > self.mask_threshold + outputs.append( + { + "masks": masks, + "iou_predictions": iou_predictions, + "low_res_logits": low_res_masks, + } + ) + return outputs + + def postprocess_masks( + self, + masks: torch.Tensor, + input_size: Tuple[int, ...], + original_size: Tuple[int, ...], + ) -> torch.Tensor: + """ + Remove padding and upscale masks to the original image size. + + Arguments: + masks (torch.Tensor): Batched masks from the mask_decoder, + in BxCxHxW format. + input_size (tuple(int, int)): The size of the image input to the + model, in (H, W) format. Used to remove padding. + original_size (tuple(int, int)): The original size of the image + before resizing for input to the model, in (H, W) format. + + Returns: + (torch.Tensor): Batched masks in BxCxHxW format, where (H, W) + is given by original_size. + """ + masks = F.interpolate( + masks, + (self.image_encoder.img_size, self.image_encoder.img_size), + mode="bilinear", + align_corners=False, + ) + masks = masks[..., : input_size[0], : input_size[1]] + masks = F.interpolate(masks, original_size, mode="bilinear", align_corners=False) + return masks + + def preprocess(self, x: torch.Tensor) -> torch.Tensor: + """Normalize pixel values and pad to a square input.""" + # Normalize colors + x = (x - self.pixel_mean) / self.pixel_std + + # Pad + h, w = x.shape[-2:] + padh = self.image_encoder.img_size - h + padw = self.image_encoder.img_size - w + x = F.pad(x, (0, padw, 0, padh)) + return x diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/segment_anything/modeling/transformer.py b/downstream/ProxyCLIP_TPAMI/clipself/src/segment_anything/modeling/transformer.py new file mode 100644 index 0000000000000000000000000000000000000000..33b8070d3c18d11a43fcca3e1b3d7d33dc9a1147 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/segment_anything/modeling/transformer.py @@ -0,0 +1,240 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import torch +from torch import Tensor, nn + +import math +from typing import Tuple, Type + +from .common import MLPBlock + + +class TwoWayTransformer(nn.Module): + def __init__( + self, + depth: int, + embedding_dim: int, + num_heads: int, + mlp_dim: int, + activation: Type[nn.Module] = nn.ReLU, + attention_downsample_rate: int = 2, + ) -> None: + """ + A transformer decoder that attends to an input image using + queries whose positional embedding is supplied. + + Args: + depth (int): number of layers in the transformer + embedding_dim (int): the channel dimension for the input embeddings + num_heads (int): the number of heads for multihead attention. Must + divide embedding_dim + mlp_dim (int): the channel dimension internal to the MLP block + activation (nn.Module): the activation to use in the MLP block + """ + super().__init__() + self.depth = depth + self.embedding_dim = embedding_dim + self.num_heads = num_heads + self.mlp_dim = mlp_dim + self.layers = nn.ModuleList() + + for i in range(depth): + self.layers.append( + TwoWayAttentionBlock( + embedding_dim=embedding_dim, + num_heads=num_heads, + mlp_dim=mlp_dim, + activation=activation, + attention_downsample_rate=attention_downsample_rate, + skip_first_layer_pe=(i == 0), + ) + ) + + self.final_attn_token_to_image = Attention( + embedding_dim, num_heads, downsample_rate=attention_downsample_rate + ) + self.norm_final_attn = nn.LayerNorm(embedding_dim) + + def forward( + self, + image_embedding: Tensor, + image_pe: Tensor, + point_embedding: Tensor, + ) -> Tuple[Tensor, Tensor]: + """ + Args: + image_embedding (torch.Tensor): image to attend to. Should be shape + B x embedding_dim x h x w for any h and w. + image_pe (torch.Tensor): the positional encoding to add to the image. Must + have the same shape as image_embedding. + point_embedding (torch.Tensor): the embedding to add to the query points. + Must have shape B x N_points x embedding_dim for any N_points. + + Returns: + torch.Tensor: the processed point_embedding + torch.Tensor: the processed image_embedding + """ + # BxCxHxW -> BxHWxC == B x N_image_tokens x C + bs, c, h, w = image_embedding.shape + image_embedding = image_embedding.flatten(2).permute(0, 2, 1) + image_pe = image_pe.flatten(2).permute(0, 2, 1) + + # Prepare queries + queries = point_embedding + keys = image_embedding + + # Apply transformer blocks and final layernorm + for layer in self.layers: + queries, keys = layer( + queries=queries, + keys=keys, + query_pe=point_embedding, + key_pe=image_pe, + ) + + # Apply the final attention layer from the points to the image + q = queries + point_embedding + k = keys + image_pe + attn_out = self.final_attn_token_to_image(q=q, k=k, v=keys) + queries = queries + attn_out + queries = self.norm_final_attn(queries) + + return queries, keys + + +class TwoWayAttentionBlock(nn.Module): + def __init__( + self, + embedding_dim: int, + num_heads: int, + mlp_dim: int = 2048, + activation: Type[nn.Module] = nn.ReLU, + attention_downsample_rate: int = 2, + skip_first_layer_pe: bool = False, + ) -> None: + """ + A transformer block with four layers: (1) self-attention of sparse + inputs, (2) cross attention of sparse inputs to dense inputs, (3) mlp + block on sparse inputs, and (4) cross attention of dense inputs to sparse + inputs. + + Arguments: + embedding_dim (int): the channel dimension of the embeddings + num_heads (int): the number of heads in the attention layers + mlp_dim (int): the hidden dimension of the mlp block + activation (nn.Module): the activation of the mlp block + skip_first_layer_pe (bool): skip the PE on the first layer + """ + super().__init__() + self.self_attn = Attention(embedding_dim, num_heads) + self.norm1 = nn.LayerNorm(embedding_dim) + + self.cross_attn_token_to_image = Attention( + embedding_dim, num_heads, downsample_rate=attention_downsample_rate + ) + self.norm2 = nn.LayerNorm(embedding_dim) + + self.mlp = MLPBlock(embedding_dim, mlp_dim, activation) + self.norm3 = nn.LayerNorm(embedding_dim) + + self.norm4 = nn.LayerNorm(embedding_dim) + self.cross_attn_image_to_token = Attention( + embedding_dim, num_heads, downsample_rate=attention_downsample_rate + ) + + self.skip_first_layer_pe = skip_first_layer_pe + + def forward( + self, queries: Tensor, keys: Tensor, query_pe: Tensor, key_pe: Tensor + ) -> Tuple[Tensor, Tensor]: + # Self attention block + if self.skip_first_layer_pe: + queries = self.self_attn(q=queries, k=queries, v=queries) + else: + q = queries + query_pe + attn_out = self.self_attn(q=q, k=q, v=queries) + queries = queries + attn_out + queries = self.norm1(queries) + + # Cross attention block, tokens attending to image embedding + q = queries + query_pe + k = keys + key_pe + attn_out = self.cross_attn_token_to_image(q=q, k=k, v=keys) + queries = queries + attn_out + queries = self.norm2(queries) + + # MLP block + mlp_out = self.mlp(queries) + queries = queries + mlp_out + queries = self.norm3(queries) + + # Cross attention block, image embedding attending to tokens + q = queries + query_pe + k = keys + key_pe + attn_out = self.cross_attn_image_to_token(q=k, k=q, v=queries) + keys = keys + attn_out + keys = self.norm4(keys) + + return queries, keys + + +class Attention(nn.Module): + """ + An attention layer that allows for downscaling the size of the embedding + after projection to queries, keys, and values. + """ + + def __init__( + self, + embedding_dim: int, + num_heads: int, + downsample_rate: int = 1, + ) -> None: + super().__init__() + self.embedding_dim = embedding_dim + self.internal_dim = embedding_dim // downsample_rate + self.num_heads = num_heads + assert self.internal_dim % num_heads == 0, "num_heads must divide embedding_dim." + + self.q_proj = nn.Linear(embedding_dim, self.internal_dim) + self.k_proj = nn.Linear(embedding_dim, self.internal_dim) + self.v_proj = nn.Linear(embedding_dim, self.internal_dim) + self.out_proj = nn.Linear(self.internal_dim, embedding_dim) + + def _separate_heads(self, x: Tensor, num_heads: int) -> Tensor: + b, n, c = x.shape + x = x.reshape(b, n, num_heads, c // num_heads) + return x.transpose(1, 2) # B x N_heads x N_tokens x C_per_head + + def _recombine_heads(self, x: Tensor) -> Tensor: + b, n_heads, n_tokens, c_per_head = x.shape + x = x.transpose(1, 2) + return x.reshape(b, n_tokens, n_heads * c_per_head) # B x N_tokens x C + + def forward(self, q: Tensor, k: Tensor, v: Tensor) -> Tensor: + # Input projections + q = self.q_proj(q) + k = self.k_proj(k) + v = self.v_proj(v) + + # Separate into heads + q = self._separate_heads(q, self.num_heads) + k = self._separate_heads(k, self.num_heads) + v = self._separate_heads(v, self.num_heads) + + # Attention + _, _, _, c_per_head = q.shape + attn = q @ k.permute(0, 1, 3, 2) # B x N_heads x N_tokens x N_tokens + attn = attn / math.sqrt(c_per_head) + attn = torch.softmax(attn, dim=-1) + + # Get output + out = attn @ v + out = self._recombine_heads(out) + out = self.out_proj(out) + + return out \ No newline at end of file diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/segment_anything/predictor.py b/downstream/ProxyCLIP_TPAMI/clipself/src/segment_anything/predictor.py new file mode 100644 index 0000000000000000000000000000000000000000..8a6e6d816955b4c6097e1de6ce6e4ed3bafe327c --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/segment_anything/predictor.py @@ -0,0 +1,269 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import numpy as np +import torch + +from segment_anything.modeling import Sam + +from typing import Optional, Tuple + +from .utils.transforms import ResizeLongestSide + + +class SamPredictor: + def __init__( + self, + sam_model: Sam, + ) -> None: + """ + Uses SAM to calculate the image embedding for an image, and then + allow repeated, efficient mask prediction given prompts. + + Arguments: + sam_model (Sam): The model to use for mask prediction. + """ + super().__init__() + self.model = sam_model + self.transform = ResizeLongestSide(sam_model.image_encoder.img_size) + self.reset_image() + + def set_image( + self, + image: np.ndarray, + image_format: str = "RGB", + ) -> None: + """ + Calculates the image embeddings for the provided image, allowing + masks to be predicted with the 'predict' method. + + Arguments: + image (np.ndarray): The image for calculating masks. Expects an + image in HWC uint8 format, with pixel values in [0, 255]. + image_format (str): The color format of the image, in ['RGB', 'BGR']. + """ + assert image_format in [ + "RGB", + "BGR", + ], f"image_format must be in ['RGB', 'BGR'], is {image_format}." + if image_format != self.model.image_format: + image = image[..., ::-1] + + # Transform the image to the form expected by the model + input_image = self.transform.apply_image(image) + input_image_torch = torch.as_tensor(input_image, device=self.device) + input_image_torch = input_image_torch.permute(2, 0, 1).contiguous()[None, :, :, :] + + self.set_torch_image(input_image_torch, image.shape[:2]) + + @torch.no_grad() + def set_torch_image( + self, + transformed_image: torch.Tensor, + original_image_size: Tuple[int, ...], + ) -> None: + """ + Calculates the image embeddings for the provided image, allowing + masks to be predicted with the 'predict' method. Expects the input + image to be already transformed to the format expected by the model. + + Arguments: + transformed_image (torch.Tensor): The input image, with shape + 1x3xHxW, which has been transformed with ResizeLongestSide. + original_image_size (tuple(int, int)): The size of the image + before transformation, in (H, W) format. + """ + assert ( + len(transformed_image.shape) == 4 + and transformed_image.shape[1] == 3 + and max(*transformed_image.shape[2:]) == self.model.image_encoder.img_size + ), f"set_torch_image input must be BCHW with long side {self.model.image_encoder.img_size}." + self.reset_image() + + self.original_size = original_image_size + self.input_size = tuple(transformed_image.shape[-2:]) + input_image = self.model.preprocess(transformed_image) + self.features = self.model.image_encoder(input_image) + self.is_image_set = True + + def predict( + self, + point_coords: Optional[np.ndarray] = None, + point_labels: Optional[np.ndarray] = None, + box: Optional[np.ndarray] = None, + mask_input: Optional[np.ndarray] = None, + multimask_output: bool = True, + return_logits: bool = False, + ) -> Tuple[np.ndarray, np.ndarray, np.ndarray]: + """ + Predict masks for the given input prompts, using the currently set image. + + Arguments: + point_coords (np.ndarray or None): A Nx2 array of point prompts to the + model. Each point is in (X,Y) in pixels. + point_labels (np.ndarray or None): A length N array of labels for the + point prompts. 1 indicates a foreground point and 0 indicates a + background point. + box (np.ndarray or None): A length 4 array given a box prompt to the + model, in XYXY format. + mask_input (np.ndarray): A low resolution mask input to the model, typically + coming from a previous prediction iteration. Has form 1xHxW, where + for SAM, H=W=256. + multimask_output (bool): If true, the model will return three masks. + For ambiguous input prompts (such as a single click), this will often + produce better masks than a single prediction. If only a single + mask is needed, the model's predicted quality score can be used + to select the best mask. For non-ambiguous prompts, such as multiple + input prompts, multimask_output=False can give better results. + return_logits (bool): If true, returns un-thresholded masks logits + instead of a binary mask. + + Returns: + (np.ndarray): The output masks in CxHxW format, where C is the + number of masks, and (H, W) is the original image size. + (np.ndarray): An array of length C containing the model's + predictions for the quality of each mask. + (np.ndarray): An array of shape CxHxW, where C is the number + of masks and H=W=256. These low resolution logits can be passed to + a subsequent iteration as mask input. + """ + if not self.is_image_set: + raise RuntimeError("An image must be set with .set_image(...) before mask prediction.") + + # Transform input prompts + coords_torch, labels_torch, box_torch, mask_input_torch = None, None, None, None + if point_coords is not None: + assert ( + point_labels is not None + ), "point_labels must be supplied if point_coords is supplied." + point_coords = self.transform.apply_coords(point_coords, self.original_size) + coords_torch = torch.as_tensor(point_coords, dtype=torch.float, device=self.device) + labels_torch = torch.as_tensor(point_labels, dtype=torch.int, device=self.device) + coords_torch, labels_torch = coords_torch[None, :, :], labels_torch[None, :] + if box is not None: + box = self.transform.apply_boxes(box, self.original_size) + box_torch = torch.as_tensor(box, dtype=torch.float, device=self.device) + box_torch = box_torch[None, :] + if mask_input is not None: + mask_input_torch = torch.as_tensor(mask_input, dtype=torch.float, device=self.device) + mask_input_torch = mask_input_torch[None, :, :, :] + + masks, iou_predictions, low_res_masks = self.predict_torch( + coords_torch, + labels_torch, + box_torch, + mask_input_torch, + multimask_output, + return_logits=return_logits, + ) + + masks_np = masks[0].detach().cpu().numpy() + iou_predictions_np = iou_predictions[0].detach().cpu().numpy() + low_res_masks_np = low_res_masks[0].detach().cpu().numpy() + return masks_np, iou_predictions_np, low_res_masks_np + + @torch.no_grad() + def predict_torch( + self, + point_coords: Optional[torch.Tensor], + point_labels: Optional[torch.Tensor], + boxes: Optional[torch.Tensor] = None, + mask_input: Optional[torch.Tensor] = None, + multimask_output: bool = True, + return_logits: bool = False, + ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """ + Predict masks for the given input prompts, using the currently set image. + Input prompts are batched torch tensors and are expected to already be + transformed to the input frame using ResizeLongestSide. + + Arguments: + point_coords (torch.Tensor or None): A BxNx2 array of point prompts to the + model. Each point is in (X,Y) in pixels. + point_labels (torch.Tensor or None): A BxN array of labels for the + point prompts. 1 indicates a foreground point and 0 indicates a + background point. + boxes (np.ndarray or None): A Bx4 array given a box prompt to the + model, in XYXY format. + mask_input (np.ndarray): A low resolution mask input to the model, typically + coming from a previous prediction iteration. Has form Bx1xHxW, where + for SAM, H=W=256. Masks returned by a previous iteration of the + predict method do not need further transformation. + multimask_output (bool): If true, the model will return three masks. + For ambiguous input prompts (such as a single click), this will often + produce better masks than a single prediction. If only a single + mask is needed, the model's predicted quality score can be used + to select the best mask. For non-ambiguous prompts, such as multiple + input prompts, multimask_output=False can give better results. + return_logits (bool): If true, returns un-thresholded masks logits + instead of a binary mask. + + Returns: + (torch.Tensor): The output masks in BxCxHxW format, where C is the + number of masks, and (H, W) is the original image size. + (torch.Tensor): An array of shape BxC containing the model's + predictions for the quality of each mask. + (torch.Tensor): An array of shape BxCxHxW, where C is the number + of masks and H=W=256. These low res logits can be passed to + a subsequent iteration as mask input. + """ + if not self.is_image_set: + raise RuntimeError("An image must be set with .set_image(...) before mask prediction.") + + if point_coords is not None: + points = (point_coords, point_labels) + else: + points = None + + # Embed prompts + sparse_embeddings, dense_embeddings = self.model.prompt_encoder( + points=points, + boxes=boxes, + masks=mask_input, + ) + + # Predict masks + low_res_masks, iou_predictions = self.model.mask_decoder( + image_embeddings=self.features, + image_pe=self.model.prompt_encoder.get_dense_pe(), + sparse_prompt_embeddings=sparse_embeddings, + dense_prompt_embeddings=dense_embeddings, + multimask_output=multimask_output, + ) + + # Upscale the masks to the original image resolution + masks = self.model.postprocess_masks(low_res_masks, self.input_size, self.original_size) + + if not return_logits: + masks = masks > self.model.mask_threshold + + return masks, iou_predictions, low_res_masks + + def get_image_embedding(self) -> torch.Tensor: + """ + Returns the image embeddings for the currently set image, with + shape 1xCxHxW, where C is the embedding dimension and (H,W) are + the embedding spatial dimension of SAM (typically C=256, H=W=64). + """ + if not self.is_image_set: + raise RuntimeError( + "An image must be set with .set_image(...) to generate an embedding." + ) + assert self.features is not None, "Features must exist if an image has been set." + return self.features + + @property + def device(self) -> torch.device: + return self.model.device + + def reset_image(self) -> None: + """Resets the currently set image.""" + self.is_image_set = False + self.features = None + self.orig_h = None + self.orig_w = None + self.input_h = None + self.input_w = None diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/segment_anything/utils/__init__.py b/downstream/ProxyCLIP_TPAMI/clipself/src/segment_anything/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5277f46157403e47fd830fc519144b97ef69d4ae --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/segment_anything/utils/__init__.py @@ -0,0 +1,5 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/segment_anything/utils/amg.py b/downstream/ProxyCLIP_TPAMI/clipself/src/segment_anything/utils/amg.py new file mode 100644 index 0000000000000000000000000000000000000000..be064071ef399fea96c673ad173689656c23534a --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/segment_anything/utils/amg.py @@ -0,0 +1,346 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import numpy as np +import torch + +import math +from copy import deepcopy +from itertools import product +from typing import Any, Dict, Generator, ItemsView, List, Tuple + + +class MaskData: + """ + A structure for storing masks and their related data in batched format. + Implements basic filtering and concatenation. + """ + + def __init__(self, **kwargs) -> None: + for v in kwargs.values(): + assert isinstance( + v, (list, np.ndarray, torch.Tensor) + ), "MaskData only supports list, numpy arrays, and torch tensors." + self._stats = dict(**kwargs) + + def __setitem__(self, key: str, item: Any) -> None: + assert isinstance( + item, (list, np.ndarray, torch.Tensor) + ), "MaskData only supports list, numpy arrays, and torch tensors." + self._stats[key] = item + + def __delitem__(self, key: str) -> None: + del self._stats[key] + + def __getitem__(self, key: str) -> Any: + return self._stats[key] + + def items(self) -> ItemsView[str, Any]: + return self._stats.items() + + def filter(self, keep: torch.Tensor) -> None: + for k, v in self._stats.items(): + if v is None: + self._stats[k] = None + elif isinstance(v, torch.Tensor): + self._stats[k] = v[torch.as_tensor(keep, device=v.device)] + elif isinstance(v, np.ndarray): + self._stats[k] = v[keep.detach().cpu().numpy()] + elif isinstance(v, list) and keep.dtype == torch.bool: + self._stats[k] = [a for i, a in enumerate(v) if keep[i]] + elif isinstance(v, list): + self._stats[k] = [v[i] for i in keep] + else: + raise TypeError(f"MaskData key {k} has an unsupported type {type(v)}.") + + def cat(self, new_stats: "MaskData") -> None: + for k, v in new_stats.items(): + if k not in self._stats or self._stats[k] is None: + self._stats[k] = deepcopy(v) + elif isinstance(v, torch.Tensor): + self._stats[k] = torch.cat([self._stats[k], v], dim=0) + elif isinstance(v, np.ndarray): + self._stats[k] = np.concatenate([self._stats[k], v], axis=0) + elif isinstance(v, list): + self._stats[k] = self._stats[k] + deepcopy(v) + else: + raise TypeError(f"MaskData key {k} has an unsupported type {type(v)}.") + + def to_numpy(self) -> None: + for k, v in self._stats.items(): + if isinstance(v, torch.Tensor): + self._stats[k] = v.detach().cpu().numpy() + + +def is_box_near_crop_edge( + boxes: torch.Tensor, crop_box: List[int], orig_box: List[int], atol: float = 20.0 +) -> torch.Tensor: + """Filter masks at the edge of a crop, but not at the edge of the original image.""" + crop_box_torch = torch.as_tensor(crop_box, dtype=torch.float, device=boxes.device) + orig_box_torch = torch.as_tensor(orig_box, dtype=torch.float, device=boxes.device) + boxes = uncrop_boxes_xyxy(boxes, crop_box).float() + near_crop_edge = torch.isclose(boxes, crop_box_torch[None, :], atol=atol, rtol=0) + near_image_edge = torch.isclose(boxes, orig_box_torch[None, :], atol=atol, rtol=0) + near_crop_edge = torch.logical_and(near_crop_edge, ~near_image_edge) + return torch.any(near_crop_edge, dim=1) + + +def box_xyxy_to_xywh(box_xyxy: torch.Tensor) -> torch.Tensor: + box_xywh = deepcopy(box_xyxy) + box_xywh[2] = box_xywh[2] - box_xywh[0] + box_xywh[3] = box_xywh[3] - box_xywh[1] + return box_xywh + + +def batch_iterator(batch_size: int, *args) -> Generator[List[Any], None, None]: + assert len(args) > 0 and all( + len(a) == len(args[0]) for a in args + ), "Batched iteration must have inputs of all the same size." + n_batches = len(args[0]) // batch_size + int(len(args[0]) % batch_size != 0) + for b in range(n_batches): + yield [arg[b * batch_size : (b + 1) * batch_size] for arg in args] + + +def mask_to_rle_pytorch(tensor: torch.Tensor) -> List[Dict[str, Any]]: + """ + Encodes masks to an uncompressed RLE, in the format expected by + pycoco tools. + """ + # Put in fortran order and flatten h,w + b, h, w = tensor.shape + tensor = tensor.permute(0, 2, 1).flatten(1) + + # Compute change indices + diff = tensor[:, 1:] ^ tensor[:, :-1] + change_indices = diff.nonzero() + + # Encode run length + out = [] + for i in range(b): + cur_idxs = change_indices[change_indices[:, 0] == i, 1] + cur_idxs = torch.cat( + [ + torch.tensor([0], dtype=cur_idxs.dtype, device=cur_idxs.device), + cur_idxs + 1, + torch.tensor([h * w], dtype=cur_idxs.dtype, device=cur_idxs.device), + ] + ) + btw_idxs = cur_idxs[1:] - cur_idxs[:-1] + counts = [] if tensor[i, 0] == 0 else [0] + counts.extend(btw_idxs.detach().cpu().tolist()) + out.append({"size": [h, w], "counts": counts}) + return out + + +def rle_to_mask(rle: Dict[str, Any]) -> np.ndarray: + """Compute a binary mask from an uncompressed RLE.""" + h, w = rle["size"] + mask = np.empty(h * w, dtype=bool) + idx = 0 + parity = False + for count in rle["counts"]: + mask[idx : idx + count] = parity + idx += count + parity ^= True + mask = mask.reshape(w, h) + return mask.transpose() # Put in C order + + +def area_from_rle(rle: Dict[str, Any]) -> int: + return sum(rle["counts"][1::2]) + + +def calculate_stability_score( + masks: torch.Tensor, mask_threshold: float, threshold_offset: float +) -> torch.Tensor: + """ + Computes the stability score for a batch of masks. The stability + score is the IoU between the binary masks obtained by thresholding + the predicted mask logits at high and low values. + """ + # One mask is always contained inside the other. + # Save memory by preventing unnecessary cast to torch.int64 + intersections = ( + (masks > (mask_threshold + threshold_offset)) + .sum(-1, dtype=torch.int16) + .sum(-1, dtype=torch.int32) + ) + unions = ( + (masks > (mask_threshold - threshold_offset)) + .sum(-1, dtype=torch.int16) + .sum(-1, dtype=torch.int32) + ) + return intersections / unions + + +def build_point_grid(n_per_side: int) -> np.ndarray: + """Generates a 2D grid of points evenly spaced in [0,1]x[0,1].""" + offset = 1 / (2 * n_per_side) + points_one_side = np.linspace(offset, 1 - offset, n_per_side) + points_x = np.tile(points_one_side[None, :], (n_per_side, 1)) + points_y = np.tile(points_one_side[:, None], (1, n_per_side)) + points = np.stack([points_x, points_y], axis=-1).reshape(-1, 2) + return points + + +def build_all_layer_point_grids( + n_per_side: int, n_layers: int, scale_per_layer: int +) -> List[np.ndarray]: + """Generates point grids for all crop layers.""" + points_by_layer = [] + for i in range(n_layers + 1): + n_points = int(n_per_side / (scale_per_layer**i)) + points_by_layer.append(build_point_grid(n_points)) + return points_by_layer + + +def generate_crop_boxes( + im_size: Tuple[int, ...], n_layers: int, overlap_ratio: float +) -> Tuple[List[List[int]], List[int]]: + """ + Generates a list of crop boxes of different sizes. Each layer + has (2**i)**2 boxes for the ith layer. + """ + crop_boxes, layer_idxs = [], [] + im_h, im_w = im_size + short_side = min(im_h, im_w) + + # Original image + crop_boxes.append([0, 0, im_w, im_h]) + layer_idxs.append(0) + + def crop_len(orig_len, n_crops, overlap): + return int(math.ceil((overlap * (n_crops - 1) + orig_len) / n_crops)) + + for i_layer in range(n_layers): + n_crops_per_side = 2 ** (i_layer + 1) + overlap = int(overlap_ratio * short_side * (2 / n_crops_per_side)) + + crop_w = crop_len(im_w, n_crops_per_side, overlap) + crop_h = crop_len(im_h, n_crops_per_side, overlap) + + crop_box_x0 = [int((crop_w - overlap) * i) for i in range(n_crops_per_side)] + crop_box_y0 = [int((crop_h - overlap) * i) for i in range(n_crops_per_side)] + + # Crops in XYWH format + for x0, y0 in product(crop_box_x0, crop_box_y0): + box = [x0, y0, min(x0 + crop_w, im_w), min(y0 + crop_h, im_h)] + crop_boxes.append(box) + layer_idxs.append(i_layer + 1) + + return crop_boxes, layer_idxs + + +def uncrop_boxes_xyxy(boxes: torch.Tensor, crop_box: List[int]) -> torch.Tensor: + x0, y0, _, _ = crop_box + offset = torch.tensor([[x0, y0, x0, y0]], device=boxes.device) + # Check if boxes has a channel dimension + if len(boxes.shape) == 3: + offset = offset.unsqueeze(1) + return boxes + offset + + +def uncrop_points(points: torch.Tensor, crop_box: List[int]) -> torch.Tensor: + x0, y0, _, _ = crop_box + offset = torch.tensor([[x0, y0]], device=points.device) + # Check if points has a channel dimension + if len(points.shape) == 3: + offset = offset.unsqueeze(1) + return points + offset + + +def uncrop_masks( + masks: torch.Tensor, crop_box: List[int], orig_h: int, orig_w: int +) -> torch.Tensor: + x0, y0, x1, y1 = crop_box + if x0 == 0 and y0 == 0 and x1 == orig_w and y1 == orig_h: + return masks + # Coordinate transform masks + pad_x, pad_y = orig_w - (x1 - x0), orig_h - (y1 - y0) + pad = (x0, pad_x - x0, y0, pad_y - y0) + return torch.nn.functional.pad(masks, pad, value=0) + + +def remove_small_regions( + mask: np.ndarray, area_thresh: float, mode: str +) -> Tuple[np.ndarray, bool]: + """ + Removes small disconnected regions and holes in a mask. Returns the + mask and an indicator of if the mask has been modified. + """ + import cv2 # type: ignore + + assert mode in ["holes", "islands"] + correct_holes = mode == "holes" + working_mask = (correct_holes ^ mask).astype(np.uint8) + n_labels, regions, stats, _ = cv2.connectedComponentsWithStats(working_mask, 8) + sizes = stats[:, -1][1:] # Row 0 is background label + small_regions = [i + 1 for i, s in enumerate(sizes) if s < area_thresh] + if len(small_regions) == 0: + return mask, False + fill_labels = [0] + small_regions + if not correct_holes: + fill_labels = [i for i in range(n_labels) if i not in fill_labels] + # If every region is below threshold, keep largest + if len(fill_labels) == 0: + fill_labels = [int(np.argmax(sizes)) + 1] + mask = np.isin(regions, fill_labels) + return mask, True + + +def coco_encode_rle(uncompressed_rle: Dict[str, Any]) -> Dict[str, Any]: + from pycocotools import mask as mask_utils # type: ignore + + h, w = uncompressed_rle["size"] + rle = mask_utils.frPyObjects(uncompressed_rle, h, w) + rle["counts"] = rle["counts"].decode("utf-8") # Necessary to serialize with json + return rle + + +def batched_mask_to_box(masks: torch.Tensor) -> torch.Tensor: + """ + Calculates boxes in XYXY format around masks. Return [0,0,0,0] for + an empty mask. For input shape C1xC2x...xHxW, the output shape is C1xC2x...x4. + """ + # torch.max below raises an error on empty inputs, just skip in this case + if torch.numel(masks) == 0: + return torch.zeros(*masks.shape[:-2], 4, device=masks.device) + + # Normalize shape to CxHxW + shape = masks.shape + h, w = shape[-2:] + if len(shape) > 2: + masks = masks.flatten(0, -3) + else: + masks = masks.unsqueeze(0) + + # Get top and bottom edges + in_height, _ = torch.max(masks, dim=-1) + in_height_coords = in_height * torch.arange(h, device=in_height.device)[None, :] + bottom_edges, _ = torch.max(in_height_coords, dim=-1) + in_height_coords = in_height_coords + h * (~in_height) + top_edges, _ = torch.min(in_height_coords, dim=-1) + + # Get left and right edges + in_width, _ = torch.max(masks, dim=-2) + in_width_coords = in_width * torch.arange(w, device=in_width.device)[None, :] + right_edges, _ = torch.max(in_width_coords, dim=-1) + in_width_coords = in_width_coords + w * (~in_width) + left_edges, _ = torch.min(in_width_coords, dim=-1) + + # If the mask is empty the right edge will be to the left of the left edge. + # Replace these boxes with [0, 0, 0, 0] + empty_filter = (right_edges < left_edges) | (bottom_edges < top_edges) + out = torch.stack([left_edges, top_edges, right_edges, bottom_edges], dim=-1) + out = out * (~empty_filter).unsqueeze(-1) + + # Return to original shape + if len(shape) > 2: + out = out.reshape(*shape[:-2], 4) + else: + out = out[0] + + return out diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/segment_anything/utils/onnx.py b/downstream/ProxyCLIP_TPAMI/clipself/src/segment_anything/utils/onnx.py new file mode 100644 index 0000000000000000000000000000000000000000..3196bdf4b782e6eeb3da4ad66ef3c7b1741535fe --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/segment_anything/utils/onnx.py @@ -0,0 +1,144 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import torch +import torch.nn as nn +from torch.nn import functional as F + +from typing import Tuple + +from ..modeling import Sam +from .amg import calculate_stability_score + + +class SamOnnxModel(nn.Module): + """ + This model should not be called directly, but is used in ONNX export. + It combines the prompt encoder, mask decoder, and mask postprocessing of Sam, + with some functions modified to enable model tracing. Also supports extra + options controlling what information. See the ONNX export script for details. + """ + + def __init__( + self, + model: Sam, + return_single_mask: bool, + use_stability_score: bool = False, + return_extra_metrics: bool = False, + ) -> None: + super().__init__() + self.mask_decoder = model.mask_decoder + self.model = model + self.img_size = model.image_encoder.img_size + self.return_single_mask = return_single_mask + self.use_stability_score = use_stability_score + self.stability_score_offset = 1.0 + self.return_extra_metrics = return_extra_metrics + + @staticmethod + def resize_longest_image_size( + input_image_size: torch.Tensor, longest_side: int + ) -> torch.Tensor: + input_image_size = input_image_size.to(torch.float32) + scale = longest_side / torch.max(input_image_size) + transformed_size = scale * input_image_size + transformed_size = torch.floor(transformed_size + 0.5).to(torch.int64) + return transformed_size + + def _embed_points(self, point_coords: torch.Tensor, point_labels: torch.Tensor) -> torch.Tensor: + point_coords = point_coords + 0.5 + point_coords = point_coords / self.img_size + point_embedding = self.model.prompt_encoder.pe_layer._pe_encoding(point_coords) + point_labels = point_labels.unsqueeze(-1).expand_as(point_embedding) + + point_embedding = point_embedding * (point_labels != -1) + point_embedding = point_embedding + self.model.prompt_encoder.not_a_point_embed.weight * ( + point_labels == -1 + ) + + for i in range(self.model.prompt_encoder.num_point_embeddings): + point_embedding = point_embedding + self.model.prompt_encoder.point_embeddings[ + i + ].weight * (point_labels == i) + + return point_embedding + + def _embed_masks(self, input_mask: torch.Tensor, has_mask_input: torch.Tensor) -> torch.Tensor: + mask_embedding = has_mask_input * self.model.prompt_encoder.mask_downscaling(input_mask) + mask_embedding = mask_embedding + ( + 1 - has_mask_input + ) * self.model.prompt_encoder.no_mask_embed.weight.reshape(1, -1, 1, 1) + return mask_embedding + + def mask_postprocessing(self, masks: torch.Tensor, orig_im_size: torch.Tensor) -> torch.Tensor: + masks = F.interpolate( + masks, + size=(self.img_size, self.img_size), + mode="bilinear", + align_corners=False, + ) + + prepadded_size = self.resize_longest_image_size(orig_im_size, self.img_size).to(torch.int64) + masks = masks[..., : prepadded_size[0], : prepadded_size[1]] # type: ignore + + orig_im_size = orig_im_size.to(torch.int64) + h, w = orig_im_size[0], orig_im_size[1] + masks = F.interpolate(masks, size=(h, w), mode="bilinear", align_corners=False) + return masks + + def select_masks( + self, masks: torch.Tensor, iou_preds: torch.Tensor, num_points: int + ) -> Tuple[torch.Tensor, torch.Tensor]: + # Determine if we should return the multiclick mask or not from the number of points. + # The reweighting is used to avoid control flow. + score_reweight = torch.tensor( + [[1000] + [0] * (self.model.mask_decoder.num_mask_tokens - 1)] + ).to(iou_preds.device) + score = iou_preds + (num_points - 2.5) * score_reweight + best_idx = torch.argmax(score, dim=1) + masks = masks[torch.arange(masks.shape[0]), best_idx, :, :].unsqueeze(1) + iou_preds = iou_preds[torch.arange(masks.shape[0]), best_idx].unsqueeze(1) + + return masks, iou_preds + + @torch.no_grad() + def forward( + self, + image_embeddings: torch.Tensor, + point_coords: torch.Tensor, + point_labels: torch.Tensor, + mask_input: torch.Tensor, + has_mask_input: torch.Tensor, + orig_im_size: torch.Tensor, + ): + sparse_embedding = self._embed_points(point_coords, point_labels) + dense_embedding = self._embed_masks(mask_input, has_mask_input) + + masks, scores = self.model.mask_decoder.predict_masks( + image_embeddings=image_embeddings, + image_pe=self.model.prompt_encoder.get_dense_pe(), + sparse_prompt_embeddings=sparse_embedding, + dense_prompt_embeddings=dense_embedding, + ) + + if self.use_stability_score: + scores = calculate_stability_score( + masks, self.model.mask_threshold, self.stability_score_offset + ) + + if self.return_single_mask: + masks, scores = self.select_masks(masks, scores, point_coords.shape[1]) + + upscaled_masks = self.mask_postprocessing(masks, orig_im_size) + + if self.return_extra_metrics: + stability_scores = calculate_stability_score( + upscaled_masks, self.model.mask_threshold, self.stability_score_offset + ) + areas = (upscaled_masks > self.model.mask_threshold).sum(-1).sum(-1) + return upscaled_masks, scores, stability_scores, areas, masks + + return upscaled_masks, scores, masks diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/segment_anything/utils/transforms.py b/downstream/ProxyCLIP_TPAMI/clipself/src/segment_anything/utils/transforms.py new file mode 100644 index 0000000000000000000000000000000000000000..c08ba1e3db751f3a5483a003be38c69c2cf2df85 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/segment_anything/utils/transforms.py @@ -0,0 +1,102 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import numpy as np +import torch +from torch.nn import functional as F +from torchvision.transforms.functional import resize, to_pil_image # type: ignore + +from copy import deepcopy +from typing import Tuple + + +class ResizeLongestSide: + """ + Resizes images to the longest side 'target_length', as well as provides + methods for resizing coordinates and boxes. Provides methods for + transforming both numpy array and batched torch tensors. + """ + + def __init__(self, target_length: int) -> None: + self.target_length = target_length + + def apply_image(self, image: np.ndarray) -> np.ndarray: + """ + Expects a numpy array with shape HxWxC in uint8 format. + """ + target_size = self.get_preprocess_shape(image.shape[0], image.shape[1], self.target_length) + return np.array(resize(to_pil_image(image), target_size)) + + def apply_coords(self, coords: np.ndarray, original_size: Tuple[int, ...]) -> np.ndarray: + """ + Expects a numpy array of length 2 in the final dimension. Requires the + original image size in (H, W) format. + """ + old_h, old_w = original_size + new_h, new_w = self.get_preprocess_shape( + original_size[0], original_size[1], self.target_length + ) + coords = deepcopy(coords).astype(float) + coords[..., 0] = coords[..., 0] * (new_w / old_w) + coords[..., 1] = coords[..., 1] * (new_h / old_h) + return coords + + def apply_boxes(self, boxes: np.ndarray, original_size: Tuple[int, ...]) -> np.ndarray: + """ + Expects a numpy array shape Bx4. Requires the original image size + in (H, W) format. + """ + boxes = self.apply_coords(boxes.reshape(-1, 2, 2), original_size) + return boxes.reshape(-1, 4) + + def apply_image_torch(self, image: torch.Tensor) -> torch.Tensor: + """ + Expects batched images with shape BxCxHxW and float format. This + transformation may not exactly match apply_image. apply_image is + the transformation expected by the model. + """ + # Expects an image in BCHW format. May not exactly match apply_image. + target_size = self.get_preprocess_shape(image.shape[2], image.shape[3], self.target_length) + return F.interpolate( + image, target_size, mode="bilinear", align_corners=False, antialias=True + ) + + def apply_coords_torch( + self, coords: torch.Tensor, original_size: Tuple[int, ...] + ) -> torch.Tensor: + """ + Expects a torch tensor with length 2 in the last dimension. Requires the + original image size in (H, W) format. + """ + old_h, old_w = original_size + new_h, new_w = self.get_preprocess_shape( + original_size[0], original_size[1], self.target_length + ) + coords = deepcopy(coords).to(torch.float) + coords[..., 0] = coords[..., 0] * (new_w / old_w) + coords[..., 1] = coords[..., 1] * (new_h / old_h) + return coords + + def apply_boxes_torch( + self, boxes: torch.Tensor, original_size: Tuple[int, ...] + ) -> torch.Tensor: + """ + Expects a torch tensor with shape Bx4. Requires the original image + size in (H, W) format. + """ + boxes = self.apply_coords_torch(boxes.reshape(-1, 2, 2), original_size) + return boxes.reshape(-1, 4) + + @staticmethod + def get_preprocess_shape(oldh: int, oldw: int, long_side_length: int) -> Tuple[int, int]: + """ + Compute the output size given input size and target long side length. + """ + scale = long_side_length * 1.0 / max(oldh, oldw) + newh, neww = oldh * scale, oldw * scale + neww = int(neww + 0.5) + newh = int(newh + 0.5) + return (newh, neww) diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/training/.gitignore b/downstream/ProxyCLIP_TPAMI/clipself/src/training/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..333c1e910a3e2bef1b9d0d4587392627d8388974 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/training/.gitignore @@ -0,0 +1 @@ +logs/ diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/training/__init__.py b/downstream/ProxyCLIP_TPAMI/clipself/src/training/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/training/clim.py b/downstream/ProxyCLIP_TPAMI/clipself/src/training/clim.py new file mode 100644 index 0000000000000000000000000000000000000000..59e511efc424eeb063d183bce68e5415222b86c6 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/training/clim.py @@ -0,0 +1,287 @@ +import random +import torch +import torch.nn.functional as F +import torch.nn as nn +import logging +from functools import partial +from training.misc import is_main_process +import torchvision.transforms.functional as TF +from torchvision.transforms import InterpolationMode +try: + import torch.distributed.nn + from torch import distributed as dist + + has_distributed = True +except ImportError: + has_distributed = False + +ignore_keys=['logit_scale', + 'backbone.visual.blocks.11.attn.q_bias', + 'backbone.visual.blocks.11.attn.q_proj.weight', + 'backbone.visual.blocks.11.attn.k_proj.weight'] + +class ClipLoss(nn.Module): + + def __init__( + self, + local_loss=False, + gather_with_grad=False, + cache_labels=False, + rank=0, + world_size=1, + use_horovod=False, + ): + super().__init__() + self.local_loss = local_loss + self.gather_with_grad = gather_with_grad + self.cache_labels = cache_labels + self.rank = rank + self.world_size = world_size + self.use_horovod = use_horovod + + # cache state + self.prev_num_logits = 0 + self.labels = {} + + def get_ground_truth(self, device, num_logits) -> torch.Tensor: + # calculated ground-truth and cache if enabled + if self.prev_num_logits != num_logits or device not in self.labels: + labels = torch.arange(num_logits, device=device, dtype=torch.long) + if self.world_size > 1 and self.local_loss: + labels = labels + num_logits * self.rank + if self.cache_labels: + self.labels[device] = labels + self.prev_num_logits = num_logits + else: + labels = self.labels[device] + return labels + + def get_logits(self, image_features, text_features, logit_scale): + if self.world_size > 1: + all_image_features, all_text_features = gather_features( + image_features, text_features, + self.local_loss, self.gather_with_grad, self.rank, self.world_size, self.use_horovod) + if self.local_loss: + logits_per_image = logit_scale * image_features @ all_text_features.T + logits_per_text = logit_scale * text_features @ all_image_features.T + else: + logits_per_image = logit_scale * all_image_features @ all_text_features.T + logits_per_text = logits_per_image.T + else: + logits_per_image = logit_scale * image_features @ text_features.T + logits_per_text = logit_scale * text_features @ image_features.T + + return logits_per_image, logits_per_text + + def forward(self, image_features, text_features, logit_scale, output_dict=False): + device = image_features.device + logits_per_image, logits_per_text = self.get_logits(image_features, text_features, logit_scale) + + labels = self.get_ground_truth(device, logits_per_image.shape[0]) + total_loss = ( + F.cross_entropy(logits_per_image, labels) + + F.cross_entropy(logits_per_text, labels) + ) / 2 + + return {"contrastive_loss": total_loss} if output_dict else total_loss + +def gather_features( + image_features, + text_features, + local_loss=False, + gather_with_grad=False, + rank=0, + world_size=1, + use_horovod=False +): + assert has_distributed, 'torch.distributed did not import correctly, please use a PyTorch version with support.' + # We gather tensors from all gpus + if gather_with_grad: + all_image_features = torch.cat(torch.distributed.nn.all_gather(image_features), dim=0) + all_text_features = torch.cat(torch.distributed.nn.all_gather(text_features), dim=0) + else: + gathered_image_features = [torch.zeros_like(image_features) for _ in range(world_size)] + gathered_text_features = [torch.zeros_like(text_features) for _ in range(world_size)] + dist.all_gather(gathered_image_features, image_features) + dist.all_gather(gathered_text_features, text_features) + # if not local_loss: # TODO: preserve local grads even when local loss is used + # ensure grads for local rank when all_* features don't have a gradient + gathered_image_features[rank] = image_features + gathered_text_features[rank] = text_features + all_image_features = torch.cat(gathered_image_features, dim=0) + all_text_features = torch.cat(gathered_text_features, dim=0) + + return all_image_features, all_text_features + +class CLIM(nn.Module): + def __init__(self, + student_backbone, + teacher_backbone, + device, + cast_dtype, + distributed, + args): + super().__init__() + self.device=device + self.distributed=distributed + self.cast_dtype=cast_dtype + self.args=args + self.mosaic_choices = [2, 3, 4] + self.path_sample_choice=5 + self.clip_loss = ClipLoss(local_loss=True, + gather_with_grad=True, # use gather with grad + cache_labels=True, + rank=args.rank, + world_size=args.world_size, + use_horovod=args.horovod,) + self.student = student_backbone + self.teacher = teacher_backbone + # for n, p in self.teacher.named_parameters(): + # if "dino" in n: + # p.requires_grad = False + for n, p in self.student.named_parameters(): + for ignore in ignore_keys: + if ignore in n: + p.requires_grad = False + break + + def forward(self, batch): + if self.args.distributed: + student = self.student.module + teacher = self.teacher.module + else: + student = self.student + teacher = self.teacher + images, texts = batch + images = images.to(device=self.device, dtype=self.cast_dtype, non_blocking=True) + texts = texts.to(device=self.device, non_blocking=True) + mosaicked_images, pseudo_boxes_list, split_images, single_images = self.split_a_batch(images, self.args.det_image_size) + teacher_image_features = [] + # teacher_image_patch_features=[] + # sampled_img_patch_coords, image_patch_crops= self.get_img_patchs(mosaicked_images, + # [teacher['backbone'].visual.image_size, + # teacher['backbone'].visual.image_size]) + with torch.no_grad(): + text_features = teacher['backbone'].encode_text(texts, normalize=True) + for split_image in split_images: + teacher_image_features.append(teacher['backbone'].encode_image(split_image, normalize=True)) + # for image_patch_crop in image_patch_crops: + # teacher_image_patch_features.append(teacher['backbone'].encode_image(image_patch_crop)) + teacher_image_features=torch.cat(teacher_image_features) + # teacher_image_patch_features=torch.cat(teacher_image_patch_features) + student_roi_features = student['backbone'].encode_pseudo_boxes(mosaicked_images, + pseudo_boxes_list, + normalize=True, + extract_type=self.args.extract_type) + # student_roi_patch_features = student['backbone'].encode_pseudo_boxes(mosaicked_images, + # sampled_img_patch_coords, + # normalize=True, + # extract_type=self.args.extract_type) + if single_images.numel()>0: + student_image_features = student['backbone'].encode_image(single_images, normalize=True) + student_features = torch.cat([student_roi_features, student_image_features], dim=0) + else: + student_features=student_roi_features + logit_scale = student['backbone'].logit_scale.exp() + contrast_loss = self.clip_loss(student_features, + text_features, + logit_scale, + output_dict=False) + pseudo_box_loss_cosine = 1.0 - (student_roi_features * teacher_image_features).sum(-1).mean() + # image_patch_loss_cosine = 1.0 - (student_roi_patch_features * teacher_image_patch_features).sum(-1).mean() + # loss_cosine=(pseudo_box_loss_cosine+image_patch_loss_cosine)/2.0 + losses = dict(loss_cosine=(contrast_loss+pseudo_box_loss_cosine)/2.0) + return losses, len(images), student['backbone'].logit_scale.exp() + + + def train(self,mode=True): + super().train(mode) + self.teacher.eval() + if is_main_process(): + logging.info("set teacher as eval mode") + + def prepare_for_distributed_training(self): + self.student=torch.nn.parallel.DistributedDataParallel(self.student, device_ids=[self.device]) + self.teacher=torch.nn.parallel.DistributedDataParallel(self.teacher, device_ids=[self.device]) + + def update_teacher(self, m): + update_fn=lambda i, j: m * i + (1. - m) * j + with torch.no_grad(): + # for teacher_v, student_v in zip(self.teacher.module.state_dict().values(), self.student.state_dict().values()): + # teacher_v.copy_(update_fn(teacher_v, student_v)) + for (teacher_k, teacher_v), (student_k, student_v) in zip(self.teacher.module.state_dict().items(), self.student.state_dict().items()): + if 'dino' in teacher_k and 'dino' in student_k: + teacher_v.copy_(update_fn(teacher_v, student_v)) + + def get_params_groups(self): + return self.student.module.named_parameters() + + @staticmethod + def _generate_normed_boxes(M, N): + grid_x, grid_y = torch.meshgrid(torch.linspace(0, 1, N + 1), torch.linspace(0, 1, M + 1), + indexing='xy') + x0y0s = torch.stack([grid_x[:M, :N], grid_y[:M, :N]], dim=-1) + x1y1s = torch.stack([grid_x[1:, 1:], grid_y[1:, 1:]], dim=-1) + pseudo_boxes = torch.cat([x0y0s, x1y1s], + dim=-1).view(-1, 4) + return pseudo_boxes + + def split_a_batch(self, images, train_image_size): + batch_size = images.shape[0] + choices = self.mosaic_choices + min_images = sum([c**2 for c in choices]) + assert batch_size >= min_images + num_single = batch_size % min_images + num_groups = batch_size // min_images + # assert num_single == 0 + split = [c for c in choices for _ in range(num_groups)] + # split = [2] * num_groups + [3] * num_groups + [4] * num_groups + pseudo_boxes_list = [self._generate_normed_boxes(s, s).to(images) for s in split] + images_list = torch.split(images, [s**2 for s in split] + [num_single], dim=0) + mosaicked_images_list = [ + F.interpolate(self._mosaic_a_minibatch(imgs, s, s), size=train_image_size, mode='bicubic') + for imgs, s in zip(images_list[:-1], split)] + + mosaicked_images = torch.cat(mosaicked_images_list) + return mosaicked_images, pseudo_boxes_list, images_list[:-1], images_list[-1] + + @staticmethod + def _mosaic_a_minibatch(images, M, N): + bs, _, h, w = images.shape + assert bs % (M * N) == 0 + num_mosaic = bs // (M*N) + images_for_mosaic = images.permute(0, 2, 3, 1) + images_for_mosaic = images_for_mosaic.view(num_mosaic, M, N, h, w, 3) + images_for_mosaic = images_for_mosaic.permute(0, 1, 3, 2, 4, 5).contiguous() + mosaicked_images = images_for_mosaic.view(num_mosaic, M * h, N * w, 3) + mosaicked_images = mosaicked_images.permute(0, 3, 1, 2) + return mosaicked_images + + def get_img_patchs(self,img_tensor, output_size): + _, _, H, W = img_tensor.shape + img_patch_coords=[self._generate_normed_boxes(i*2,i*2) for i in self.mosaic_choices] + sampled_img_patch_coords=[] + image_patch_crops=[] + for img_patch_coord in img_patch_coords: + num_coords = img_patch_coord.size(0) + if num_coords <= self.path_sample_choice: + sampled = img_patch_coord + else: + indices = torch.randperm(num_coords)[:self.path_sample_choice] + sampled = img_patch_coord[indices] + sampled_img_patch_coords.append(sampled.to(self.device)) + for img_index, sampled_coord in enumerate(sampled_img_patch_coords): + image_patch_crops_i=[] + _coord = sampled_coord.clone() + _coord[:,2] = _coord[:,2] - _coord[:,0] + _coord[:,3] = _coord[:,3] - _coord[:,1] + _coord[:, [0, 2]] *= W + _coord[:, [1, 3]] *= H + _coord=_coord.to(torch.int16) + for i in _coord: + image_patch_crops_i.append(TF.resized_crop(img_tensor[img_index],i[0],i[1],i[3],i[2], + size=output_size, + interpolation=InterpolationMode.BICUBIC, + antialias=True)) + image_patch_crops.append(torch.stack(image_patch_crops_i,dim=0)) + return sampled_img_patch_coords, image_patch_crops diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/training/clipself.py b/downstream/ProxyCLIP_TPAMI/clipself/src/training/clipself.py new file mode 100644 index 0000000000000000000000000000000000000000..83a9d4931581b0560de756fe22195000e072f7d7 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/training/clipself.py @@ -0,0 +1,147 @@ +import torch +import torch.nn.functional as F +import torch.nn as nn +import logging +from training.misc import is_main_process +from src.segment_anything import sam_model_registry +from .utils import get_freeze_keys + +def build_vfm(name): + # Register hook for SAM model + feat_out = {} + def hook_fn_forward_qkv(module, input, output): + feat_out["qkv"] = output + if name=="sam": + vfm = sam_model_registry["vit_b"](checkpoint="/mnt/SSD8T/home/wjj/code/ProxyCLIP/sam_ckpts/sam_vit_b_01ec64.pth").half() + vfm.image_encoder._modules["blocks"][-1]._modules["mlp"].register_forward_hook(hook_fn_forward_qkv) + elif name=="dino": + vfm = torch.hub.load('facebookresearch/dino:main', 'dino_vitb8').half() + vfm._modules["blocks"][-1]._modules["attn"]._modules["qkv"].register_forward_hook(hook_fn_forward_qkv) + elif name == 'dinov2': + vfm = torch.hub.load('facebookresearch/dinov2', 'dinov2_vitb14_reg').half() + vfm._modules["blocks"][-1]._modules["attn"]._modules["qkv"].register_forward_hook(hook_fn_forward_qkv) + else: + print("vlm_model not supported") + exit(0) + # Assuming this is the correct module path for the hook + for p in vfm.parameters(): + p.requires_grad = False + return vfm,feat_out + +class CLIPWithProjector(nn.Module): + def __init__(self, clip, hidden_dim=768, regular_alpha=0.7, args=None): + super().__init__() + self.clip = clip + self.regular_alpha =regular_alpha + self.args=args + self.mode=args.mode + self.logit_scale=clip.logit_scale + if args.mode == "qk_vfm_distill": + self.projector_q = nn.Sequential( + nn.Linear(hidden_dim, hidden_dim, bias=False), + nn.GELU(), + nn.Linear(hidden_dim, hidden_dim, bias=False) + ).to(args.device) + self.projector_k = nn.Sequential( + nn.Linear(hidden_dim, hidden_dim, bias=False), + nn.GELU(), + nn.Linear(hidden_dim, hidden_dim, bias=False) + ).to(args.device) + nn.init.zeros_(self.projector_q[2].weight) + nn.init.kaiming_normal_(self.projector_q[0].weight) + nn.init.zeros_(self.projector_k[2].weight) + nn.init.kaiming_normal_(self.projector_k[0].weight) + else: + self.projector= nn.Sequential( + nn.Linear(hidden_dim, hidden_dim, bias=False), + nn.GELU(), + nn.Linear(hidden_dim, hidden_dim, bias=False) + ).to(args.device) + nn.init.zeros_(self.projector[2].weight) + nn.init.kaiming_normal_(self.projector[0].weight) + freeze_keys=get_freeze_keys(args) + for n, p in self.clip.named_parameters(): + if n in freeze_keys: + p.requires_grad = False + + def forward(self, images, rois_list): + B = images.shape[0] + clip_roi_features, clip_dense_features = self.clip.encode_pseudo_boxes(images, + rois_list, + normalize=True, + extract_type=self.args.extract_type, + mode=self.mode, # "ss", "only_v","maskclip","sclip","ss_vfm_distill" + ex_feats=None) + if self.mode=="ss_vfm_distill": + N, _ = clip_dense_features.shape[1:] + clip_dense_features = clip_dense_features.transpose(0, 1).contiguous().view(N, B, -1).transpose(0, 1) + elif self.mode=="qk_vfm_distill": + q_feature, k_feature=clip_dense_features + N, _ = q_feature.shape[1:] + q_feature = q_feature.transpose(0, 1).contiguous().view(N, B, -1).transpose(0, 1) + k_feature = k_feature.transpose(0, 1).contiguous().view(N, B, -1).transpose(0, 1) + q_feature = q_feature + self.regular_alpha * self.projector_q(q_feature) + k_feature = k_feature + self.regular_alpha * self.projector_k(k_feature) + return clip_roi_features, q_feature, k_feature + else: + clip_dense_features=clip_dense_features.flatten(2,3).transpose(-2,-1) + clip_dense_features = clip_dense_features + self.regular_alpha * self.projector(clip_dense_features) + return clip_roi_features, clip_dense_features + + +class CLIPSelf: + def __call__(self, batch, student, teacher, vfm_model,feat_out, args): + losses={} + if args.distributed: + student = student.module + images, normed_boxes, image_crops, proxy_image = batch + images = images.to(device=args.device, dtype=torch.float16, non_blocking=True) + normed_boxes = normed_boxes.to(device=args.device, dtype=torch.float16,non_blocking=True) + image_crops = image_crops.to(device=args.device, dtype=torch.float16,non_blocking=True) + proxy_image=proxy_image.to(device=args.device, dtype=torch.float16, non_blocking=True) + rois_list = [] + crops_list = [] + for bboxes_per_image, crops_per_image in zip(normed_boxes, image_crops): + valid = bboxes_per_image[:, -1] > 0.5 + rois_list.append(bboxes_per_image[valid, :4]) + crops_list.append(crops_per_image[valid]) + image_crops = torch.cat(crops_list) + with torch.no_grad(): + teacher_crop_features = teacher.encode_image(image_crops, normalize=True) + if args.proxy: + if args.proxy=="sam": + # vfm_feats=vfm_model.image_encoder(proxy_image).flatten(2, 3) + vfm_feats=vfm_model.image_encoder(proxy_image) + vfm_feats=feat_out['qkv'].permute(0, 3, 1, 2).flatten(2, 3) # [1, 768, 4096] + vfm_feats= F.normalize(vfm_feats, dim=1) + vfm_similarity = torch.einsum("b c m, b c n -> b m n", vfm_feats, vfm_feats) + else: + feat = vfm_model.get_intermediate_layers(proxy_image)[0] + nb_im = feat.shape[0] + patch_size = vfm_model.patch_embed.patch_size + I, J = proxy_image[0].shape[-2] // patch_size, proxy_image[0].shape[-2] // patch_size + vfm_feats = feat[:, 1:, :].reshape(nb_im, I, J, -1).permute(0, 3, 1, 2) + if args.proxy: + if student.mode=="ss_vfm_distill": + student_roi_features, extra_feats=student(images,rois_list) # num_patch,C bs,C,H,W + extra_feats = F.normalize(extra_feats, dim=-1).transpose(-2,-1) + extra_feats_similarity=torch.einsum("b c m, b c n -> b m n", extra_feats, extra_feats) + _loss_loc_cosine=(vfm_similarity - extra_feats_similarity).norm(p=2,dim=-1).mean() + losses.update({"loss_loc_cosine":_loss_loc_cosine*0.05}) + else: + student_roi_features, q_feature, k_feature = student(images,rois_list) # num_patch,C bs,C,H,W + q_feature = F.normalize(q_feature, dim=-1).transpose(-2,-1) + k_feature = F.normalize(k_feature, dim=-1).transpose(-2,-1) + qk_feats_similarity=torch.einsum("b c m, b c n -> b m n", q_feature, k_feature) + _loss_loc_cosine=(vfm_similarity - qk_feats_similarity).norm(p=2,dim=-1).mean() + losses.update({"loss_loc_cosine":_loss_loc_cosine*0.05}) + else: + student_roi_features = student.encode_pseudo_boxes(images, + rois_list, + normalize=True, + extract_type=args.extract_type, + mode="ss", # "ss", "only_v","maskclip","sclip","ss_vfm_distill" + ex_feats=None) + _loss_cosine = 1.0 - (student_roi_features * teacher_crop_features).sum(-1).mean() + losses.update({"loss_clip_cosine":_loss_cosine*2.0}) + return losses, len(images), student.logit_scale.exp() \ No newline at end of file diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/training/coco_api.py b/downstream/ProxyCLIP_TPAMI/clipself/src/training/coco_api.py new file mode 100644 index 0000000000000000000000000000000000000000..40f7f2c9b930de3dadd967db9d131913fc9bf54c --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/training/coco_api.py @@ -0,0 +1,137 @@ +# Copyright (c) OpenMMLab. All rights reserved. +# This file add snake case alias for coco api + +import warnings +from collections import defaultdict +from typing import List, Optional, Union + +import pycocotools +from pycocotools.coco import COCO as _COCO +from pycocotools.cocoeval import COCOeval as _COCOeval + + +class COCO(_COCO): + """This class is almost the same as official pycocotools package. + + It implements some snake case function aliases. So that the COCO class has + the same interface as LVIS class. + """ + + def __init__(self, annotation_file=None): + if getattr(pycocotools, '__version__', '0') >= '12.0.2': + warnings.warn( + 'mmpycocotools is deprecated. Please install official pycocotools by "pip install pycocotools"', # noqa: E501 + UserWarning) + super().__init__(annotation_file=annotation_file) + self.img_ann_map = self.imgToAnns + self.cat_img_map = self.catToImgs + + def get_ann_ids(self, img_ids=[], cat_ids=[], area_rng=[], iscrowd=None): + return self.getAnnIds(img_ids, cat_ids, area_rng, iscrowd) + + def get_cat_ids(self, cat_names=[], sup_names=[], cat_ids=[]): + return self.getCatIds(cat_names, sup_names, cat_ids) + + def get_img_ids(self, img_ids=[], cat_ids=[]): + return self.getImgIds(img_ids, cat_ids) + + def load_anns(self, ids): + return self.loadAnns(ids) + + def load_cats(self, ids): + return self.loadCats(ids) + + def load_imgs(self, ids): + return self.loadImgs(ids) + + +# just for the ease of import +COCOeval = _COCOeval + + +class COCOPanoptic(COCO): + """This wrapper is for loading the panoptic style annotation file. + + The format is shown in the CocoPanopticDataset class. + + Args: + annotation_file (str, optional): Path of annotation file. + Defaults to None. + """ + + def __init__(self, annotation_file: Optional[str] = None) -> None: + super(COCOPanoptic, self).__init__(annotation_file) + + def createIndex(self) -> None: + """Create index.""" + # create index + print('creating index...') + # anns stores 'segment_id -> annotation' + anns, cats, imgs = {}, {}, {} + img_to_anns, cat_to_imgs = defaultdict(list), defaultdict(list) + if 'annotations' in self.dataset: + for ann in self.dataset['annotations']: + for seg_ann in ann['segments_info']: + # to match with instance.json + seg_ann['image_id'] = ann['image_id'] + img_to_anns[ann['image_id']].append(seg_ann) + # segment_id is not unique in coco dataset orz... + # annotations from different images but + # may have same segment_id + if seg_ann['id'] in anns.keys(): + anns[seg_ann['id']].append(seg_ann) + else: + anns[seg_ann['id']] = [seg_ann] + + # filter out annotations from other images + img_to_anns_ = defaultdict(list) + for k, v in img_to_anns.items(): + img_to_anns_[k] = [x for x in v if x['image_id'] == k] + img_to_anns = img_to_anns_ + + if 'images' in self.dataset: + for img_info in self.dataset['images']: + img_info['segm_file'] = img_info['file_name'].replace( + 'jpg', 'png') + imgs[img_info['id']] = img_info + + if 'categories' in self.dataset: + for cat in self.dataset['categories']: + cats[cat['id']] = cat + + if 'annotations' in self.dataset and 'categories' in self.dataset: + for ann in self.dataset['annotations']: + for seg_ann in ann['segments_info']: + cat_to_imgs[seg_ann['category_id']].append(ann['image_id']) + + print('index created!') + + self.anns = anns + self.imgToAnns = img_to_anns + self.catToImgs = cat_to_imgs + self.imgs = imgs + self.cats = cats + + def load_anns(self, + ids: Union[List[int], int] = []) -> Optional[List[dict]]: + """Load anns with the specified ids. + + ``self.anns`` is a list of annotation lists instead of a + list of annotations. + + Args: + ids (Union[List[int], int]): Integer ids specifying anns. + + Returns: + anns (List[dict], optional): Loaded ann objects. + """ + anns = [] + + if hasattr(ids, '__iter__') and hasattr(ids, '__len__'): + # self.anns is a list of annotation lists instead of + # a list of annotations + for id in ids: + anns += self.anns[id] + return anns + elif type(ids) == int: + return self.anns[ids] diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/training/custom_transforms.py b/downstream/ProxyCLIP_TPAMI/clipself/src/training/custom_transforms.py new file mode 100644 index 0000000000000000000000000000000000000000..9c828dc0af5935132c2e8b4a7b065d0b78e1fe2e --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/training/custom_transforms.py @@ -0,0 +1,44 @@ +import random +import torch +import torch.nn as nn +import torchvision.transforms.functional as F +from torchvision.transforms import RandomCrop, InterpolationMode + + +class CustomRandomResize(nn.Module): + + def __init__(self, scale=(0.5, 2.0), interpolation=InterpolationMode.BILINEAR): + super().__init__() + self.min_scale, self.max_scale = min(scale), max(scale) + self.interpolation = interpolation + + def forward(self, img): + if isinstance(img, torch.Tensor): + height, width = img.shape[:2] + else: + width, height = img.size + scale = random.uniform(self.min_scale, self.max_scale) + new_size = [int(height * scale), int(width * scale)] + img = F.resize(img, new_size, self.interpolation) + + return img + + +class CustomRandomCrop(RandomCrop): + def forward(self, img): + """ + Args: + img (PIL Image or Tensor): Image to be cropped. + + Returns: + PIL Image or Tensor: Cropped image. + """ + + width, height = F.get_image_size(img) + tar_h, tar_w = self.size + + tar_h = min(tar_h, height) + tar_w = min(tar_w, width) + i, j, h, w = self.get_params(img, (tar_h, tar_w)) + + return F.crop(img, i, j, h, w) diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/training/data.py b/downstream/ProxyCLIP_TPAMI/clipself/src/training/data.py new file mode 100644 index 0000000000000000000000000000000000000000..bdd4844f5f2e027b8039488dfa6dec7182007305 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/training/data.py @@ -0,0 +1,877 @@ +import json +import logging +import os +import random +from dataclasses import dataclass +from multiprocessing import Value +import numpy as np +from training.misc import get_tokenizer +from training.utils import mask2box +import torch +from PIL import Image +from torch.utils.data import Dataset, DataLoader +from torch.utils.data.distributed import DistributedSampler +from open_clip.transform import ResizeMaxSize, _convert_to_rgb, det_image_transform, get_scale +from pycocotools.coco import COCO +from training.coco_api import COCOPanoptic +from panopticapi import utils +# import mmcv +import io +# from mmengine.fileio import get +try: + from petrel_client.client import Client +except: + Client = None +from open_clip.transform import ResizeLongest + +# import image transforms +from torchvision.transforms import RandomHorizontalFlip, Compose,Normalize,ToTensor +from training.custom_transforms import CustomRandomResize, CustomRandomCrop + + + +class ProposalDistillDataset(Dataset): + def __init__(self, input_filename, transforms, image_root, + crop_size=224, + tokenizer=None, args=None): + logging.debug(f'Loading coco style data from {input_filename}.') + self.coco = COCO(input_filename) + logging.debug('Done loading data.') + self.transforms = transforms + self.tokenize = tokenizer + self.image_root = image_root + self.image_ids = list(self.coco.imgs.keys()) + self.max_anns = 20 + if not isinstance(crop_size, (tuple, list)): + crop_size = [crop_size, crop_size] + self.crop_size = crop_size + self.args = args + self.min_size = args.min_size + self.max_size = args.max_size + self.ceph_root = args.train_ceph_root + self.use_ceph = (self.ceph_root != "") + self.FILE_CLIENT = None + + def read_image(self, image_name): + if self.use_ceph: + image_path = os.path.join(self.ceph_root, image_name) + if self.FILE_CLIENT is None: + self.FILE_CLIENT = Client() + try: + img_bytes = self.FILE_CLIENT.get(image_path) + buff = io.BytesIO(img_bytes) + image = Image.open(buff) + except: + print(f"Cannot load {image_path}", flush=True) + return None + else: + image_path = os.path.join(self.image_root, image_name) + try: + image = Image.open(image_path) + except: + print(f"Cannot load {image_path}", flush=True) + return None + + width, height = image.size + if width < 10 or height < 10: + print(f"Invalid image, size {image.size}", flush=True) + return None + + return image + + def __len__(self): + return len(self.image_ids) + + def __getitem__(self, idx): + image_id = self.image_ids[idx] + image_info = self.coco.imgs[image_id] + if 'file_name' in image_info: + image_name = image_info['file_name'] + else: + assert 'coco_url' in image_info + coco_url = image_info['coco_url'].split('/') + image_name = os.path.join(coco_url[-2], coco_url[-1]) + + old_image = self.read_image(image_name) + if old_image is None: + next_id = random.choice(range(self.__len__())) + return self.__getitem__(next_id) + img_w, img_h = old_image.width, old_image.height + new_image = self.transforms[0](old_image) + scale = get_scale(old_image, new_image) + anns = self.coco.imgToAnns[image_id] + boxes_template = torch.zeros(self.max_anns, 4 + 1) # xyxy s + texts=[] + image_crops = torch.zeros(self.max_anns, 3, *self.crop_size) + indices = list(range(len(anns))) + random.shuffle(indices) + num_valid_boxes = 0 + for i, ann_id in enumerate(indices[:self.max_anns]): + ann = anns[ann_id] + x, y, w, h = ann['bbox'] + if w*h < (self.min_size ** 2) or w*h > (self.max_size ** 2): + continue + num_valid_boxes += 1 + cx, cy = x + w*0.5, y + h*0.5 + x0, y0, x1, y1 = \ + max(cx - w*0.75, 0), max(cy - h*0.75, 0), min(cx + w*0.75, img_w), min(cy + h*0.75, img_h) + image_crops[i] = self.transforms[1](old_image.crop((x0, y0, x1, y1))) # image crops + box_info = torch.tensor([x, y, x + w, y + h, 1.0]) # x, y, x + w, y + h + boxes_template[i] = box_info + + if num_valid_boxes == 0: + boxes_template[0] = torch.tensor([0, 0, img_w / 4, img_h / 4, 1.0]) # avoid empty + image_crops[0] = self.transforms[1](old_image.crop((0, 0, img_w // 4, img_h // 4))) + + _, h, w = new_image.shape + + boxes_template[:, :4] *= scale + boxes_template[:, [0, 2]] /= w + boxes_template[:, [1, 3]] /= h + return new_image, boxes_template, image_crops + +class FrosterDataset(Dataset): + # mix of ProposalDistillDataset and COCORegionCLIPDataset + def __init__(self, input_filename, transforms, image_root, crop_size=224, + tokenizer=None, args=None): + logging.debug(f'Loading coco style data from {input_filename}.') + self.coco = COCO(input_filename) + logging.debug('Done loading data.') + self.transforms = transforms + self.tokenize = tokenizer + self.image_root = image_root + self.image_ids = list(self.coco.imgs.keys()) + self.max_anns = 20 + if not isinstance(crop_size, (tuple, list)): + crop_size = [crop_size, crop_size] + self.crop_size = crop_size + self.args = args + self.min_size = args.min_size + self.max_size = args.max_size + self.ceph_root = args.train_ceph_root + self.use_ceph = (self.ceph_root != "") + self.FILE_CLIENT = None + cat_ids = sorted([cat['id'] for cat in self.coco.cats.values()]) + self.cat_id2label = {cat_id: label for label, cat_id in enumerate(cat_ids)} + + def read_image(self, image_name): + if self.use_ceph: + image_path = os.path.join(self.ceph_root, image_name) + if self.FILE_CLIENT is None: + self.FILE_CLIENT = Client() + try: + img_bytes = self.FILE_CLIENT.get(image_path) + buff = io.BytesIO(img_bytes) + image = Image.open(buff) + except: + print(f"Cannot load {image_path}", flush=True) + return None + else: + image_path = os.path.join(self.image_root, image_name) + try: + image = Image.open(image_path) + except: + print(f"Cannot load {image_path}", flush=True) + return None + + width, height = image.size + if width < 10 or height < 10: + print(f"Invalid image, size {image.size}", flush=True) + return None + + return image + + def __len__(self): + return len(self.image_ids) + + def __getitem__(self, idx): + image_id = self.image_ids[idx] + image_info = self.coco.imgs[image_id] + if 'file_name' in image_info: + image_name = image_info['file_name'] + else: + assert 'coco_url' in image_info + coco_url = image_info['coco_url'].split('/') + image_name = os.path.join(coco_url[-2], coco_url[-1]) + + old_image = self.read_image(image_name) + if old_image is None: + next_id = random.choice(range(self.__len__())) + return self.__getitem__(next_id) + img_w, img_h = old_image.width, old_image.height + new_image = self.transforms[0](old_image) + scale = get_scale(old_image, new_image) + anns = self.coco.imgToAnns[image_id] + boxes_template = torch.zeros(self.max_anns, 4 + 2) # xyxy,cls, s + image_crops = torch.zeros(self.max_anns, 3, *self.crop_size) + indices = list(range(len(anns))) + random.shuffle(indices) + num_valid_boxes = 0 + for i, ann_id in enumerate(indices[:self.max_anns]): + ann = anns[ann_id] + cat_id = ann['category_id'] + cls_label = self.cat_id2label[cat_id] + x, y, w, h = ann['bbox'] + if w*h < (self.min_size ** 2) or w*h > (self.max_size ** 2): + continue + num_valid_boxes += 1 + cx, cy = x + w*0.5, y + h*0.5 + x0, y0, x1, y1 = \ + max(cx - w*0.75, 0), max(cy - h*0.75, 0), min(cx + w*0.75, img_w), min(cy + h*0.75, img_h) + image_crops[i] = self.transforms[1](old_image.crop((x0, y0, x1, y1))) # image crops + box_info = torch.tensor([x, y, x + w, y + h, cls_label, 1.0]) # x, y, x + w, y + h + boxes_template[i] = box_info + + if num_valid_boxes == 0: + boxes_template[0] = torch.tensor([0, 0, img_w / 4, img_h / 4, -1, 1.0]) # avoid empty + image_crops[0] = self.transforms[1](old_image.crop((0, 0, img_w // 4, img_h // 4))) + + _, h, w = new_image.shape + + boxes_template[:, :4] *= scale + boxes_template[:, [0, 2]] /= w + boxes_template[:, [1, 3]] /= h + return new_image, boxes_template, image_crops + + +class GridDistillDataset(Dataset): + def __init__(self, + input_filename, transforms, image_root, + max_split=16, + crop_size=224, + pre_transforms=False, + ceph_root="", + args=None): + self._init_choices(max_split) + logging.debug(f'Loading coco caption style data from {input_filename}.') + self.coco = COCO(input_filename) + logging.debug('Done loading data.') + self.transforms = transforms + self.image_root = image_root + self.args = args + image_ids = list(self.coco.imgs.keys()) + train_ratio = args.train_ratio + if train_ratio < 1.0: + num_images = int(len(image_ids) * train_ratio) + random.shuffle(image_ids) + image_ids = image_ids[:num_images] + self.image_ids = image_ids + self.max_anns = args.max_boxes + if not isinstance(crop_size, (tuple, list)): + crop_size = [crop_size, crop_size] + self.crop_size = crop_size + self._init_boxes() + self.ceph_root = ceph_root + self.use_ceph = (ceph_root != "") + self.FILE_CLIENT = None + if pre_transforms: + self.pre_transforms = Compose([ + CustomRandomResize(scale=(0.5, 2.0)), + CustomRandomCrop(size=self.transforms[0].transforms[0].max_size), + RandomHorizontalFlip()]) + else: + self.pre_transforms = None + self.proxy_transform = det_image_transform( + 224 if args.proxy=="dino" else 1024, + is_train=False, + mean=[0.485, 0.456, 0.406], + std=[0.229, 0.224, 0.225], + ) + + def read_image(self, image_name): + if self.use_ceph: + image_path = os.path.join(self.ceph_root, image_name) + if self.FILE_CLIENT is None: + self.FILE_CLIENT = Client() + try: + img_bytes = self.FILE_CLIENT.get(image_path) + buff = io.BytesIO(img_bytes) + image = Image.open(buff) + except: + print(f"Cannot load {image_path}", flush=True) + return None + else: + image_path = os.path.join(self.image_root, image_name) + try: + image = Image.open(image_path) + except: + print(f"Cannot load {image_path}", flush=True) + return None + + width, height = image.size + if width < 10 or height < 10: + print(f"Invalid image, size {image.size}", flush=True) + return None + + return image + + def _init_choices(self, M=16): + choices = [] + for m in range(1, M+1): + for n in range((m + 1)//2, min(m*2 + 1, M+1)): + choices.append((m, n)) + self.choices = choices + + def __len__(self): + return len(self.image_ids) + + def _init_boxes(self, ): + box_templates = {} + for choice in self.choices: + M, N = choice + grid_x, grid_y = torch.meshgrid(torch.linspace(0, 1, N + 1), torch.linspace(0, 1, M + 1), + indexing='xy') + x0y0s = torch.stack([grid_x[:M, :N], grid_y[:M, :N]], dim=-1) + x1y1s = torch.stack([grid_x[1:, 1:], grid_y[1:, 1:]], dim=-1) + pseudo_boxes = torch.cat([x0y0s, x1y1s],dim=-1).view(-1, 4) + + assert pseudo_boxes.shape[0] == M*N + box_templates[choice] = pseudo_boxes + + self.box_templates = box_templates + + def _obtain_image_crops(self, image, choice): + image_crops = [] + img_w, img_h = image.size + normed_boxes = self.box_templates[choice] + indices = list(range(len(normed_boxes))) + random.shuffle(indices) + indices = indices[:self.max_anns] + boxes = normed_boxes * torch.tensor([img_w, img_h, img_w, img_h]) + for idx in indices: + box = boxes[idx] + x0, y0, x1, y1 = box.tolist() # todo expand + if self.args.crop_scale > 1.0: + box_w, box_h = x1 - x0, y1 - y0 + cx, cy = (x1 + x0)/2, (y1 + y0)/2 + delta_factor = 0.5 * self.args.crop_scale + x0, y0, x1, y1 = max(cx - box_w * delta_factor, 0), max(cy - box_h * delta_factor, 0), \ + min(cx + box_w * delta_factor, img_w), min(cy + box_h * delta_factor, img_h) + vanilla_view=self.transforms[1](image.crop((x0, y0, x1, y1))) + image_crops.append(vanilla_view) + return torch.stack(image_crops), boxes[indices] + + def _load_target(self, id: int): + return self.coco.loadAnns(self.coco.getAnnIds(id)) + + def __getitem__(self, idx): + image_id = self.image_ids[idx] + image_info = self.coco.imgs[image_id] + if 'file_name' in image_info: + image_name = image_info['file_name'] + else: + assert 'coco_url' in image_info + coco_url = image_info['coco_url'].split('/') + image_name = os.path.join(coco_url[-2], coco_url[-1]) + # image_path = os.path.join(self.image_root, image_name) + # old_image = Image.open(image_path) + old_image = self.read_image(image_name) + proxy_image=self.proxy_transform(old_image) + if old_image is None: + next_id = random.choice(range(self.__len__())) + return self.__getitem__(next_id) + new_image = self.transforms[0](old_image) + scale = get_scale(old_image, new_image) + boxes_template = torch.zeros(self.max_anns, 4 + 1) + image_crops_template = torch.zeros(self.max_anns, 3, *self.crop_size) + image_crops, boxes = self._obtain_image_crops(old_image,random.choice(self.choices)) + assert image_crops.shape[0] == boxes.shape[0] + _, h, w = new_image.shape + boxes[:, :4] *= scale + boxes[:, [0, 2]] /= w + boxes[:, [1, 3]] /= h + boxes_template[:boxes.shape[0], :4] = boxes + boxes_template[:boxes.shape[0], 4] = 1.0 + image_crops_template[:boxes.shape[0]] = image_crops + return new_image, boxes_template, image_crops_template, proxy_image + + +class COCOPanopticDataset(Dataset): + def __init__(self, input_filename, transforms, image_root, embed_path, + segm_root, + crop_size=224, + tokenizer=None, + downsample_factor=16, + min_size=8, + max_size=1024, + args=None): + logging.debug(f'Loading coco caption style data from {input_filename}.') + self.coco = COCOPanoptic(input_filename) + logging.debug('Done loading data.') + self.transforms = transforms + self.tokenize = tokenizer + self.image_root = image_root + self.embeddings = np.load(embed_path) + self.image_ids = list(self.coco.imgs.keys()) + num_annos = [len(anns) for anns in self.coco.imgToAnns.values()] + self.max_anns = min(max(num_annos), 100) + if not isinstance(crop_size, (tuple, list)): + crop_size = [crop_size, crop_size] + self.crop_size = crop_size + self.min_size = 8 # fix for val + self.max_size = 1024 + self.segm_root = segm_root + self.downsample_factor = downsample_factor + self.segm_transform = ResizeLongest(max_size=self.transforms[0].transforms[0].max_size // downsample_factor, + fill=0) # downsample to the output size of image encoder + self.args=args + cat_ids = sorted([cat['id'] for cat in self.coco.cats.values()]) + self.cat_id2label = {cat_id: label for label, cat_id in enumerate(cat_ids)} + self.label2cat_id = {label: cat_id for cat_id, label in self.cat_id2label.items()} + self.proxy_transform = det_image_transform( + 224 if args.proxy=="dino" else 1024, + is_train=False, + mean=[0.485, 0.456, 0.406], + std=[0.229, 0.224, 0.225], + ) + def __len__(self): + return len(self.image_ids) + + @staticmethod + def _load_segm(segm_path): + segmentation = np.array( + Image.open(segm_path), + dtype=np.uint8 + ) + # img_bytes = get(segm_path) + # pan_png = mmcv.imfrombytes( + # img_bytes, flag='color', channel_order='rgb').squeeze() + segm_map = utils.rgb2id(segmentation) + + return segm_map + + def __getitem__(self, idx): + image_id = self.image_ids[idx] + image_info = self.coco.imgs[image_id] + image_name = image_info['file_name'] + segm_file = image_info['segm_file'] + image_path = os.path.join(self.image_root, image_name) + segm_path = os.path.join(self.segm_root, segm_file) + segm_map = self._load_segm(segm_path) + + old_image = Image.open(image_path) + img_w, img_h = old_image.width, old_image.height + new_image = self.transforms[0](old_image) + proxy_image=self.proxy_transform(old_image) + scale = get_scale(old_image, new_image) + anns = self.coco.imgToAnns[image_id] + boxes_template = torch.zeros(self.max_anns, 4 + 2 + 1 + 1) # xyxy c valid size, isthing + image_crops = torch.zeros(self.max_anns, 3, *self.crop_size) + gt_masks = torch.zeros(self.max_anns, self.segm_transform.max_size,self.segm_transform.max_size) + masked_image_crops = torch.zeros(self.max_anns, 3, *self.crop_size) + for i, ann in enumerate(anns): + if i == self.max_anns: + break + cat_id = ann['category_id'] + is_thing = self.coco.cats[cat_id]['isthing'] + if is_thing > 0: + x, y, w, h = ann['bbox'] + cx, cy = x + w*0.5, y + h*0.5 + x0, y0, x1, y1 = \ + max(cx - w*0.75, 0), max(cy - h*0.75, 0), min(cx + w*0.75, img_w), min(cy + h*0.75, img_h) + else: + x0, y0, x1, y1 = mask2box(segm_map == ann['id']) + x, y, w, h = x0, y0, x1 - x0, y1 - y0 + if w * h < (self.min_size ** 2) or w * h > (self.max_size ** 2): + continue + image_crops[i] = self.transforms[1](old_image.crop((x0, y0, x1, y1))) # image crops + # masked image crop + np_old_image = np.asarray(old_image.copy()) + np_old_image[segm_map != ann['id']] = 114 + masked_old_image = Image.fromarray(np_old_image) + masked_image_crops[i] = self.transforms[1](masked_old_image.crop((x0, y0, x1, y1))) # image crops + + gt_mask = torch.from_numpy(segm_map == ann['id']).float() + gt_mask = self.segm_transform(gt_mask[None]) > 0.0 + cls_label = self.cat_id2label[cat_id] + box_info = torch.tensor([x, y, x + w, y + h, cls_label, 1.0, w * h, is_thing]) # x, y, x + w, y + h + boxes_template[i] = box_info + gt_masks[i] = gt_mask[0] + _, h, w = new_image.shape + + boxes_template[:, :4] *= scale + boxes_template[:, [0, 2]] /= w + boxes_template[:, [1, 3]] /= h + + return image_name, new_image, boxes_template, image_crops, gt_masks, masked_image_crops, proxy_image + + +class COCORegionCLIPDataset(Dataset): + def __init__(self, input_filename, transforms, image_root, args): + logging.debug(f'Loading coco caption style data from {input_filename}.') + self.coco = COCO(input_filename) + logging.debug('Done loading data.') + self.transforms = transforms + self.image_root = image_root + image_ids = list(self.coco.imgToAnns.keys()) # only use images that have anns + train_ratio = args.train_ratio + if train_ratio < 1.0: + num_images = int(len(image_ids) * train_ratio) + random.shuffle(image_ids) + image_ids = image_ids[:num_images] + self.image_ids = image_ids + + num_annos = [len(anns) for anns in self.coco.imgToAnns.values()] + self.max_anns = min(max(num_annos), 20) + self.args = args + self.ceph_root = args.train_ceph_root + self.use_ceph = (self.ceph_root != "") + self.FILE_CLIENT = None + cat_ids = sorted([cat['id'] for cat in self.coco.cats.values()]) + + self.cat_id2label = {cat_id: label for label, cat_id in enumerate(cat_ids)} + + def __len__(self): + return len(self.image_ids) + + def read_image(self, image_name): + if self.use_ceph: + image_path = os.path.join(self.ceph_root, image_name) + if self.FILE_CLIENT is None: + self.FILE_CLIENT = Client() + img_bytes = self.FILE_CLIENT.get(image_path) + buff = io.BytesIO(img_bytes) + image = Image.open(buff) + else: + image_path = os.path.join(self.image_root, image_name) + image = Image.open(image_path) + return image + + def __getitem__(self, idx): + image_id = self.image_ids[idx] + image_info = self.coco.imgs[image_id] + image_name = image_info['file_name'] + # image_path = os.path.join(self.image_root, image_name) + # old_image = Image.open(image_path) + old_image = self.read_image(image_name) + new_image = self.transforms[0](old_image) + + scale = get_scale(old_image, new_image) + anns = self.coco.imgToAnns[image_id] + boxes_template = torch.zeros(self.max_anns, 4 + 2) # xyxy cls valid + + for i, ann in enumerate(anns): + if i == self.max_anns: + break + cat_id = ann['category_id'] + x, y, w, h = ann['bbox'] + cls_label = self.cat_id2label[cat_id] + box_info = torch.tensor([x, y, x + w, y + h, cls_label, 1.0]) # x, y, x + w, y + h + boxes_template[i] = box_info + + _, h, w = new_image.shape + + boxes_template[:, :4] *= scale + boxes_template[:, [0, 2]] /= w + boxes_template[:, [1, 3]] /= h + + return new_image, boxes_template + + +class COCOCaptionDataset(Dataset): + def __init__(self, input_filename, transforms, image_root, + tokenizer=None, args=None): + logging.debug(f'Loading coco caption style data from {input_filename}.') + with open(input_filename, 'r') as f: + self.images = json.load(f)['images'] + logging.debug('Done loading data.') + self.transforms = transforms + self.tokenize = get_tokenizer(args.model) + self.image_root = image_root + self.ceph_root = args.train_ceph_root + self.use_ceph = (self.ceph_root != "") + self.FILE_CLIENT = None + + def read_image(self, image_name): + if self.use_ceph: + image_path = os.path.join(self.ceph_root, image_name) + if self.FILE_CLIENT is None: + self.FILE_CLIENT = Client() + try: + img_bytes = self.FILE_CLIENT.get(image_path) + buff = io.BytesIO(img_bytes) + image = Image.open(buff) + except: + print(f"Cannot load {image_path}", flush=True) + return None + else: + image_path = os.path.join(self.image_root, image_name) + try: + image = Image.open(image_path) + except: + print(f"Cannot load {image_path}", flush=True) + return None + + width, height = image.size + if width < 10 or height < 10: + print(f"Invalid image, size {image.size}", flush=True) + return None + + return image + + def __len__(self): + return len(self.images) + + def __getitem__(self, idx): + image_info = self.images[idx] + text = random.choice(image_info['captions']) + image_name = image_info['file_name'] + image = self.read_image(image_name) + if image is None: + next_id = random.choice(range(self.__len__())) + return self.__getitem__(next_id) + image = self.transforms(image) + text = self.tokenize([text])[0] + return image, text + + +def get_coco_panoptic_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 = COCOPanopticDataset( + input_filename, + preprocess_fn, + segm_root=args.val_segm_root, + image_root=args.val_image_root, + embed_path=args.embed_path, + tokenizer=tokenizer, + crop_size=224 if args.model=="EVA02-CLIP-B-16" else 336, + min_size=args.min_size, + max_size=args.max_size, + downsample_factor=args.downsample_factor, + args=args, + ) + num_samples = len(dataset) + # TODO: distributed for test + sampler = DistributedSampler(dataset) if args.distributed else None # and is_train else None + shuffle = is_train and sampler is None + if is_train: + batch_size = args.batch_size + else: + batch_size = min(args.batch_size, 1) # only support bs = 1 for inference + dataloader = DataLoader( + dataset, + batch_size=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_proposal_distill_dataset(args, preprocess_fn, is_train, epoch=0, tokenizer=None): + assert is_train + input_filename = args.train_data # if is_train else args.val_data + assert input_filename + dataset = ProposalDistillDataset( + input_filename, + preprocess_fn, + image_root=args.train_image_root, + tokenizer=tokenizer, + crop_size=args.input_size, + args=args + ) + num_samples = len(dataset) + # TODO: distributed for test + sampler = DistributedSampler(dataset) if args.distributed else None # and is_train else None + shuffle = is_train and sampler is None + batch_size = args.batch_size + dataloader = DataLoader( + dataset, + batch_size=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_grid_distill_dataset(args, preprocess_fn, is_train, epoch=0, tokenizer=None): + assert is_train + input_filename = args.train_data + assert input_filename + dataset = GridDistillDataset( + input_filename=input_filename, + transforms=preprocess_fn, + image_root=args.train_image_root, + crop_size=args.input_size, + max_split=args.max_split, + ceph_root=args.train_ceph_root, + pre_transforms=args.pre_transforms, + args=args + ) + num_samples = len(dataset) + # TODO: distributed for test + sampler = DistributedSampler(dataset) if args.distributed else None # and is_train else None + shuffle = is_train and sampler is None + batch_size = args.batch_size + dataloader = DataLoader( + dataset, + batch_size=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_region_clip_dataset(args, preprocess_fn, is_train, epoch=0, tokenizer=None): + assert is_train + input_filename = args.train_data + assert input_filename + dataset = COCORegionCLIPDataset( + input_filename=input_filename, + transforms=preprocess_fn, + image_root=args.train_image_root, + args=args, + ) + num_samples = len(dataset) + # TODO: distributed for test + sampler = DistributedSampler(dataset) if args.distributed else None # and is_train else None + shuffle = is_train and sampler is None + batch_size = args.batch_size + dataloader = DataLoader( + dataset, + batch_size=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_froster_dataset(args, preprocess_fn, is_train, epoch=0, tokenizer=None): + assert is_train + input_filename = args.train_data # if is_train else args.val_data + assert input_filename + dataset = FrosterDataset( + input_filename, + preprocess_fn, + image_root=args.train_image_root, + tokenizer=tokenizer, + crop_size=args.input_size, + args=args + ) + num_samples = len(dataset) + # TODO: distributed for test + sampler = DistributedSampler(dataset) if args.distributed else None # and is_train else None + shuffle = is_train and sampler is None + batch_size = args.batch_size + dataloader = DataLoader( + dataset, + batch_size=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_coco_caption_dataset(args, preprocess_fn, is_train, epoch=0, tokenizer=None): + assert is_train + input_filename = args.train_data + assert input_filename + dataset = COCOCaptionDataset( + input_filename, + preprocess_fn, + image_root=args.train_image_root, + tokenizer=tokenizer, + args=args + ) + 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 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 get_dataset_fn(data_path, dataset_type): + if dataset_type == 'coco_panoptic': + return get_coco_panoptic_dataset + elif dataset_type == 'proposals_distill': + return get_proposal_distill_dataset + elif dataset_type == 'grid_distill': + return get_grid_distill_dataset + elif dataset_type == 'region_clip': + return get_region_clip_dataset + elif dataset_type == 'coco_caption': + return get_coco_caption_dataset + elif dataset_type == 'froster': + return get_froster_dataset + 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: + 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, dataset_type=args.test_type)( + args, preprocess_val, is_train=False, tokenizer=tokenizer) + + return data \ No newline at end of file diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/training/dist_utils.py b/downstream/ProxyCLIP_TPAMI/clipself/src/training/dist_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..1d229214372df339d23621ad8838c813578d093d --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/training/dist_utils.py @@ -0,0 +1,228 @@ +# Copyright (c) Facebook, Inc. and its affiliates. +""" +This file contains primitives for multi-gpu communication. +This is useful when doing distributed training. +""" + +import functools +import numpy as np +import torch +import torch.distributed as dist + +_LOCAL_PROCESS_GROUP = None +_MISSING_LOCAL_PG_ERROR = ( + "Local process group is not yet created! Please use detectron2's `launch()` " + "to start processes and initialize pytorch process group. If you need to start " + "processes in other ways, please call comm.create_local_process_group(" + "num_workers_per_machine) after calling torch.distributed.init_process_group()." +) + + +def get_world_size() -> int: + if not dist.is_available(): + return 1 + if not dist.is_initialized(): + return 1 + return dist.get_world_size() + + +def get_rank() -> int: + if not dist.is_available(): + return 0 + if not dist.is_initialized(): + return 0 + return dist.get_rank() + + +@functools.lru_cache() +def create_local_process_group(num_workers_per_machine: int) -> None: + """ + Create a process group that contains ranks within the same machine. + Detectron2's launch() in engine/launch.py will call this function. If you start + workers without launch(), you'll have to also call this. Otherwise utilities + like `get_local_rank()` will not work. + This function contains a barrier. All processes must call it together. + Args: + num_workers_per_machine: the number of worker processes per machine. Typically + the number of GPUs. + """ + global _LOCAL_PROCESS_GROUP + assert _LOCAL_PROCESS_GROUP is None + assert get_world_size() % num_workers_per_machine == 0 + num_machines = get_world_size() // num_workers_per_machine + machine_rank = get_rank() // num_workers_per_machine + for i in range(num_machines): + ranks_on_i = list(range(i * num_workers_per_machine, (i + 1) * num_workers_per_machine)) + pg = dist.new_group(ranks_on_i) + if i == machine_rank: + _LOCAL_PROCESS_GROUP = pg + + +def get_local_process_group(): + """ + Returns: + A torch process group which only includes processes that are on the same + machine as the current process. This group can be useful for communication + within a machine, e.g. a per-machine SyncBN. + """ + assert _LOCAL_PROCESS_GROUP is not None, _MISSING_LOCAL_PG_ERROR + return _LOCAL_PROCESS_GROUP + + +def get_local_rank() -> int: + """ + Returns: + The rank of the current process within the local (per-machine) process group. + """ + if not dist.is_available(): + return 0 + if not dist.is_initialized(): + return 0 + assert _LOCAL_PROCESS_GROUP is not None, _MISSING_LOCAL_PG_ERROR + return dist.get_rank(group=_LOCAL_PROCESS_GROUP) + + +def get_local_size() -> int: + """ + Returns: + The size of the per-machine process group, + i.e. the number of processes per machine. + """ + if not dist.is_available(): + return 1 + if not dist.is_initialized(): + return 1 + assert _LOCAL_PROCESS_GROUP is not None, _MISSING_LOCAL_PG_ERROR + return dist.get_world_size(group=_LOCAL_PROCESS_GROUP) + + +def is_main_process() -> bool: + return get_rank() == 0 + + +def synchronize(): + """ + Helper function to synchronize (barrier) among all processes when + using distributed training + """ + if not dist.is_available(): + return + if not dist.is_initialized(): + return + world_size = dist.get_world_size() + if world_size == 1: + return + if dist.get_backend() == dist.Backend.NCCL: + # This argument is needed to avoid warnings. + # It's valid only for NCCL backend. + dist.barrier(device_ids=[torch.cuda.current_device()]) + else: + dist.barrier() + + +@functools.lru_cache() +def _get_global_gloo_group(): + """ + Return a process group based on gloo backend, containing all the ranks + The result is cached. + """ + if dist.get_backend() == "nccl": + return dist.new_group(backend="gloo") + else: + return dist.group.WORLD + + +def all_gather(data, group=None): + """ + Run all_gather on arbitrary picklable data (not necessarily tensors). + Args: + data: any picklable object + group: a torch process group. By default, will use a group which + contains all ranks on gloo backend. + Returns: + list[data]: list of data gathered from each rank + """ + if get_world_size() == 1: + return [data] + if group is None: + group = _get_global_gloo_group() # use CPU group by default, to reduce GPU RAM usage. + world_size = dist.get_world_size(group) + if world_size == 1: + return [data] + + output = [None for _ in range(world_size)] + dist.all_gather_object(output, data, group=group) + return output + + +def gather(data, dst=0, group=None): + """ + Run gather on arbitrary picklable data (not necessarily tensors). + Args: + data: any picklable object + dst (int): destination rank + group: a torch process group. By default, will use a group which + contains all ranks on gloo backend. + Returns: + list[data]: on dst, a list of data gathered from each rank. Otherwise, + an empty list. + """ + if get_world_size() == 1: + return [data] + if group is None: + group = _get_global_gloo_group() + world_size = dist.get_world_size(group=group) + if world_size == 1: + return [data] + rank = dist.get_rank(group=group) + + if rank == dst: + output = [None for _ in range(world_size)] + dist.gather_object(data, output, dst=dst, group=group) + return output + else: + dist.gather_object(data, None, dst=dst, group=group) + return [] + + +def shared_random_seed(): + """ + Returns: + int: a random number that is the same across all workers. + If workers need a shared RNG, they can use this shared seed to + create one. + All workers must call this function, otherwise it will deadlock. + """ + ints = np.random.randint(2**31) + all_ints = all_gather(ints) + return all_ints[0] + + +def reduce_dict(input_dict, average=True): + """ + Reduce the values in the dictionary from all processes so that process with rank + 0 has the reduced results. + Args: + input_dict (dict): inputs to be reduced. All the values must be scalar CUDA Tensor. + average (bool): whether to do average or sum + Returns: + a dict with the same keys as input_dict, after reduction. + """ + world_size = get_world_size() + if world_size < 2: + return input_dict + with torch.no_grad(): + names = [] + values = [] + # sort the keys so that they are consistent across processes + for k in sorted(input_dict.keys()): + names.append(k) + values.append(input_dict[k]) + values = torch.stack(values, dim=0) + dist.reduce(values, dst=0) + if dist.get_rank() == 0 and average: + # only main process gets accumulated, so only divide by + # world_size in this case + values /= world_size + reduced_dict = {k: v for k, v in zip(names, values)} + return reduced_dict diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/training/distributed.py b/downstream/ProxyCLIP_TPAMI/clipself/src/training/distributed.py new file mode 100644 index 0000000000000000000000000000000000000000..cb6e64a55c6d0e521b6154c8cdccf80f4dc68f7e --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/training/distributed.py @@ -0,0 +1,136 @@ +import os + +import torch +import torch.distributed as dist + +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(): + 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 + 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 + 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 + + 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 + + +def broadcast_object(args, obj, src=0): + # broadcast a pickle-able python object from rank-0 to all ranks + if args.horovod: + return hvd.broadcast_object(obj, root_rank=src) + else: + if args.rank == src: + objects = [obj] + else: + objects = [None] + dist.broadcast_object_list(objects, src=src) + return objects[0] + + +def all_gather_object(args, obj, dst=0): + # gather a pickle-able python object across all ranks + if args.horovod: + return hvd.allgather_object(obj) + else: + objects = [None for _ in range(args.world_size)] + dist.all_gather_object(objects, obj) + return objects diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/training/file_utils.py b/downstream/ProxyCLIP_TPAMI/clipself/src/training/file_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..395cf7df0acc164c6851f17834d793f5852d4605 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/training/file_utils.py @@ -0,0 +1,83 @@ +import logging +import os +import multiprocessing +import subprocess +import time +import fsspec +import torch +from tqdm import tqdm + +def remote_sync_s3(local_dir, remote_dir): + # skip epoch_latest which can change during sync. + result = subprocess.run(["aws", "s3", "sync", local_dir, remote_dir, '--exclude', '*epoch_latest.pt'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) + if result.returncode != 0: + logging.error(f"Error: Failed to sync with S3 bucket {result.stderr.decode('utf-8')}") + return False + + logging.info(f"Successfully synced with S3 bucket") + return True + +def remote_sync_fsspec(local_dir, remote_dir): + # FIXME currently this is slow and not recommended. Look into speeding up. + a = fsspec.get_mapper(local_dir) + b = fsspec.get_mapper(remote_dir) + + for k in a: + # skip epoch_latest which can change during sync. + if 'epoch_latest.pt' in k: + continue + + logging.info(f'Attempting to sync {k}') + if k in b and len(a[k]) == len(b[k]): + logging.debug(f'Skipping remote sync for {k}.') + continue + + try: + logging.info(f'Successful sync for {k}.') + b[k] = a[k] + except Exception as e: + logging.info(f'Error during remote sync for {k}: {e}') + return False + + return True + +def remote_sync(local_dir, remote_dir, protocol): + logging.info('Starting remote sync.') + if protocol == 's3': + return remote_sync_s3(local_dir, remote_dir) + elif protocol == 'fsspec': + return remote_sync_fsspec(local_dir, remote_dir) + else: + logging.error('Remote protocol not known') + return False + +def keep_running_remote_sync(sync_every, local_dir, remote_dir, protocol): + while True: + time.sleep(sync_every) + remote_sync(local_dir, remote_dir, protocol) + +def start_sync_process(sync_every, local_dir, remote_dir, protocol): + p = multiprocessing.Process(target=keep_running_remote_sync, args=(sync_every, local_dir, remote_dir, protocol)) + return p + +# Note: we are not currently using this save function. +def pt_save(pt_obj, file_path): + of = fsspec.open(file_path, "wb") + with of as f: + torch.save(pt_obj, file_path) + +def pt_load(file_path, map_location=None): + if file_path.startswith('s3'): + logging.info('Loading remote checkpoint, which may take a bit.') + of = fsspec.open(file_path, "rb") + with of as f: + out = torch.load(f, map_location=map_location) + return out + +def check_exists(file_path): + try: + with fsspec.open(file_path): + pass + except FileNotFoundError: + return False + return True diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/training/logger.py b/downstream/ProxyCLIP_TPAMI/clipself/src/training/logger.py new file mode 100644 index 0000000000000000000000000000000000000000..6d9abed92568d459cbc8d6094ae3901935d89621 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/training/logger.py @@ -0,0 +1,26 @@ +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/downstream/ProxyCLIP_TPAMI/clipself/src/training/main.py b/downstream/ProxyCLIP_TPAMI/clipself/src/training/main.py new file mode 100644 index 0000000000000000000000000000000000000000..56cc1c57d1440f999595b3eac29ebd87908b40f8 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/training/main.py @@ -0,0 +1,339 @@ +import glob +import logging +import os +import re +import subprocess +import sys +import random +from datetime import datetime + +from hubconf import maskclip +from open_clip.model import get_cast_dtype +from tools.k_means import run_kmeans +from tools.segmentation import run_seg +from training.clim import CLIM +from training.misc import CosineScheduler, is_main_process +from training.region_clip import RegionCLIP +from training.clipself import CLIPSelf, CLIPWithProjector, build_vfm +import numpy as np +import torch +from torch import optim +from torch.cuda.amp import GradScaler +from clipself.src.open_clip import create_model_and_transforms, get_tokenizer, create_model +from training.data import get_data +from training.distributed import is_master, init_distributed_device, broadcast_object +from training.logger import setup_logging +from training.params import parse_args +from training.scheduler import cosine_lr, const_lr, const_lr_cooldown +from training.train import train_one_epoch, evaluate, student_teacher_ensemble +from training.file_utils import pt_load +from .utils import ViTB_16_Only_V_Distill_keys, ViTL_14_Only_V_Distill_keys + +LATEST_CHECKPOINT_NAME = "epoch_latest.pt" + + +def random_seed(seed=42, rank=0): + torch.manual_seed(seed + rank) + np.random.seed(seed + rank) + random.seed(seed + rank) + + +def natural_key(string_): + """See http://www.codinghorror.com/blog/archives/001018.html""" + return [int(s) if s.isdigit() else s for s in re.split(r'(\d+)', string_.lower())] + + +def get_latest_checkpoint(path: str, remote : bool): + # as writen, this glob recurses, so can pick up checkpoints across multiple sub-folders + if remote: + result = subprocess.run(["aws", "s3", "ls", path + "/"], stdout=subprocess.PIPE, stderr=subprocess.PIPE) + print(result) + if result.returncode == 1: + return None + checkpoints = [os.path.join(path, x.split(' ')[-1]) for x in result.stdout.decode().split('\n')[:-1]] + else: + checkpoints = glob.glob(path + '**/*.pt', recursive=True) + if checkpoints: + checkpoints = sorted(checkpoints, key=natural_key) + return checkpoints[-1] + return None + + +def main(args): + args = parse_args(args) + 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 + + # fully initialize distributed device environment + device = init_distributed_device(args) + # get the name of the experiments + if args.name is None: + # sanitize model name for filesystem / uri use, easier if we don't use / in name as a rule? + model_name_safe = args.model.replace('/', '-') + date_str = datetime.now().strftime("%Y_%m_%d-%H_%M_%S") + if args.distributed: + # sync date_str from master to all ranks + date_str = broadcast_object(args, date_str) + args.name = '-'.join([ + date_str, + f"model_{model_name_safe}", + f"lr_{args.lr}", + f"b_{args.batch_size}", + f"j_{args.workers}", + f"p_{args.precision}", + ]) + log_base_path = os.path.join(args.logs, args.name) + args.log_path = None + if is_master(args, local=args.log_local): + 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 os.path.exists(args.log_path): + print("WARNING, Experiment already exists.") + # Setup text logger + args.log_level = logging.DEBUG if args.debug else logging.INFO + setup_logging(args.log_path, args.log_level) + args.checkpoint_path = os.path.join(log_base_path, "checkpoints") + 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.') + 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}.') + + if isinstance(args.force_image_size, (tuple, list)) and len(args.force_image_size) == 1: + # arg is nargs, single (square) image size list -> int + args.force_image_size = args.force_image_size[0] + + random_seed(args.seed, 0) + student_model, preprocess_train, preprocess_val = create_model_and_transforms( + args.model, + args.pretrained, + precision=args.precision, + device=device, + jit=args.torchscript, + force_quick_gelu=args.force_quick_gelu, + force_custom_text=args.force_custom_text, + force_patch_dropout=args.force_patch_dropout, + force_image_size=args.force_image_size, + pretrained_image=args.pretrained_image, + image_mean=args.image_mean, + image_std=args.image_std, + aug_cfg=args.aug_cfg, + output_dict=True, + cache_dir=args.cache_dir, + det_image_size=args.det_image_size, + dataset_type=args.dataset_type, + args=args + ) + random_seed(args.seed, args.rank) + teacher_model = create_model( + args.model, # same ! + args.pretrained, + device=device, + precision=args.precision, + output_dict=True, + cache_dir=args.cache_dir # cache dir of pre-trained models + ).to(args.device) + args.input_size = student_model.visual.image_size + if args.lock_image: + student_model.lock_image_tower( + unlocked_groups=args.lock_image_unlocked_groups, + freeze_bn_stats=args.lock_image_freeze_bn_stats, + ) + if args.grad_checkpointing: + student_model.set_grad_checkpointing() + if args.proxy: + student_model=CLIPWithProjector(student_model, + hidden_dim=768 if args.model=="EVA02-CLIP-B-16" else 1024, + regular_alpha=0.7, + args=args + ).to(args.device) + vfm_model, feat_out = build_vfm(args.proxy) + vfm_model = vfm_model.to(args.device) + else: + freeze_keys=ViTB_16_Only_V_Distill_keys if args.model=="EVA02-CLIP-B-16" else ViTL_14_Only_V_Distill_keys + for n, p in student_model.named_parameters(): + if n in freeze_keys: + p.requires_grad = False + vfm_model=None + feat_out=None + + method = CLIPSelf() + student_model_without_ddp=student_model + if is_master(args): + logging.info("Model:") + logging.info(f"{str(student_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") + + if args.distributed: + if args.use_bn_sync: + if args.proxy: + student_model.clip= torch.nn.SyncBatchNorm.convert_sync_batchnorm(student_model.clip) + else: + student_model = torch.nn.SyncBatchNorm.convert_sync_batchnorm(student_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 + student_model = torch.nn.parallel.DistributedDataParallel(student_model, device_ids=[device], **ddp_args) + student_model_without_ddp=student_model.module + # create optimizer and scaler + optimizer = None + scaler = None + if args.train_data: + exclude = lambda n, p: p.ndim < 2 or "bn" in n or "ln" in n or "bias" in n or 'logit_scale' in n + include = lambda n, p: not exclude(n, p) + named_parameters = list(student_model_without_ddp.named_parameters()) + gain_or_bias_params = [p for n, p in named_parameters if exclude(n, p) and p.requires_grad] + rest_params = [p for n, p in named_parameters if include(n, p) and p.requires_grad] + optimizer = optim.AdamW( + [ + {"params": gain_or_bias_params, "weight_decay": 0.}, + {"params": rest_params, "weight_decay": args.wd}, + ], + lr=args.lr, + betas=(args.beta1, args.beta2), + eps=args.eps, + ) + scaler = GradScaler() if args.precision == "amp" else None + # optionally resume from a checkpoint + start_epoch = 0 + if args.resume is not None: + checkpoint = pt_load(args.resume, map_location='cpu') + if 'epoch' in checkpoint: + # resuming a train checkpoint w/ epoch and optimizer state + start_epoch = checkpoint["epoch"] + sd = checkpoint["state_dict"] + student_model_without_ddp.clip.load_state_dict(sd) if args.proxy else student_model_without_ddp.load_state_dict(sd) + if args.dataset_type == "froster": + teacher_model.load_state_dict(sd) + if optimizer is not None: + optimizer.load_state_dict(checkpoint["optimizer"]) + if scaler is not None and 'scaler' in checkpoint: + scaler.load_state_dict(checkpoint['scaler']) + if is_main_process(): + logging.info(f"=> resuming checkpoint '{args.resume}' (epoch {start_epoch})") + else: + # loading a bare (model only) checkpoint for fine-tune or evaluation + student_model_without_ddp.clip.load_state_dict(sd) if args.proxy else student_model_without_ddp.load_state_dict(sd) + if args.dataset_type == "froster": + teacher_model.load_state_dict(checkpoint) + if is_main_process(): + logging.info(f"=> loaded checkpoint '{args.resume}' (epoch {start_epoch})") + + # initialize datasets + data = get_data(args, (preprocess_train, preprocess_val), epoch=start_epoch, tokenizer=get_tokenizer(args.model)) + assert len(data), 'At least one train or eval dataset must be specified.' + # create scheduler if train + scheduler = None + if 'train' in data and optimizer is not None: + total_steps = (data["train"].dataloader.num_batches // args.accum_freq) * args.epochs + if args.lr_scheduler == "cosine": + scheduler = cosine_lr(optimizer, args.lr, args.warmup, total_steps) + elif args.lr_scheduler == "const": + scheduler = const_lr(optimizer, args.lr, args.warmup, total_steps) + elif args.lr_scheduler == "const-cooldown": + assert args.epochs_cooldown is not None,\ + "Please specify the number of cooldown epochs for this lr schedule." + cooldown_steps = (data["train"].dataloader.num_batches // args.accum_freq) * args.epochs_cooldown + scheduler = const_lr_cooldown( + optimizer, args.lr, args.warmup, total_steps, + cooldown_steps, args.lr_cooldown_power, args.lr_cooldown_end) + else: + logging.error( + f'Unknown scheduler, {args.lr_scheduler}. Available options are: cosine, const, const-cooldown.') + exit(1) + # determine if this worker should save logs and checkpoints. only do so if it is rank == 0 + args.save_logs = args.logs and args.logs.lower() != 'none' and is_master(args) + os.makedirs(args.checkpoint_path, exist_ok=True) + if 'train' not in data or args.eval: + del teacher_model + if args.k_means: + run_kmeans(student_model_without_ddp.clip,data,args) + elif args.run_seg: + run_seg(student_model_without_ddp.clip,data,args) + else: + evaluate(student_model_without_ddp.clip if args.proxy else student_model_without_ddp, data, start_epoch, args) + return + if not args.skip_first_eval: + if is_main_process(): + logging.info('Evaluate before training') + evaluate(student_model_without_ddp.clip if args.proxy else student_model_without_ddp, data, start_epoch, args) + for epoch in range(start_epoch, args.epochs): + if is_master(args): + logging.info(f'Start epoch {epoch}') + train_one_epoch(student_model, + teacher_model, + vfm_model, + method, + feat_out, + data,epoch,optimizer, scaler, scheduler, args) + completed_epoch = epoch + 1 + student_state_dict = student_model_without_ddp.clip.state_dict() if args.proxy else student_model_without_ddp.state_dict() + if args.alpha < 1.0: + teacher_state_dict = teacher_model.state_dict() + target_state_dict = student_teacher_ensemble(student_state_dict, teacher_state_dict, args.alpha) + else: + target_state_dict = student_state_dict + if is_master(args): + # Saving checkpoints. + checkpoint_dict = { + "epoch": completed_epoch, + "name": args.name, + "state_dict": target_state_dict, + "optimizer": optimizer.state_dict(), + } + if scaler is not None: + checkpoint_dict["scaler"] = scaler.state_dict() + if completed_epoch == args.epochs or ( + args.save_frequency > 0 and (completed_epoch % args.save_frequency) == 0 + ): + torch.save( + checkpoint_dict, + os.path.join(args.checkpoint_path, f"epoch_{completed_epoch}.pt"), + ) + if args.delete_previous_checkpoint: + previous_checkpoint = os.path.join(args.checkpoint_path, f"epoch_{completed_epoch - 1}.pt") + if os.path.exists(previous_checkpoint): + os.remove(previous_checkpoint) + + if args.save_most_recent: + # try not to corrupt the latest checkpoint if save fails + tmp_save_path = os.path.join(args.checkpoint_path, "tmp.pt") + latest_save_path = os.path.join(args.checkpoint_path, LATEST_CHECKPOINT_NAME) + torch.save(checkpoint_dict, tmp_save_path) + os.replace(tmp_save_path, latest_save_path) + + if completed_epoch % args.zeroshot_frequency == 0: + test_model = create_model( + args.model, + args.pretrained, + device=device, + precision=args.precision, + output_dict=True, + cache_dir=args.cache_dir) + test_model.load_state_dict(target_state_dict) + # if args.distributed: + # test_model = torch.nn.parallel.DistributedDataParallel(test_model, device_ids=[device], **ddp_args) + evaluate(test_model, data, completed_epoch, args) + del test_model + + +if __name__ == "__main__": + main(sys.argv[1:]) diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/training/misc.py b/downstream/ProxyCLIP_TPAMI/clipself/src/training/misc.py new file mode 100644 index 0000000000000000000000000000000000000000..17fe32855d9ab80a71ba8ae68da80a16103f65cb --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/training/misc.py @@ -0,0 +1,683 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved +""" +Misc functions, including distributed helpers. + +Mostly copy-paste from torchvision references. +""" +import os +import random +import subprocess +import time +from collections import OrderedDict, defaultdict, deque +import datetime +import pickle +from typing import Optional, List +from copy import deepcopy +import json, time +import numpy as np +import torch +import torch.distributed as dist +from torch import Tensor +from pathlib import Path +import colorsys +import warnings +import re +from open_clip.tokenizer import HFTokenizer, tokenize +warnings.filterwarnings('ignore', category=UserWarning, message='TypedStorage is deprecated') +# needed due to empty tensor bug in pytorch and torchvision 0.5 +import torchvision +__torchvision_need_compat_flag = float(torchvision.__version__.split('.')[1]) < 7 +if __torchvision_need_compat_flag: + from torchvision.ops import _new_empty_tensor + from torchvision.ops.misc import _output_size + +HF_HUB_PREFIX = 'hf-hub:' +_MODEL_CONFIG_PATHS = [Path(__file__).parent.parent / f"model_configs/"] +_MODEL_CONFIGS = {} # directory (model_name: config) of model architecture configs + +def _natural_key(string_): + return [int(s) if s.isdigit() else s for s in re.split(r'(\d+)', string_.lower())] + +def _rescan_model_configs(): + global _MODEL_CONFIGS + + config_ext = ('.json',) + config_files = [] + for config_path in _MODEL_CONFIG_PATHS: + if config_path.is_file() and config_path.suffix in config_ext: + config_files.append(config_path) + elif config_path.is_dir(): + for ext in config_ext: + config_files.extend(config_path.glob(f'*{ext}')) + + for cf in config_files: + with open(cf, 'r') as f: + model_cfg = json.load(f) + if all(a in model_cfg for a in ('embed_dim', 'vision_cfg', 'text_cfg')): + _MODEL_CONFIGS[cf.stem] = model_cfg + + _MODEL_CONFIGS = {k: v for k, v in sorted(_MODEL_CONFIGS.items(), key=lambda x: _natural_key(x[0]))} + + +_rescan_model_configs() # initial populate of model config registry + +def get_model_config(model_name): + if model_name in _MODEL_CONFIGS: + return deepcopy(_MODEL_CONFIGS[model_name]) + else: + return None + +def get_tokenizer(model_name): + if 'EVA' in model_name: + from open_clip import eva_clip + return eva_clip.get_tokenizer(model_name) + if model_name.startswith(HF_HUB_PREFIX): + tokenizer = HFTokenizer(model_name[len(HF_HUB_PREFIX):]) + else: + config = get_model_config(model_name) + tokenizer = HFTokenizer( + config['text_cfg']['hf_tokenizer_name']) if 'hf_tokenizer_name' in config['text_cfg'] else tokenize + return tokenizer + + +class CosineScheduler(object): + def __init__(self, base_value, final_value, total_iters, warmup_iters=0, start_warmup_value=0, freeze_iters=0): + super().__init__() + self.final_value = final_value + self.total_iters = total_iters + + freeze_schedule = np.zeros((freeze_iters)) + + warmup_schedule = np.linspace(start_warmup_value, base_value, warmup_iters) + + iters = np.arange(total_iters - warmup_iters - freeze_iters) + schedule = final_value + 0.5 * (base_value - final_value) * (1 + np.cos(np.pi * iters / len(iters))) + self.schedule = np.concatenate((freeze_schedule, warmup_schedule, schedule)) + + assert len(self.schedule) == self.total_iters + + def __getitem__(self, it): + if it >= self.total_iters: + return self.final_value + else: + return self.schedule[it] + +class SmoothedValue(object): + """Track a series of values and provide access to smoothed values over a + window or the global series average. + """ + + def __init__(self, window_size=20, fmt=None): + if fmt is None: + fmt = "{median:.4f} ({global_avg:.4f})" + self.deque = deque(maxlen=window_size) + self.total = 0.0 + self.count = 0 + self.fmt = fmt + + def update(self, value, n=1): + self.deque.append(value) + self.count += n + self.total += value * n + + def synchronize_between_processes(self): + """ + Warning: does not synchronize the deque! + """ + if not is_dist_avail_and_initialized(): + return + t = torch.tensor([self.count, self.total], dtype=torch.float64, device='cuda') + dist.barrier() + dist.all_reduce(t) + t = t.tolist() + self.count = int(t[0]) + self.total = t[1] + + @property + def median(self): + d = torch.tensor(list(self.deque)) + if d.shape[0] == 0: + return 0 + return d.median().item() + + @property + def avg(self): + d = torch.tensor(list(self.deque), dtype=torch.float32) + return d.mean().item() + + @property + def global_avg(self): + return self.total / self.count + + @property + def max(self): + return max(self.deque) + + @property + def value(self): + return self.deque[-1] + + def __str__(self): + return self.fmt.format( + median=self.median, + avg=self.avg, + global_avg=self.global_avg, + max=self.max, + value=self.value) + + +def all_gather(data): + """ + Run all_gather on arbitrary picklable data (not necessarily tensors) + Args: + data: any picklable object + Returns: + list[data]: list of data gathered from each rank + """ + world_size = get_world_size() + if world_size == 1: + return [data] + + # serialized to a Tensor + buffer = pickle.dumps(data) + storage = torch.ByteStorage.from_buffer(buffer) + tensor = torch.ByteTensor(storage).to("cuda") + + # obtain Tensor size of each rank + local_size = torch.tensor([tensor.numel()], device="cuda") + size_list = [torch.tensor([0], device="cuda") for _ in range(world_size)] + dist.all_gather(size_list, local_size) + size_list = [int(size.item()) for size in size_list] + max_size = max(size_list) + + # receiving Tensor from all ranks + # we pad the tensor because torch all_gather does not support + # gathering tensors of different shapes + tensor_list = [] + for _ in size_list: + tensor_list.append(torch.empty((max_size,), dtype=torch.uint8, device="cuda")) + if local_size != max_size: + padding = torch.empty(size=(max_size - local_size,), dtype=torch.uint8, device="cuda") + tensor = torch.cat((tensor, padding), dim=0) + dist.all_gather(tensor_list, tensor) + data_list = [] + for size, tensor in zip(size_list, tensor_list): + buffer = tensor.cpu().numpy().tobytes()[:size] + data_list.append(pickle.loads(buffer)) + + return data_list + + +def reduce_dict(input_dict, average=True): + """ + Args: + input_dict (dict): all the values will be reduced + average (bool): whether to do average or sum + Reduce the values in the dictionary from all processes so that all processes + have the averaged results. Returns a dict with the same fields as + input_dict, after reduction. + """ + world_size = get_world_size() + if world_size < 2: + return input_dict + with torch.no_grad(): + names = [] + values = [] + # sort the keys so that they are consistent across processes + for k in sorted(input_dict.keys()): + names.append(k) + values.append(input_dict[k]) + values = torch.stack(values, dim=0) + dist.all_reduce(values) + if average: + values /= world_size + reduced_dict = {k: v for k, v in zip(names, values)} + return reduced_dict + + +class MetricLogger(object): + def __init__(self, delimiter="\t"): + self.meters = defaultdict(SmoothedValue) + self.delimiter = delimiter + + def update(self, **kwargs): + for k, v in kwargs.items(): + if isinstance(v, torch.Tensor): + v = v.item() + assert isinstance(v, (float, int)) + self.meters[k].update(v) + + def __getattr__(self, attr): + if attr in self.meters: + return self.meters[attr] + if attr in self.__dict__: + return self.__dict__[attr] + raise AttributeError("'{}' object has no attribute '{}'".format( + type(self).__name__, attr)) + + def __str__(self): + loss_str = [] + for name, meter in self.meters.items(): + # print(name, str(meter)) + # import ipdb;ipdb.set_trace() + if meter.count > 0: + loss_str.append( + "{}: {}".format(name, str(meter)) + ) + return self.delimiter.join(loss_str) + + def synchronize_between_processes(self): + for meter in self.meters.values(): + meter.synchronize_between_processes() + + def add_meter(self, name, meter): + self.meters[name] = meter + + def log_every(self, iterable, print_freq, header=None, logger=None): + if logger is None: + print_func = print + else: + print_func = logger.info + + i = 0 + if not header: + header = '' + start_time = time.time() + end = time.time() + iter_time = SmoothedValue(fmt='{avg:.4f}') + data_time = SmoothedValue(fmt='{avg:.4f}') + space_fmt = ':' + str(len(str(len(iterable)))) + 'd' + if torch.cuda.is_available(): + log_msg = self.delimiter.join([ + header, + '[{0' + space_fmt + '}/{1}]', + 'eta: {eta}', + '{meters}', + 'time: {time}', + 'data: {data}', + 'max mem: {memory:.0f}' + ]) + else: + log_msg = self.delimiter.join([ + header, + '[{0' + space_fmt + '}/{1}]', + 'eta: {eta}', + '{meters}', + 'time: {time}', + 'data: {data}' + ]) + MB = 1024.0 * 1024.0 + for obj in iterable: + data_time.update(time.time() - end) + yield obj + + iter_time.update(time.time() - end) + if i % print_freq == 0 or i == len(iterable) - 1: + eta_seconds = iter_time.global_avg * (len(iterable) - i) + eta_string = str(datetime.timedelta(seconds=int(eta_seconds))) + if torch.cuda.is_available(): + print_func(log_msg.format( + i, len(iterable), eta=eta_string, + meters=str(self), + time=str(iter_time), data=str(data_time), + memory=torch.cuda.max_memory_allocated() / MB)) + else: + print_func(log_msg.format( + i, len(iterable), eta=eta_string, + meters=str(self), + time=str(iter_time), data=str(data_time))) + i += 1 + end = time.time() + total_time = time.time() - start_time + total_time_str = str(datetime.timedelta(seconds=int(total_time))) + print_func('{} Total time: {} ({:.4f} s / it)'.format( + header, total_time_str, total_time / len(iterable))) + + +def get_sha(): + cwd = os.path.dirname(os.path.abspath(__file__)) + + def _run(command): + return subprocess.check_output(command, cwd=cwd).decode('ascii').strip() + sha = 'N/A' + diff = "clean" + branch = 'N/A' + try: + sha = _run(['git', 'rev-parse', 'HEAD']) + subprocess.check_output(['git', 'diff'], cwd=cwd) + diff = _run(['git', 'diff-index', 'HEAD']) + diff = "has uncommited changes" if diff else "clean" + branch = _run(['git', 'rev-parse', '--abbrev-ref', 'HEAD']) + except Exception: + pass + message = f"sha: {sha}, status: {diff}, branch: {branch}" + return message + +class CollateFn: + def __init__(self, resolution): + self.resolution = resolution + + def __call__(self, batch): + batch = list(zip(*batch)) + batch[0] = self.nested_tensor_from_tensor_list_fixed(batch[0]) + return tuple(batch) + + def nested_tensor_from_tensor_list_fixed(self, tensor_list: List[Tensor]): + # TODO make this more general + if tensor_list[0].ndim == 3: + if torchvision._is_tracing(): + return _onnx_nested_tensor_from_tensor_list(tensor_list) + max_size = [3,self.resolution[0],self.resolution[1]] + batch_shape = [len(tensor_list)] + max_size + b, c, h, w = batch_shape + dtype = tensor_list[0].dtype + device = tensor_list[0].device + tensor = torch.zeros(batch_shape, dtype=dtype, device=device) + mask = torch.ones((b, h, w), dtype=torch.bool, device=device) + for img, pad_img, m in zip(tensor_list, tensor, mask): + pad_img[: img.shape[0], : img.shape[1], : img.shape[2]].copy_(img) + m[: img.shape[1], :img.shape[2]] = False + else: + raise ValueError('not supported') + return NestedTensor(tensor, mask) + +def collate_fn(batch): + batch = list(zip(*batch)) + batch[0] = nested_tensor_from_tensor_list(batch[0]) + return tuple(batch) + +def _max_by_axis(the_list): + # type: (List[List[int]]) -> List[int] + maxes = the_list[0] + for sublist in the_list[1:]: + for index, item in enumerate(sublist): + maxes[index] = max(maxes[index], item) + return maxes + + +class NestedTensor(object): + def __init__(self, tensors, mask: Optional[Tensor]): + self.tensors = tensors + self.mask = mask + if mask == 'auto': + self.mask = torch.zeros_like(tensors).to(tensors.device) + if self.mask.dim() == 3: + self.mask = self.mask.sum(0).to(bool) + elif self.mask.dim() == 4: + self.mask = self.mask.sum(1).to(bool) + else: + raise ValueError("tensors dim must be 3 or 4 but {}({})".format(self.tensors.dim(), self.tensors.shape)) + + def imgsize(self): + res = [] + for i in range(self.tensors.shape[0]): + mask = self.mask[i] + maxH = (~mask).sum(0).max() + maxW = (~mask).sum(1).max() + res.append(torch.Tensor([maxH, maxW])) + return res + + def to(self, device): + # type: (Device) -> NestedTensor # noqa + cast_tensor = self.tensors.to(device) + mask = self.mask + if mask is not None: + assert mask is not None + cast_mask = mask.to(device) + else: + cast_mask = None + return NestedTensor(cast_tensor, cast_mask) + + def to_img_list_single(self, tensor, mask): + assert tensor.dim() == 3, "dim of tensor should be 3 but {}".format(tensor.dim()) + maxH = (~mask).sum(0).max() + maxW = (~mask).sum(1).max() + img = tensor[:, :maxH, :maxW] + return img + + def to_img_list(self): + """remove the padding and convert to img list + + Returns: + [type]: [description] + """ + if self.tensors.dim() == 3: + return self.to_img_list_single(self.tensors, self.mask) + else: + res = [] + for i in range(self.tensors.shape[0]): + tensor_i = self.tensors[i] + mask_i = self.mask[i] + res.append(self.to_img_list_single(tensor_i, mask_i)) + return res + + @property + def device(self): + return self.tensors.device + + def decompose(self): + return self.tensors, self.mask + + def __repr__(self): + return str(self.tensors) + + @property + def shape(self): + return { + 'tensors.shape': self.tensors.shape, + 'mask.shape': self.mask.shape + } + + +def nested_tensor_from_tensor_list(tensor_list: List[Tensor]): + # TODO make this more general + if tensor_list[0].ndim == 3: + if torchvision._is_tracing(): + # nested_tensor_from_tensor_list() does not export well to ONNX + # call _onnx_nested_tensor_from_tensor_list() instead + return _onnx_nested_tensor_from_tensor_list(tensor_list) + + # TODO make it support different-sized images + max_size = _max_by_axis([list(img.shape) for img in tensor_list]) + # min_size = tuple(min(s) for s in zip(*[img.shape for img in tensor_list])) + batch_shape = [len(tensor_list)] + max_size + b, c, h, w = batch_shape + dtype = tensor_list[0].dtype + device = tensor_list[0].device + tensor = torch.zeros(batch_shape, dtype=dtype, device=device) + mask = torch.ones((b, h, w), dtype=torch.bool, device=device) + for img, pad_img, m in zip(tensor_list, tensor, mask): + pad_img[: img.shape[0], : img.shape[1], : img.shape[2]].copy_(img) + m[: img.shape[1], :img.shape[2]] = False + else: + raise ValueError('not supported') + return NestedTensor(tensor, mask) + +# _onnx_nested_tensor_from_tensor_list() is an implementation of +# nested_tensor_from_tensor_list() that is supported by ONNX tracing. +@torch.jit.unused +def _onnx_nested_tensor_from_tensor_list(tensor_list: List[Tensor]) -> NestedTensor: + max_size = [] + for i in range(tensor_list[0].dim()): + max_size_i = torch.max(torch.stack([img.shape[i] for img in tensor_list]).to(torch.float32)).to(torch.int64) + max_size.append(max_size_i) + max_size = tuple(max_size) + + # work around for + # pad_img[: img.shape[0], : img.shape[1], : img.shape[2]].copy_(img) + # m[: img.shape[1], :img.shape[2]] = False + # which is not yet supported in onnx + padded_imgs = [] + padded_masks = [] + for img in tensor_list: + padding = [(s1 - s2) for s1, s2 in zip(max_size, tuple(img.shape))] + padded_img = torch.nn.functional.pad(img, (0, padding[2], 0, padding[1], 0, padding[0])) + padded_imgs.append(padded_img) + + m = torch.zeros_like(img[0], dtype=torch.int, device=img.device) + padded_mask = torch.nn.functional.pad(m, (0, padding[2], 0, padding[1]), "constant", 1) + padded_masks.append(padded_mask.to(torch.bool)) + + tensor = torch.stack(padded_imgs) + mask = torch.stack(padded_masks) + + return NestedTensor(tensor, mask=mask) + + +def setup_for_distributed(is_master): + """ + This function disables printing when not in master process + """ + import builtins as __builtin__ + builtin_print = __builtin__.print + + def print(*args, **kwargs): + force = kwargs.pop('force', False) + if is_master or force: + builtin_print(*args, **kwargs) + + __builtin__.print = print + + +def is_dist_avail_and_initialized(): + if not dist.is_available(): + return False + if not dist.is_initialized(): + return False + return True + + +def get_world_size(): + if not is_dist_avail_and_initialized(): + return 1 + return dist.get_world_size() + + +def get_rank(): + if not is_dist_avail_and_initialized(): + return 0 + return dist.get_rank() + + +def is_main_process(): + return get_rank() == 0 + + +def save_on_master(*args, **kwargs): + if is_main_process(): + torch.save(*args, **kwargs) + + +def init_distributed_mode(args): + if 'WORLD_SIZE' in os.environ and os.environ['WORLD_SIZE'] != '': # 'RANK' in os.environ and + # args.rank = int(os.environ["RANK"]) + # args.world_size = int(os.environ['WORLD_SIZE']) + # args.gpu = args.local_rank = int(os.environ['LOCAL_RANK']) + + # launch by torch.distributed.launch + # Single node + # python -m torch.distributed.launch --nproc_per_node=8 main.py --world-size 1 --rank 0 ... + # Multi nodes + # python -m torch.distributed.launch --nproc_per_node=8 main.py --world-size 2 --rank 0 --dist-url 'tcp://IP_OF_NODE0:FREEPORT' ... + # python -m torch.distributed.launch --nproc_per_node=8 main.py --world-size 2 --rank 1 --dist-url 'tcp://IP_OF_NODE0:FREEPORT' ... + + local_world_size = int(os.environ['WORLD_SIZE']) + args.world_size = args.world_size * local_world_size + args.gpu = args.local_rank = int(os.environ['LOCAL_RANK']) + args.rank = args.rank * local_world_size + args.local_rank + print('world size: {}, rank: {}, local rank: {}'.format(args.world_size, args.rank, args.local_rank)) + print(json.dumps(dict(os.environ), indent=2)) + elif 'SLURM_PROCID' in os.environ: + args.rank = int(os.environ['SLURM_PROCID']) + args.gpu = args.local_rank = int(os.environ['SLURM_LOCALID']) + args.world_size = int(os.environ['SLURM_NPROCS']) + + print('world size: {}, world rank: {}, local rank: {}, device_count: {}'.format(args.world_size, args.rank, args.local_rank, torch.cuda.device_count())) + else: + print('Not using distributed mode') + args.distributed = False + args.world_size = 1 + args.rank = 0 + args.local_rank = 0 + return + + print("world_size:{} rank:{} local_rank:{}".format(args.world_size, args.rank, args.local_rank)) + args.distributed = True + torch.cuda.set_device(args.local_rank) + args.dist_backend = 'nccl' + print('| distributed init (rank {}): {}'.format(args.rank, args.dist_url), flush=True) + torch.distributed.init_process_group(backend=args.dist_backend, init_method=args.dist_url, + world_size=args.world_size, rank=args.rank) + print("Before torch.distributed.barrier()") + torch.distributed.barrier() + print("End torch.distributed.barrier()") + setup_for_distributed(args.rank == 0) + + +@torch.no_grad() +def accuracy(output, target, topk=(1,)): + """Computes the precision@k for the specified values of k""" + if target.numel() == 0: + return [torch.zeros([], device=output.device)] + maxk = max(topk) + batch_size = target.size(0) + + _, pred = output.topk(maxk, 1, True, True) + pred = pred.t() + correct = pred.eq(target.view(1, -1).expand_as(pred)) + + res = [] + for k in topk: + correct_k = correct[:k].view(-1).float().sum(0) + res.append(correct_k.mul_(100.0 / batch_size)) + return res + + +def interpolate(input, size=None, scale_factor=None, mode="nearest", align_corners=None): + # type: (Tensor, Optional[List[int]], Optional[float], str, Optional[bool]) -> Tensor + """ + Equivalent to nn.functional.interpolate, but with support for empty batch sizes. + This will eventually be supported natively by PyTorch, and this + class can go away. + """ + if __torchvision_need_compat_flag < 0.7: + if input.numel() > 0: + return torch.nn.functional.interpolate( + input, size, scale_factor, mode, align_corners + ) + + output_shape = _output_size(2, input, size, scale_factor) + output_shape = list(input.shape[:-2]) + list(output_shape) + return _new_empty_tensor(input, output_shape) + else: + return torchvision.ops.misc.interpolate(input, size, scale_factor, mode, align_corners) + + + +class color_sys(): + def __init__(self, num_colors) -> None: + self.num_colors = num_colors + colors=[] + for i in np.arange(0., 360., 360. / num_colors): + hue = i/360. + lightness = (50 + np.random.rand() * 10)/100. + saturation = (90 + np.random.rand() * 10)/100. + colors.append(tuple([int(j*255) for j in colorsys.hls_to_rgb(hue, lightness, saturation)])) + self.colors = colors + + def __call__(self, idx): + return self.colors[idx] + +def inverse_sigmoid(x, eps=1e-3): + x = x.clamp(min=0, max=1) + x1 = x.clamp(min=eps) + x2 = (1 - x).clamp(min=eps) + return torch.log(x1/x2) + +def clean_state_dict(state_dict): + new_state_dict = OrderedDict() + for k, v in state_dict.items(): + if k[:7] == 'module.': + k = k[7:] # remove `module.` + new_state_dict[k] = v + return new_state_dict \ No newline at end of file diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/training/params.py b/downstream/ProxyCLIP_TPAMI/clipself/src/training/params.py new file mode 100644 index 0000000000000000000000000000000000000000..a03e23bf9a3e35646ccf5f978b4e87c6378756ef --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/training/params.py @@ -0,0 +1,518 @@ +import argparse +import ast + + +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} + + +class ParseKwargs(argparse.Action): + def __call__(self, parser, namespace, values, option_string=None): + kw = {} + for value in values: + key, value = value.split('=') + try: + kw[key] = ast.literal_eval(value) + except ValueError: + kw[key] = str(value) # fallback to string (avoid need to escape on command line) + setattr(namespace, self.dest, kw) + + +def parse_args(args): + parser = argparse.ArgumentParser() + parser.add_argument( + "--max-boxes", + type=int, + default=20, + ) + parser.add_argument( + "--featup", + action="store_true", + default=False, + ) + parser.add_argument( + "--clim", + action="store_true", + default=False, + ) + parser.add_argument( + "--max-masks", + type=int, + default=20) + parser.add_argument( + "--skip-first-eval", + action="store_true", + default=False) + parser.add_argument( + "--eval", + action="store_true", + default=False) + parser.add_argument( + "--downsample-factor", + type=int, + default=16) + parser.add_argument( + "--alpha", + type=float, + default=2.0, # not used when alpha >=1.0 + ) + parser.add_argument( + "--grid-noise", + action="store_true", + default=False + ) + parser.add_argument( + "--proxy", + type=str, + choices=['dino', 'dinov2','sam'], + default="", + ) + parser.add_argument( + "--shift-range", + type=float, + default=0.0 + ) + parser.add_argument( + "--scale-range", + type=float, + default=0.0 + ) + parser.add_argument( + "--crop-scale", + type=float, + default=1.0, + ) + parser.add_argument( + "--box-scale", + type=float, + default=1.5, + ) + parser.add_argument( + "--multiscale", + action="store_true", + default=False, + ) + parser.add_argument( + "--pre-transforms", + action="store_true", + default=False, + ) + parser.add_argument( + "--max-size", + type=int, + default=1024, + ) + parser.add_argument( + "--embed-dim", + type=int, + default=768, + ) + parser.add_argument( + "--fix-logit-scale", + action="store_true", + default=False, + ) + parser.add_argument( + "--min-size", + type=int, + default=8, + ) + parser.add_argument( + "--max-split", + type=int, + default=6, + ) + parser.add_argument( + "--extract-type", + type=str, + choices=['v1', 'v2'], + default="v2", + ) + parser.add_argument( + "--cache-dir", + type=str, + default="checkpoints", + ) + parser.add_argument( + "--kl-weight", + type=float, + default=1.0, + ) + parser.add_argument( + "--contrast-weight", + type=float, + default=1.0, + ) + + parser.add_argument( + "--train-ratio", + type=float, + default=1.0, + ) + parser.add_argument( + "--l1-weight", + type=float, + default=0.10, + ) + parser.add_argument( + "--smooth-weight", + type=float, + default=0.0, + ) + parser.add_argument( + "--cosine-weight", + type=float, + default=1.0, + ) + parser.add_argument( + "--det-image-size", + type=int, + default=1024, + ) + parser.add_argument( + "--train-image-size", + type=int, + default=1024, + ) + + parser.add_argument( + "--image-ave-pool", + action="store_true", + default=False, + ) + + parser.add_argument( + "--roi-teacher", + action="store_true", + default=False, + ) + parser.add_argument( + "--mask-thr", + type=float, + default=0.7, + ) + parser.add_argument( + "--train-image-root", + type=str, + default="data/coco/val2017", + ) + parser.add_argument( + "--train-ceph-root", + type=str, + default="", + ) + parser.add_argument( + "--val-image-root", + type=str, + default="data/coco/val2017", + ) + parser.add_argument( + "--val-segm-root", + type=str, + default="data/coco/annotations/panoptic_val2017", + ) + parser.add_argument( + "--train-segm-root", + type=str, + default="data/coco/annotations/panoptic_val2017", + ) + parser.add_argument( + "--embed-path", + type=str, + default="metadata/coco_clip_hand_craft_RN50.npy", + ) + parser.add_argument( + "--train-embed-path", + type=str, + default="", + ) + parser.add_argument( + "--del-dist-model", + action="store_true", + default=False, + ) + parser.add_argument( + "--train-data", + type=str, + default="", + help="Path to file(s) with training data. When using webdataset, " + "multiple datasources can be combined using the `::` separator.", + ) + parser.add_argument( + "--val-data", + type=str, + default="data/coco/annotations/instances_val2017_100.json" + ) + parser.add_argument( + "--dataset-type", + choices=['proposals_distill', "region_clip", "grid_distill","coco_caption","froster"], + default="grid_distill", + help="Which type of dataset to process." + ) + parser.add_argument( + "--test-type", + choices=['coco_panoptic'], + default="coco_panoptic", + help="Which type of dataset to process." + ) + 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=int, default=32, help="Number of epochs to train for." + ) + parser.add_argument("--lr", type=float, default=1e-5, 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( + "--lr-scheduler", + type=str, + default='cosine', + help="LR scheduler. One of: 'cosine', 'const' (constant), 'const-cooldown' (constant w/ cooldown). Default: cosine", + ) + parser.add_argument( + "--lr-cooldown-end", type=float, default=0.0, + help="End learning rate for cooldown schedule. Default: 0" + ) + parser.add_argument( + "--lr-cooldown-power", type=float, default=1.0, + help="Power for polynomial cooldown schedule. Default: 1.0 (linear 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=2, help="How often to run zero shot." + ) + parser.add_argument( + "--resume", + default=None, + type=str, + help="path to latest checkpoint (default: none)", + ) + parser.add_argument( + "--precision", + choices=["amp", "amp_bf16", "amp_bfloat16", "bf16", "fp16", "fp32"], + default="amp", + help="Floating point precision." + ) + parser.add_argument( + "--mode", + choices=["ss_vfm", "ss_vfm_distill", "qk_vfm_distill", "only_v_distill"], + default="ss_vfm", + help="Choosing an attention mode for training and inference" + ) + 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", + 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-image-unlocked-groups", + type=int, + default=3, # freeze at 2 + help="Leave last n image tower layer groups unlocked.", + ) + parser.add_argument( + "--lock-image-freeze-bn-stats", + default=True, + action='store_true', + help="Freeze BatchNorm running stats in image tower for any locked layers.", + ) + parser.add_argument( + "--k-means", + default=False, + action='store_true', + help="run k-means on evaluation set", + ) + parser.add_argument( + "--run-seg", + default=False, + action='store_true', + help="run open-vocabulary segmentation on evaluation set", + ) + 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('--aug-cfg', nargs='*', default={}, action=ParseKwargs) + parser.add_argument( + "--grad-checkpointing", + default=False, + action='store_true', + help="Enable gradient checkpointing.", + ) + parser.add_argument( + "--gather-with-grad", + default=False, + action="store_true", + help="enable full distributed gradient for feature gather" + ) + parser.add_argument( + '--force-image-size', type=int, nargs='+', default=None, + help='Override default image size' + ) + 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( + "--force-patch-dropout", + default=None, + type=float, + help="Override the patch dropout during training, for fine tuning with no dropout near the end as in the paper", + ) + parser.add_argument( + "--force-custom-text", + default=False, + action='store_true', + help="Force use of CustomTextCLIP model (separate text-tower).", + ) + 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( + "--accum-freq", type=int, default=1, help="Update the model every --acum-freq steps." + ) + # 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( + "--debug", + default=False, + action="store_true", + help="If true, more information is logged." + ) + parser.add_argument( + "--copy-codebase", + default=False, + action="store_true", + help="If true, we copy the entire base on the log directory, 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( + "--grad-clip-norm", type=float, default=None, help="Gradient clip." + ) + parser.add_argument( + "--log-every-n-steps", + type=int, + default=100, + ) + + parser.add_argument( + "--delete-previous-checkpoint", + default=False, + action="store_true", + help="If true, delete previous checkpoint after storing a new one." + ) + + args = parser.parse_args(args) + + # 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/downstream/ProxyCLIP_TPAMI/clipself/src/training/precision.py b/downstream/ProxyCLIP_TPAMI/clipself/src/training/precision.py new file mode 100644 index 0000000000000000000000000000000000000000..a63b92256518d13afd57261df1568e26b1622201 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/training/precision.py @@ -0,0 +1,12 @@ +import torch +from contextlib import suppress + + +def get_autocast(precision): + if precision == 'amp': + return torch.cuda.amp.autocast + elif precision == 'amp_bfloat16' or precision == 'amp_bf16': + # amp_bfloat16 is more stable than amp float16 for clip training + return lambda: torch.cuda.amp.autocast(dtype=torch.bfloat16) + else: + return suppress diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/training/profile.py b/downstream/ProxyCLIP_TPAMI/clipself/src/training/profile.py new file mode 100644 index 0000000000000000000000000000000000000000..f10372cdef306e5e199db432b23062df1c098cf9 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/training/profile.py @@ -0,0 +1,158 @@ +import argparse + +import torch +import open_clip +import pandas as pd +from fvcore.nn import FlopCountAnalysis, flop_count_str, ActivationCountAnalysis + + +parser = argparse.ArgumentParser(description='OpenCLIP Profiler') + +# benchmark specific args +parser.add_argument('--model', metavar='NAME', default='', + help='model(s) to profile') +parser.add_argument('--results-file', default='', type=str, metavar='FILENAME', + help='Output csv file for results') + + +def profile_fvcore( + model, + image_input_size=(3, 224, 224), + text_input_size=(77,), + batch_size=1, + detailed=False, + force_cpu=False +): + if force_cpu: + model = model.to('cpu') + device, dtype = next(model.parameters()).device, next(model.parameters()).dtype + example_image_input = torch.ones((batch_size,) + image_input_size, device=device, dtype=dtype) + example_text_input = torch.ones((batch_size,) + text_input_size, device=device, dtype=torch.int64) + fca = FlopCountAnalysis(model, (example_image_input, example_text_input)) + aca = ActivationCountAnalysis(model, (example_image_input, example_text_input)) + if detailed: + fcs = flop_count_str(fca) + print(fcs) + return fca.total(), aca.total() + + +def profile_fvcore_text( + model, + text_input_size=(77,), + batch_size=1, + detailed=False, + force_cpu=False +): + if force_cpu: + model = model.to('cpu') + device = next(model.parameters()).device + example_input = torch.ones((batch_size,) + text_input_size, device=device, dtype=torch.int64) + fca = FlopCountAnalysis(model, example_input) + aca = ActivationCountAnalysis(model, example_input) + if detailed: + fcs = flop_count_str(fca) + print(fcs) + return fca.total(), aca.total() + + +def profile_fvcore_image( + model, + image_input_size=(3, 224, 224), + batch_size=1, + detailed=False, + force_cpu=False +): + if force_cpu: + model = model.to('cpu') + device, dtype = next(model.parameters()).device, next(model.parameters()).dtype + example_input = torch.ones((batch_size,) + image_input_size, device=device, dtype=dtype) + fca = FlopCountAnalysis(model, example_input) + aca = ActivationCountAnalysis(model, example_input) + if detailed: + fcs = flop_count_str(fca) + print(fcs) + return fca.total(), aca.total() + + +def count_params(model): + return sum([m.numel() for m in model.parameters()]) + + +def profile_model(model_name): + model = open_clip.create_model(model_name, force_custom_text=True, pretrained_hf=False) + model.eval() + if torch.cuda.is_available(): + model = model.cuda() + + if isinstance(model.visual.image_size, (tuple, list)): + image_input_size = (3,) + tuple(model.visual.image_size[-2:]) + else: + image_input_size = (3, model.visual.image_size, model.visual.image_size) + text_input_size = (77,) + + results = {} + results['model'] = model_name + results['image_size'] = image_input_size[1] + + model_cfg = open_clip.get_model_config(model_name) + if model_cfg: + vision_cfg = open_clip.CLIPVisionCfg(**model_cfg['vision_cfg']) + text_cfg = open_clip.CLIPTextCfg(**model_cfg['text_cfg']) + results['image_width'] = int(vision_cfg.width) + results['text_width'] = int(text_cfg.width) + results['embed_dim'] = int(model_cfg['embed_dim']) + else: + results['image_width'] = 0 + results['text_width'] = 0 + results['embed_dim'] = 0 + + retries = 2 + while retries: + retries -= 1 + try: + macs, acts = profile_fvcore( + model, image_input_size=image_input_size, text_input_size=text_input_size, force_cpu=not retries) + + image_macs, image_acts = profile_fvcore_image( + model.visual, image_input_size=image_input_size, force_cpu=not retries) + + text_macs, text_acts = profile_fvcore_text( + model.text, text_input_size=text_input_size, force_cpu=not retries) + + results['gmacs'] = round(macs / 1e9, 2) + results['macts'] = round(acts / 1e6, 2) + results['mparams'] = round(count_params(model) / 1e6, 2) + results['image_gmacs'] = round(image_macs / 1e9, 2) + results['image_macts'] = round(image_acts / 1e6, 2) + results['image_mparams'] = round(count_params(model.visual) / 1e6, 2) + results['text_gmacs'] = round(text_macs / 1e9, 2) + results['text_macts'] = round(text_acts / 1e6, 2) + results['text_mparams'] = round(count_params(model.text) / 1e6, 2) + except RuntimeError as e: + pass + return results + + +def main(): + args = parser.parse_args() + + # FIXME accept a text file name to allow lists of models in txt/csv + if args.model == 'all': + parsed_model = open_clip.list_models() + else: + parsed_model = args.model.split(',') + + results = [] + for m in parsed_model: + row = profile_model(m) + results.append(row) + + df = pd.DataFrame(results, columns=results[0].keys()) + df = df.sort_values('gmacs') + print(df) + if args.results_file: + df.to_csv(args.results_file, index=False) + + +if __name__ == '__main__': + main() diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/training/region_clip.py b/downstream/ProxyCLIP_TPAMI/clipself/src/training/region_clip.py new file mode 100644 index 0000000000000000000000000000000000000000..962a4dbb0bad81f80fc2509f13e0e37cb94a2de2 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/training/region_clip.py @@ -0,0 +1,67 @@ +import numpy as np +import torch +import torch.nn.functional as F +import torch.nn as nn + + +def get_fed_loss_inds(gt_classes, num_sample_cats, C): + appeared = torch.unique(gt_classes) # C' + prob = appeared.new_ones(C).float() + if len(appeared) < num_sample_cats: + prob[appeared] = 0 + more_appeared = torch.multinomial( + prob, num_sample_cats - len(appeared), + replacement=False) + appeared = torch.cat([appeared, more_appeared]) + return appeared + + +class RegionCLIP(nn.Module): + def __init__(self, args): + super().__init__() + embed_path = args.train_embed_path + noun_embeddings = torch.from_numpy(np.load(embed_path)) + noun_embeddings = F.normalize(noun_embeddings, dim=-1) + self.register_buffer("noun_embeddings", noun_embeddings) + self.place_holder = nn.Parameter(torch.ones(1)) + + def __call__(self, batch, model, dist_model, loss, device, cast_dtype, + distributed, args): + if distributed: + model = model.module + images, boxes = batch + images = images.to(device=device, dtype=cast_dtype, non_blocking=True) + boxes = boxes.to(device=device, non_blocking=True) + + boxes_list = [] + boxes_label_list = [] + + for boxes_per_image in boxes: + boxes_per_image = boxes_per_image[boxes_per_image[:, -1] > 0.5] + boxes_label_list.append(boxes_per_image[:, 4].long()) + boxes_list.append(boxes_per_image[:, :4]) + boxes_labels = torch.cat(boxes_label_list) + box_features = model.encode_pseudo_boxes(images, boxes_list, normalize=True, + extract_type=args.extract_type) + temp = model.logit_scale.exp().detach() + boxes2nouns = box_features @ self.noun_embeddings.T * temp + target = torch.zeros_like(boxes2nouns) + target[range(len(boxes_labels)), boxes_labels] = 1.0 + + appeared = get_fed_loss_inds(boxes_labels, 100, self.noun_embeddings.shape[0]) + target = target[:, appeared] + boxes2nouns = boxes2nouns[:, appeared] + + loss_cls = F.binary_cross_entropy_with_logits(boxes2nouns, target, reduction='none') # B x C + loss_cls = loss_cls.sum(-1).mean() + + image_size = model.visual.image_size + if isinstance(image_size, int): + tar_h = tar_w = image_size + else: + tar_h, tar_w = image_size + images = F.interpolate(images, size=(tar_h, tar_w), mode='bilinear') + + losses = dict(loss_contrast=loss_cls * args.contrast_weight) + + return losses, len(images), temp diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/training/scheduler.py b/downstream/ProxyCLIP_TPAMI/clipself/src/training/scheduler.py new file mode 100644 index 0000000000000000000000000000000000000000..fba76fcf1720b11d136a5ab6d3a58ab2fbe42f74 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/training/scheduler.py @@ -0,0 +1,53 @@ +import numpy as np + + +def assign_learning_rate(optimizer, new_lr): + 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 const_lr(optimizer, base_lr, warmup_length, steps): + def _lr_adjuster(step): + if step < warmup_length: + lr = _warmup_lr(base_lr, warmup_length, step) + else: + lr = base_lr + assign_learning_rate(optimizer, lr) + return lr + return _lr_adjuster + + +def const_lr_cooldown(optimizer, base_lr, warmup_length, steps, cooldown_steps, cooldown_power=1.0, cooldown_end_lr=0.): + def _lr_adjuster(step): + start_cooldown_step = steps - cooldown_steps + if step < warmup_length: + lr = _warmup_lr(base_lr, warmup_length, step) + else: + if step < start_cooldown_step: + lr = base_lr + else: + e = step - start_cooldown_step + es = steps - start_cooldown_step + # linear decay if power == 1; polynomial decay otherwise; + decay = (1 - (e/es)) ** cooldown_power + lr = decay * (base_lr - cooldown_end_lr) + cooldown_end_lr + assign_learning_rate(optimizer, lr) + return lr + return _lr_adjuster + + +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 diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/training/train.py b/downstream/ProxyCLIP_TPAMI/clipself/src/training/train.py new file mode 100644 index 0000000000000000000000000000000000000000..8c0d4e06965afb4b7fb966232be46415be0df3b4 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/training/train.py @@ -0,0 +1,202 @@ +import json +import logging +import math +import time +import torch +from training.misc import is_main_process +from open_clip import get_cast_dtype +from .distributed import is_master +from .zero_shot import zero_shot_eval +from .precision import get_autocast +import os + + +class AverageMeter(object): + """Computes and stores the average and current value""" + + def __init__(self): + self.reset() + + def reset(self): + self.val = 0 + self.avg = 0 + self.sum = 0 + self.count = 0 + + def update(self, val, n=1): + self.val = val + self.sum += val * n + self.count += n + self.avg = self.sum / self.count + +def postprocess_clip_output(model_out): + return { + "image_features": model_out[0], + "text_features": model_out[1], + "logit_scale": model_out[2] + } + +def unwrap_model(model): + if hasattr(model, 'module'): + return model.module + else: + return model + + +def backward(total_loss, scaler): + if scaler is not None: + scaler.scale(total_loss).backward() + else: + total_loss.backward() + +def format_time(seconds): + """将秒数转换为小时、分钟和秒的格式""" + hours = int(seconds // 3600) + minutes = int((seconds % 3600) // 60) + seconds = int(seconds % 60) + return f"{hours}h {minutes}m {seconds}s" + +@torch.no_grad() +def student_teacher_ensemble(student, teacher, alpha=0.5): + target_state_dict = {} + for k, v in student.items(): + target_state_dict[k] = v * alpha + teacher[k] * (1.0 - alpha) + return target_state_dict + + +def train_one_epoch(model, teacher_model, vfm_model, method, feat_out, data, epoch, optimizer, scaler, scheduler, args): + autocast = get_autocast(args.precision) + model.train() + data['train'].set_epoch(epoch) # set epoch in process safe manner via sampler or shared_epoch + dataloader = data['train'].dataloader + num_batches_per_epoch = dataloader.num_batches // args.accum_freq + sample_digits = math.ceil(math.log(dataloader.num_samples + 1, 10)) + losses_m = {} + batch_time_m = AverageMeter() + data_time_m = AverageMeter() + end = time.time() + epoch_start_time = time.time() + for i, batch in enumerate(dataloader): + i_accum = i // args.accum_freq + step = num_batches_per_epoch * epoch + i_accum + if not args.skip_scheduler: + scheduler(step) + data_time_m.update(time.time() - end) + optimizer.zero_grad() + assert args.accum_freq == 1, "accum freq disabled" + with autocast(): + losses, batch_size, logit_scale = method(batch, model, teacher_model, vfm_model, feat_out, args) + total_loss = sum(losses.values()) + losses["loss"] = total_loss + backward(total_loss, scaler) + if scaler is not None: + if args.horovod: + optimizer.synchronize() + scaler.unscale_(optimizer) + if args.grad_clip_norm is not None: + torch.nn.utils.clip_grad_norm_(model.parameters(), args.grad_clip_norm, norm_type=2.0) + with optimizer.skip_synchronize(): + scaler.step(optimizer) + else: + if args.grad_clip_norm is not None: + scaler.unscale_(optimizer) + torch.nn.utils.clip_grad_norm_(model.parameters(), args.grad_clip_norm, norm_type=2.0) + scaler.step(optimizer) + scaler.update() + else: + if args.grad_clip_norm is not None: + torch.nn.utils.clip_grad_norm_(model.parameters(), args.grad_clip_norm, norm_type=2.0) + optimizer.step() + # Note: we clamp to 4.6052 = ln(100), as in the original paper. + with torch.no_grad(): + if args.distributed: + if args.proxy: + model.module.clip.logit_scale.clamp_(0, math.log(100)) + else: + model.module.logit_scale.clamp_(0, math.log(100)) + else: + if args.proxy: + model.clip.logit_scale.clamp_(0, math.log(100)) + else: + model.logit_scale.clamp_(0, math.log(100)) + batch_time_m.update(time.time() - end) + end = time.time() + batch_count = i_accum + 1 + + # compute the epoch remaining time + elapsed_time = time.time() - epoch_start_time + avg_iteration_time = elapsed_time / batch_count + remaining_iterations = num_batches_per_epoch - batch_count + estimated_remaining_time = avg_iteration_time * remaining_iterations + formatted_eta = format_time(estimated_remaining_time) + + if is_master(args) and (i_accum % args.log_every_n_steps == 0 or batch_count == num_batches_per_epoch): + # batch_size = len(images) + num_samples = batch_count * batch_size * args.accum_freq * args.world_size + samples_per_epoch = dataloader.num_samples + percent_complete = 100.0 * batch_count / num_batches_per_epoch + + # NOTE loss is coarsely sampled, just master node and per log update + for key, val in losses.items(): + if key not in losses_m: + losses_m[key] = AverageMeter() + losses_m[key].update(val.item(), batch_size) + + logit_scale_scalar = logit_scale.item() + loss_log = " ".join( + [ + f"{loss_name.capitalize()}: {loss_m.val:#.5g} ({loss_m.avg:#.5g})" + for loss_name, loss_m in losses_m.items() + ] + ) + samples_per_second = args.accum_freq * args.batch_size * args.world_size / batch_time_m.val + samples_per_second_per_gpu = args.accum_freq * args.batch_size / batch_time_m.val + logging.info( + f"Train Epoch: {epoch} [{num_samples:>{sample_digits}}/{samples_per_epoch} ({percent_complete:.0f}%)] " + f"ETA: {formatted_eta} " + f"Data (t): {data_time_m.avg:.3f} " + f"Batch (t): {batch_time_m.avg:.3f} " + f"LR: {optimizer.param_groups[0]['lr']:6f} "+ loss_log + ) + + # Save train loss / etc. Using non avg meter values as loggers have their own smoothing + log_data = { + "data_time": data_time_m.val, + "batch_time": batch_time_m.val, + "samples_per_second": samples_per_second, + "samples_per_second_per_gpu": samples_per_second_per_gpu, + "scale": logit_scale_scalar, + "lr": optimizer.param_groups[0]["lr"] + } + log_data.update({name:val.val for name,val in losses_m.items()}) + # resetting batch / data time meters per log window + batch_time_m.reset() + data_time_m.reset() + + +def evaluate(model, data, epoch, args): + metrics = {} + model.eval() + zero_shot_metrics = zero_shot_eval(model, data, epoch, args) + if not is_master(args): + return {} + metrics.update(zero_shot_metrics) + if not metrics: + return metrics + + keys = ''.join([f"{k}, " for k in metrics.keys() if 'all' in k])[:-2] + values = ''.join([f'{round(v, 4):.4f}, ' for k, v in metrics.items() if 'all' in k])[:-2] + + logging.info( + f"Eval Epoch: {epoch-1}. " + + f"{keys}: {values}." + ) + # TODO save the results as plots + logging.info(metrics) + + if args.save_logs: + with open(os.path.join(args.checkpoint_path, "results.json"), "a+") as f: + f.write(json.dumps(metrics)) + f.write("\n") + + return metrics diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/training/utils.py b/downstream/ProxyCLIP_TPAMI/clipself/src/training/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..961cd3314007041626efa2167e1af984df875752 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/training/utils.py @@ -0,0 +1,103 @@ + +import torch +import torch.nn.functional as F +import numpy as np +def contrastive_correlation_loss( + vfm_feats, + clip_feats, + samples = 20, + shift = 0.12): + """ + input: + vfm_self_attn_feats-> [bs,c,h,w] + clip_self_attn_feats->[bs,c,h,w] + return + pos_intra_loss + """ + coord_shape = [vfm_feats.shape[0], samples, samples, 2] + coords = torch.rand(coord_shape, device=vfm_feats.device) * 2 - 1 + sampled_vfm_feats = sample(vfm_feats, coords) + sampled_clip_feats = sample(clip_feats, coords) + with torch.no_grad(): + # Comes straight from backbone which is currently frozen. this saves mem. + normd_sampled_vfm_feats=norm(sampled_vfm_feats) + vfm_self_attn = tensor_correlation(normd_sampled_vfm_feats,normd_sampled_vfm_feats) + old_mean = vfm_self_attn.mean() + vfm_self_attn -= vfm_self_attn.mean([3, 4], keepdim=True) + vfm_self_attn = vfm_self_attn - vfm_self_attn.mean() + old_mean + normd_sampled_clip_feats=norm(sampled_clip_feats) + clip_self_attn = tensor_correlation(normd_sampled_clip_feats, normd_sampled_clip_feats) + min_val = 0.0 + loss = - clip_self_attn.clamp(min_val) * (vfm_self_attn - shift) + return loss.mean() + +def sample(t: torch.Tensor, coords: torch.Tensor): + return F.grid_sample(t, coords.permute(0, 2, 1, 3), padding_mode='border', align_corners=True) + +def tensor_correlation(a, b): + return torch.einsum("nchw,ncij->nhwij", a, b) + +def norm(t): + return F.normalize(t, dim=1, eps=1e-10) + +def mask2box(mask): + ys, xs = np.where(mask) + y0, y1 = ys.min(), ys.max() + x0, x1 = xs.min(), xs.max() + return x0, y0, x1, y1 + +def get_freeze_keys(args): + if args.model=="EVA02-CLIP-B-16": + if args.mode=="qk_vfm_distill": + freeze_keys=ViTB_16_QK_Distill_keys + elif args.mode=="ss_vfm_distill": + freeze_keys=ViTB_16_SS_Distill_keys + else: + freeze_keys=ViTB_16_Only_V_Distill_keys + else: + if args.mode=="qk_vfm_distill": + freeze_keys=ViTL_14_QK_Distill_keys + elif args.mode=="ss_vfm_distill": + freeze_keys=ViTL_14_SS_Distill_keys + else: + freeze_keys=ViTL_14_Only_V_Distill_keys + return freeze_keys + +BASE_ViTB_16_freeze_keys=[ + 'logit_scale', + 'visual.blocks.11.norm2.weight', + 'visual.blocks.11.norm2.bias', + 'visual.blocks.11.mlp.w1.weight', + 'visual.blocks.11.mlp.w1.bias', + 'visual.blocks.11.mlp.w2.weight', + 'visual.blocks.11.mlp.w2.bias', + 'visual.blocks.11.mlp.w3.weight', + 'visual.blocks.11.mlp.w3.bias', + 'visual.blocks.11.mlp.ffn_ln.weight', + 'visual.blocks.11.mlp.ffn_ln.bias'] +BASE_ViTL_14_freeze_keys=[ + 'logit_scale', + 'visual.blocks.23.norm2.weight', + 'visual.blocks.23.norm2.bias', + 'visual.blocks.23.mlp.w1.weight', + 'visual.blocks.23.mlp.w1.bias', + 'visual.blocks.23.mlp.w2.weight', + 'visual.blocks.23.mlp.w2.bias', + 'visual.blocks.23.mlp.w3.weight', + 'visual.blocks.23.mlp.w3.bias', + 'visual.blocks.23.mlp.ffn_ln.weight', + 'visual.blocks.23.mlp.ffn_ln.bias'] + +ViTB_16_SS_Distill_keys=['visual.blocks.11.attn.k_proj.weight'] + BASE_ViTB_16_freeze_keys +ViTL_14_SS_Distill_keys=['visual.blocks.23.attn.k_proj.weight'] + BASE_ViTL_14_freeze_keys + +ViTB_16_Only_V_Distill_keys=['visual.blocks.11.attn.q_bias', + 'visual.blocks.11.attn.q_proj.weight', + 'visual.blocks.11.attn.k_proj.weight',] + BASE_ViTB_16_freeze_keys + +ViTL_14_Only_V_Distill_keys=['visual.blocks.23.attn.q_bias', + 'visual.blocks.23.attn.q_proj.weight', + 'visual.blocks.23.attn.k_proj.weight',] + BASE_ViTL_14_freeze_keys + +ViTB_16_QK_Distill_keys = BASE_ViTB_16_freeze_keys +ViTL_14_QK_Distill_keys = BASE_ViTL_14_freeze_keys \ No newline at end of file diff --git a/downstream/ProxyCLIP_TPAMI/clipself/src/training/zero_shot.py b/downstream/ProxyCLIP_TPAMI/clipself/src/training/zero_shot.py new file mode 100644 index 0000000000000000000000000000000000000000..d15972a7e678b4c967336794d6d68a533a33dac1 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/clipself/src/training/zero_shot.py @@ -0,0 +1,216 @@ +import logging +from featup.util import UnNormalize +import torch +import torch.nn.functional as F +from training.dist_utils import all_gather +from tqdm import tqdm +from .distributed import is_master +from open_clip import get_cast_dtype +from .precision import get_autocast +import torch.nn as nn +from torchvision import transforms +from src.segment_anything import sam_model_registry + +def run(model, dataloader, args): + cls_embeddings = dataloader.dataset.embeddings + cls_embeddings = F.normalize(torch.from_numpy(cls_embeddings).float(), dim=-1) + cls_embeddings = cls_embeddings.to(args.device) + autocast = get_autocast(args.precision) + cast_dtype = get_cast_dtype(args.precision) + if cast_dtype is not None: + cls_embeddings = cls_embeddings.to(dtype=cast_dtype) + if args.mode=="ss_vfm_distill": + inference_mode="ss" + elif args.mode=="only_v_distill": + inference_mode="only_v" + else: + inference_mode="qk" + with torch.no_grad(): + correct_rois = [] + correct_maskpool = [] + correct_crops = [] + similarity_crops = [] + similarity_rois = [] + similarity_maskpool = [] + all_box_sizes = [] + all_is_thing = [] + all_cls_labels = [] + # if args.proxy: + # if args.proxy=="sam": + # vfm = sam_model_registry["vit_b"](checkpoint="/mnt/SSD8T/home/wjj/code/ProxyCLIP/sam_ckpts/sam_vit_b_01ec64.pth").half().to(args.device).eval() + # elif args.proxy=="dino": + # vfm = torch.hub.load('facebookresearch/dino:main', 'dino_vitb8').half().to(args.device).eval() + # # vfm = torch.hub.load('facebookresearch/dino:main', 'dino_vitb16').half().to(args.device) + # elif args.proxy == 'dinov2': + # # self.vfm = torch.hub.load('facebookresearch/dinov2', 'dinov2_vits14_reg') + # vfm = torch.hub.load('facebookresearch/dinov2', 'dinov2_vitb14_reg').half().to(args.device).eval() + # else: + # print("vlm_model not supported") + # exit(0) + # for p in vfm.parameters(): + # p.requires_grad = False + for _, images, bboxes, image_crops, gt_masks, masked_image_crops,proxy_imgs in tqdm(dataloader, disable=not is_master(args)): + images = images.to(args.device) + bboxes = bboxes.to(args.device) + image_crops = image_crops.to(args.device) + masked_image_crops = masked_image_crops.to(args.device) + gt_masks = gt_masks.to(args.device) + if cast_dtype is not None: + images = images.to(dtype=cast_dtype) + bboxes = bboxes.to(dtype=cast_dtype) + image_crops = image_crops.to(dtype=cast_dtype) + masked_image_crops = masked_image_crops.to(dtype=cast_dtype) + gt_masks = gt_masks.to(dtype=cast_dtype) + image_crops_list = [] + gt_masks_list = [] + cls_labels = [] + rois = [] + box_sizes = [] + is_thing = [] + for bboxes_per_image, crops_per_image, gt_mask, masked_crops_per_image \ + in zip(bboxes, image_crops, gt_masks, masked_image_crops): + valid = bboxes_per_image[:, 5] > 0.5 + rois.append(bboxes_per_image[valid, :4]) + cls_labels.append(bboxes_per_image[valid, 4]) + image_crops_list.append(crops_per_image[valid]) + gt_masks_list.append(gt_mask[valid]) + box_sizes.append(bboxes_per_image[valid, 6]) + is_thing.append(bboxes_per_image[valid, 7]) + cls_labels = torch.cat(cls_labels, dim=0).to(torch.long) + if cls_labels.shape[0] == 0: + continue + image_crops = torch.cat(image_crops_list) + box_sizes = torch.cat(box_sizes, dim=0).float() + is_thing = torch.cat(is_thing, dim=0) + all_box_sizes.append(box_sizes) + all_is_thing.append(is_thing) + with autocast(): + # predict + module = model + roi_extractor = module.encode_pseudo_boxes + mask_pooler = module.encode_masks + roi_features = roi_extractor(images, + rois, + normalize=True, + extract_type=args.extract_type, + mode=inference_mode) + maskpool_features = mask_pooler(images, gt_masks_list, + normalize=True, + mask_attn=args.extract_type == "v1", + mode=inference_mode) + # New way to obtain crop features + if args.image_ave_pool: + feature_map = module.visual.encode_dense(image_crops, keep_shape=True) + crop_features = feature_map.mean(dim=(-2, -1)) + crop_features = F.normalize(crop_features, dim=-1) + else: + crop_features = module.encode_image(image_crops, normalize=True) + + if cast_dtype is not None: + roi_features = roi_features.to(dtype=cast_dtype) + crop_features = crop_features.to(dtype=cast_dtype) + maskpool_features = maskpool_features.to(dtype=cast_dtype) + + roi_logits = roi_features @ cls_embeddings.T + crop_logits = crop_features @ cls_embeddings.T + maskpool_logits = maskpool_features @ cls_embeddings.T + + _, roi_top5_inds = roi_logits.topk(5) + _, crop_top5_inds = crop_logits.topk(5) + _, maskpool_top5_inds = maskpool_logits.topk(5) + correct_rois.append(roi_top5_inds == cls_labels.view(-1, 1)) + correct_crops.append(crop_top5_inds == cls_labels.view(-1, 1)) + correct_maskpool.append(maskpool_top5_inds == cls_labels.view(-1, 1)) + + similarity_rois.append(torch.gather(roi_logits, dim=1, index=cls_labels.view(-1, 1))[:, 0]) + similarity_crops.append(torch.gather(crop_logits, dim=1, index=cls_labels.view(-1, 1))[:, 0]) + similarity_maskpool.append(torch.gather(maskpool_logits, dim=1, index=cls_labels.view(-1, 1))[:, 0]) + + all_cls_labels.append(cls_labels) + # TODO: gather correct matrix across gpus + correct_rois = torch.cat(correct_rois).float() + correct_crops = torch.cat(correct_crops).float() + correct_maskpool = torch.cat(correct_maskpool).float() + similarity_rois = torch.cat(similarity_rois).float() + similarity_crops = torch.cat(similarity_crops).float() + similarity_maskpool = torch.cat(similarity_maskpool).float() + all_box_sizes = torch.cat(all_box_sizes) + all_is_thing = torch.cat(all_is_thing) + all_cls_labels = torch.cat(all_cls_labels) + if args.distributed and not args.horovod: + correct_rois = multi_gpu_sync(correct_rois) + correct_crops = multi_gpu_sync(correct_crops) + correct_maskpool = multi_gpu_sync(correct_maskpool) + all_box_sizes = multi_gpu_sync(all_box_sizes) + all_is_thing = multi_gpu_sync(all_is_thing) + similarity_rois = multi_gpu_sync(similarity_rois) + similarity_crops = multi_gpu_sync(similarity_crops) + similarity_maskpool = multi_gpu_sync(similarity_maskpool) + all_cls_labels = multi_gpu_sync(all_cls_labels) + + return correct_rois, correct_crops, correct_maskpool, \ + similarity_rois, similarity_crops, similarity_maskpool, \ + all_box_sizes, all_is_thing, all_cls_labels + + +def multi_gpu_sync(x): + device = x.device + x_list = all_gather(x.cpu()) + x = torch.cat([res.to(device) for res in x_list]) + return x + + +def macc_with_is_thing(correct_matrix, is_thing, all_cls_labels, prefix): + def _macc(corrects, cls_labels): + min_id = cls_labels.min().item() + max_id = cls_labels.max().item() + cand_labels = list(range(min_id, max_id+1)) + + acc_per_cls = [] + + for lb in cand_labels: + corrects_per_cls = corrects[cls_labels == lb] + if corrects_per_cls.shape[0] == 0: + continue + acc_per_cls.append(corrects_per_cls.mean().half().item()) + + return sum(acc_per_cls) / len(acc_per_cls) + + results = {} + thing_correct_matrix = correct_matrix[is_thing > 0] + stuff_correct_matrix = correct_matrix[is_thing < 1] + + thing_cls_labels = all_cls_labels[is_thing > 0].long() + stuff_cls_labels = all_cls_labels[is_thing < 1].long() + + thing_top1_acc = _macc(thing_correct_matrix[:, 0], thing_cls_labels) + thing_top5_acc = _macc(thing_correct_matrix.sum(-1), thing_cls_labels) + + stuff_top1_acc = _macc(stuff_correct_matrix[:, 0], stuff_cls_labels) + stuff_top5_acc = _macc(stuff_correct_matrix.sum(-1), stuff_cls_labels) + + results[f'{prefix}.thing.macc1'] = thing_top1_acc + results[f'{prefix}.thing.macc5'] = thing_top5_acc + results[f'{prefix}.stuff.macc1'] = stuff_top1_acc + results[f'{prefix}.stuff.macc5'] = stuff_top5_acc + + return results + + +def zero_shot_eval(model, data, epoch, args): + if 'val' not in data: + return {} + if args.zeroshot_frequency == 0: + return {} + if (epoch % args.zeroshot_frequency) != 0 and epoch != args.epochs: + return {} + logging.info('Region classifier') + results = {} + correct_rois, correct_crops, correct_maskpool, \ + similarity_rois, similarity_crops, similarity_maskpool, \ + all_box_sizes, all_is_thing, all_cls_labels = run(model, data['val'].dataloader, args) + results.update(macc_with_is_thing(correct_rois, all_is_thing, all_cls_labels, 'rois')) + results.update(macc_with_is_thing(correct_crops, all_is_thing, all_cls_labels, 'crops')) + results.update(macc_with_is_thing(correct_maskpool, all_is_thing, all_cls_labels, 'maskpool')) + + return results diff --git a/downstream/ProxyCLIP_TPAMI/configs/eva_clip/base_config.py b/downstream/ProxyCLIP_TPAMI/configs/eva_clip/base_config.py new file mode 100644 index 0000000000000000000000000000000000000000..bb32a777bc059d389ff17eed2aeb15066623fea3 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/configs/eva_clip/base_config.py @@ -0,0 +1,37 @@ +# CLIP baseline configurations (vanilla attention) +model = dict( + type='DeCLIPSegmentation', + clip_type='EVA02-CLIP-B-16', + # CLIP baseline - vanilla attention + checkpoint='/opt/tiger/xiaomoguhzz/EVA02_CLIP_B_psz16_s8B.pt', + mode='vanilla', # CLIP 使用 vanilla attention + pretrained='eva', +) + +test_evaluator = dict(type='IoUMetric', iou_metrics=['mIoU']) + +default_scope = 'mmseg' +env_cfg = dict( + cudnn_benchmark=True, + mp_cfg=dict(mp_start_method='fork', opencv_num_threads=0), + dist_cfg=dict(backend='nccl'), +) +vis_backends = [dict(type='LocalVisBackend')] +visualizer = dict( + type='SegLocalVisualizer', vis_backends=vis_backends, alpha=1.0, name='visualizer') +log_processor = dict(by_epoch=False) +log_level = 'INFO' +load_from = None +resume = False + +test_cfg = dict(type='TestLoop') + +default_hooks = dict( + timer=dict(type='IterTimerHook'), + logger=dict(type='LoggerHook', interval=50, log_metric_by_epoch=False), + param_scheduler=dict(type='ParamSchedulerHook'), + checkpoint=dict(type='CheckpointHook', by_epoch=False, interval=2000), + sampler_seed=dict(type='DistSamplerSeedHook'), + visualization=dict(type='SegVisualizationHook', + draw=False, + interval=100)) diff --git a/downstream/ProxyCLIP_TPAMI/configs/eva_clip/cfg_ade20k.py b/downstream/ProxyCLIP_TPAMI/configs/eva_clip/cfg_ade20k.py new file mode 100644 index 0000000000000000000000000000000000000000..f910d7be54717b3adc1cc4e93070205b9a9ac3a3 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/configs/eva_clip/cfg_ade20k.py @@ -0,0 +1,38 @@ +_base_ = './base_config.py' + +# model settings - CLIP baseline (vanilla attention) +model = dict( + name_path='./configs/proxyclip/cls_ade20k.txt', + vfm=None, + type='DeCLIPSegmentation', + clip_type='EVA02-CLIP-B-16', + pretrained='eva', + checkpoint='/opt/tiger/xiaomoguhzz/EVA02_CLIP_B_psz16_s8B.pt', + mode='vanilla', +) + +# dataset settings +dataset_type = 'ADE20KDataset' +data_root = '/opt/tiger/xiaomoguhzz/dataset/ADEChallengeData2016' + +test_pipeline = [ + dict(type='LoadImageFromFile'), + dict(type='Resize', scale=(4096, 448), keep_ratio=True), + dict(type='LoadAnnotations', reduce_zero_label=True), + dict(type='PackSegInputs', meta_keys=('img_path', 'seg_map_path', 'ori_shape', + 'img_shape', 'pad_shape', 'scale_factor', 'flip', + 'flip_direction', 'reduce_zero_label','resize_shape')) +] + +test_dataloader = dict( + batch_size=1, + num_workers=4, + persistent_workers=True, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + data_prefix=dict( + img_path='images/validation', + seg_map_path='annotations/validation'), + pipeline=test_pipeline)) diff --git a/downstream/ProxyCLIP_TPAMI/configs/eva_clip/cfg_city_scapes.py b/downstream/ProxyCLIP_TPAMI/configs/eva_clip/cfg_city_scapes.py new file mode 100644 index 0000000000000000000000000000000000000000..a309f98799508dfb6075b377f7adaff87e44570c --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/configs/eva_clip/cfg_city_scapes.py @@ -0,0 +1,37 @@ +_base_ = './base_config.py' + +# model settings - CLIP baseline (vanilla attention) +model = dict( + name_path='./configs/proxyclip/cls_city_scapes.txt', + vfm=None, + type='DeCLIPSegmentation', + clip_type='EVA02-CLIP-B-16', + pretrained='eva', + checkpoint='/opt/tiger/xiaomoguhzz/EVA02_CLIP_B_psz16_s8B.pt', + mode='vanilla', +) + +# dataset settings +dataset_type = 'CityscapesDataset' +data_root = '/opt/tiger/xiaomoguhzz/dataset/cityscapes' + +test_pipeline = [ + dict(type='LoadImageFromFile'), + dict(type='Resize', scale=(4096, 560), keep_ratio=True), + dict(type='LoadAnnotations'), + dict(type='PackSegInputs', meta_keys=('img_path', 'seg_map_path', 'ori_shape', + 'img_shape', 'pad_shape', 'scale_factor', 'flip', + 'flip_direction', 'reduce_zero_label','resize_shape')) +] + +test_dataloader = dict( + batch_size=1, + num_workers=4, + persistent_workers=True, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + data_prefix=dict( + img_path='leftImg8bit/val', seg_map_path='gtFine/val'), + pipeline=test_pipeline)) diff --git a/downstream/ProxyCLIP_TPAMI/configs/eva_clip/cfg_coco_object.py b/downstream/ProxyCLIP_TPAMI/configs/eva_clip/cfg_coco_object.py new file mode 100644 index 0000000000000000000000000000000000000000..3fba621d740347dee838f90d3829dbaeffc39702 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/configs/eva_clip/cfg_coco_object.py @@ -0,0 +1,39 @@ +_base_ = './base_config.py' + +# model settings - CLIP baseline (vanilla attention) +model = dict( + name_path='./configs/proxyclip/cls_coco_object.txt', + vfm=None, + type='DeCLIPSegmentation', + clip_type='EVA02-CLIP-B-16', + pretrained='eva', + checkpoint='/opt/tiger/xiaomoguhzz/EVA02_CLIP_B_psz16_s8B.pt', + mode='vanilla', + prob_thd=0.3, +) + +# dataset settings +dataset_type = 'COCOObjectDataset' +data_root = '/opt/tiger/xiaomoguhzz/dataset/coco_obj' + +test_pipeline = [ + dict(type='LoadImageFromFile'), + dict(type='Resize', scale=(2048, 448), keep_ratio=True), + dict(type='LoadAnnotations'), + dict(type='PackSegInputs', meta_keys=('img_path', 'seg_map_path', 'ori_shape', + 'img_shape', 'pad_shape', 'scale_factor', 'flip', + 'flip_direction', 'reduce_zero_label','resize_shape')) +] + +test_dataloader = dict( + batch_size=1, + num_workers=4, + persistent_workers=True, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + reduce_zero_label=False, + data_prefix=dict( + img_path='images/val2017', seg_map_path='annotations/val2017'), + pipeline=test_pipeline)) diff --git a/downstream/ProxyCLIP_TPAMI/configs/eva_clip/cfg_coco_stuff164k.py b/downstream/ProxyCLIP_TPAMI/configs/eva_clip/cfg_coco_stuff164k.py new file mode 100644 index 0000000000000000000000000000000000000000..d6432ed702c7f178e34a43d043b96673bfd87295 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/configs/eva_clip/cfg_coco_stuff164k.py @@ -0,0 +1,38 @@ +_base_ = './base_config.py' + +# model settings - CLIP baseline (vanilla attention) +model = dict( + name_path='./configs/proxyclip/cls_coco_stuff.txt', + vfm=None, + type='DeCLIPSegmentation', + clip_type='EVA02-CLIP-B-16', + pretrained='eva', + checkpoint='/opt/tiger/xiaomoguhzz/EVA02_CLIP_B_psz16_s8B.pt', + mode='vanilla', # CLIP 使用 vanilla attention +) + +# dataset settings +dataset_type = 'COCOStuffDataset' +data_root = '' + +test_pipeline = [ + dict(type='LoadImageFromFile'), + dict(type='Resize', scale=(4096, 448), keep_ratio=True), + dict(type='LoadAnnotations'), + dict(type='PackSegInputs', meta_keys=('img_path', 'seg_map_path', 'ori_shape', + 'img_shape', 'pad_shape', 'scale_factor', 'flip', + 'flip_direction', 'reduce_zero_label','resize_shape')) + ] + +test_dataloader = dict( + batch_size=1, + num_workers=4, + persistent_workers=True, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + data_prefix=dict( + img_path='/opt/tiger/xiaomoguhzz/standard_coco/val2017', + seg_map_path='/opt/tiger/xiaomoguhzz/standard_coco/annotations/val2017'), + pipeline=test_pipeline)) diff --git a/downstream/ProxyCLIP_TPAMI/configs/eva_clip/cfg_context59.py b/downstream/ProxyCLIP_TPAMI/configs/eva_clip/cfg_context59.py new file mode 100644 index 0000000000000000000000000000000000000000..9fa4f5ed4ddd0d8cdbdc09a26680f93846bf8909 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/configs/eva_clip/cfg_context59.py @@ -0,0 +1,38 @@ +_base_ = './base_config.py' + +# model settings - CLIP baseline (vanilla attention) +model = dict( + name_path='./configs/proxyclip/cls_context59.txt', + vfm=None, + type='DeCLIPSegmentation', + clip_type='EVA02-CLIP-B-16', + pretrained='eva', + checkpoint='/opt/tiger/xiaomoguhzz/EVA02_CLIP_B_psz16_s8B.pt', + mode='vanilla', +) + +# dataset settings +dataset_type = 'PascalContext59Dataset' +data_root = '/opt/tiger/xiaomoguhzz/dataset/VOCdevkit/VOC2010' + +test_pipeline = [ + dict(type='LoadImageFromFile'), + dict(type='Resize', scale=(4096, 448), keep_ratio=True), + dict(type='LoadAnnotations', reduce_zero_label=True), + dict(type='PackSegInputs', meta_keys=('img_path', 'seg_map_path', 'ori_shape', + 'img_shape', 'pad_shape', 'scale_factor', 'flip', + 'flip_direction', 'reduce_zero_label','resize_shape')) +] + +test_dataloader = dict( + batch_size=1, + num_workers=4, + persistent_workers=True, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + data_prefix=dict( + img_path='JPEGImages', seg_map_path='SegmentationClassContext'), + ann_file='ImageSets/SegmentationContext/val.txt', + pipeline=test_pipeline)) diff --git a/downstream/ProxyCLIP_TPAMI/configs/eva_clip/cfg_context60.py b/downstream/ProxyCLIP_TPAMI/configs/eva_clip/cfg_context60.py new file mode 100644 index 0000000000000000000000000000000000000000..b29f48f109a8c643e67db26deec3a515ae47e73a --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/configs/eva_clip/cfg_context60.py @@ -0,0 +1,40 @@ +_base_ = './base_config.py' + +# model settings - CLIP baseline (vanilla attention) +model = dict( + name_path='./configs/proxyclip/cls_context60.txt', + vfm=None, + type='DeCLIPSegmentation', + clip_type='EVA02-CLIP-B-16', + pretrained='eva', + checkpoint='/opt/tiger/xiaomoguhzz/EVA02_CLIP_B_psz16_s8B.pt', + mode='vanilla', + prob_thd=0.15, + logit_scale=40, +) + +# dataset settings +dataset_type = 'PascalContext60Dataset' +data_root = '/opt/tiger/xiaomoguhzz/dataset/VOCdevkit/VOC2010' + +test_pipeline = [ + dict(type='LoadImageFromFile'), + dict(type='Resize', scale=(4096, 448), keep_ratio=True), + dict(type='LoadAnnotations'), + dict(type='PackSegInputs', meta_keys=('img_path', 'seg_map_path', 'ori_shape', + 'img_shape', 'pad_shape', 'scale_factor', 'flip', + 'flip_direction', 'reduce_zero_label','resize_shape')) +] + +test_dataloader = dict( + batch_size=1, + num_workers=4, + persistent_workers=True, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + data_prefix=dict( + img_path='JPEGImages', seg_map_path='SegmentationClassContext'), + ann_file='ImageSets/SegmentationContext/val.txt', + pipeline=test_pipeline)) diff --git a/downstream/ProxyCLIP_TPAMI/configs/eva_clip/cfg_voc20.py b/downstream/ProxyCLIP_TPAMI/configs/eva_clip/cfg_voc20.py new file mode 100644 index 0000000000000000000000000000000000000000..a192a631d2d79bc74b7ecc73f063d0ab83ce5309 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/configs/eva_clip/cfg_voc20.py @@ -0,0 +1,38 @@ +_base_ = './base_config.py' + +# model settings - CLIP baseline (vanilla attention) +model = dict( + name_path='./configs/proxyclip/cls_voc20.txt', + vfm=None, + type='DeCLIPSegmentation', + clip_type='EVA02-CLIP-B-16', + pretrained='eva', + checkpoint='/opt/tiger/xiaomoguhzz/EVA02_CLIP_B_psz16_s8B.pt', + mode='vanilla', +) + +# dataset settings +dataset_type = 'PascalVOC20Dataset' +data_root = '/opt/tiger/xiaomoguhzz/dataset/VOCdevkit/VOC2012' + +test_pipeline = [ + dict(type='LoadImageFromFile'), + dict(type='Resize', scale=(4096, 448), keep_ratio=True), + dict(type='LoadAnnotations'), + dict(type='PackSegInputs', meta_keys=('img_path', 'seg_map_path', 'ori_shape', + 'img_shape', 'pad_shape', 'scale_factor', 'flip', + 'flip_direction', 'reduce_zero_label','resize_shape')) +] + +test_dataloader = dict( + batch_size=1, + num_workers=4, + persistent_workers=True, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + data_prefix=dict( + img_path='JPEGImages', seg_map_path='SegmentationClass'), + ann_file='ImageSets/Segmentation/val.txt', + pipeline=test_pipeline)) diff --git a/downstream/ProxyCLIP_TPAMI/configs/eva_clip/cfg_voc21.py b/downstream/ProxyCLIP_TPAMI/configs/eva_clip/cfg_voc21.py new file mode 100644 index 0000000000000000000000000000000000000000..ced5913e79acc694714cddd94c53966b1fc2507a --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/configs/eva_clip/cfg_voc21.py @@ -0,0 +1,40 @@ +_base_ = './base_config.py' + +# model settings - CLIP baseline (vanilla attention) +model = dict( + name_path='./configs/proxyclip/cls_voc21.txt', + vfm=None, + type='DeCLIPSegmentation', + clip_type='EVA02-CLIP-B-16', + pretrained='eva', + checkpoint='/opt/tiger/xiaomoguhzz/EVA02_CLIP_B_psz16_s8B.pt', + mode='vanilla', + prob_thd=0.5, + logit_scale=80, +) + +# dataset settings +dataset_type = 'PascalVOCDataset' +data_root = '/opt/tiger/xiaomoguhzz/dataset/VOCdevkit/VOC2012' + +test_pipeline = [ + dict(type='LoadImageFromFile'), + dict(type='Resize', scale=(4096, 448), keep_ratio=True), + dict(type='LoadAnnotations'), + dict(type='PackSegInputs', meta_keys=('img_path', 'seg_map_path', 'ori_shape', + 'img_shape', 'pad_shape', 'scale_factor', 'flip', + 'flip_direction', 'reduce_zero_label','resize_shape')) +] + +test_dataloader = dict( + batch_size=1, + num_workers=4, + persistent_workers=True, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + data_prefix=dict( + img_path='JPEGImages', seg_map_path='SegmentationClass'), + ann_file='ImageSets/Segmentation/val.txt', + pipeline=test_pipeline)) diff --git a/downstream/ProxyCLIP_TPAMI/configs/eva_declip/base_config.py b/downstream/ProxyCLIP_TPAMI/configs/eva_declip/base_config.py new file mode 100644 index 0000000000000000000000000000000000000000..cd3da9548e7d1ea4e0ca7387ce680b7878ec1ea9 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/configs/eva_declip/base_config.py @@ -0,0 +1,35 @@ +# base configurations +model = dict( + type='DeCLIPSegmentation', + clip_type='EVA02-CLIP-B-16', + # DeCLIP checkpoint - 正确路径 + checkpoint='/mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/logs/declip_plus_seg/epoch_6.pt', +) + +test_evaluator = dict(type='IoUMetric', iou_metrics=['mIoU']) + +default_scope = 'mmseg' +env_cfg = dict( + cudnn_benchmark=True, + mp_cfg=dict(mp_start_method='fork', opencv_num_threads=0), + dist_cfg=dict(backend='nccl'), +) +vis_backends = [dict(type='LocalVisBackend')] +visualizer = dict( + type='SegLocalVisualizer', vis_backends=vis_backends, alpha=1.0, name='visualizer') +log_processor = dict(by_epoch=False) +log_level = 'INFO' +load_from = None +resume = False + +test_cfg = dict(type='TestLoop') + +default_hooks = dict( + timer=dict(type='IterTimerHook'), + logger=dict(type='LoggerHook', interval=50, log_metric_by_epoch=False), + param_scheduler=dict(type='ParamSchedulerHook'), + checkpoint=dict(type='CheckpointHook', by_epoch=False, interval=2000), + sampler_seed=dict(type='DistSamplerSeedHook'), + visualization=dict(type='SegVisualizationHook', + draw=False, + interval=100)) \ No newline at end of file diff --git a/downstream/ProxyCLIP_TPAMI/configs/eva_declip/cfg_ade20k.py b/downstream/ProxyCLIP_TPAMI/configs/eva_declip/cfg_ade20k.py new file mode 100644 index 0000000000000000000000000000000000000000..33fb1d9214903bea4e85ead6d1961bdce0096a6c --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/configs/eva_declip/cfg_ade20k.py @@ -0,0 +1,50 @@ +_base_ = './base_config.py' + +# model settings + +# model = dict( +# name_path='./configs/proxyclip/cls_ade20k.txt', +# vfm=None, +# type='DeCLIPSegmentation', +# clip_type='EVA02-CLIP-B-16', +# pretrained='eva', +# checkpoint='/mnt/SSD8T/home/wjj/code/decoupledCLIP/logs/OVS/eva_dinov2B_csa_560_0.25_1.0/checkpoints/epoch_6.pt', +# mode="csa", +# ) + +model = dict( + name_path='./configs/proxyclip/cls_ade20k.txt', + vfm=None, + type='DeCLIPSegmentation', + clip_type='EVA02-CLIP-B-16', + pretrained='eva', + checkpoint="/mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/logs/declip_plus_seg/epoch_6.pt", + mode="csa", +) + + +# dataset settings +dataset_type = 'ADE20KDataset' +data_root = '/opt/tiger/xiaomoguhzz/dataset/ADEChallengeData2016' + +test_pipeline = [ + dict(type='LoadImageFromFile'), + dict(type='Resize', scale=(4096, 448), keep_ratio=True), + dict(type='LoadAnnotations', reduce_zero_label=True), + dict(type='PackSegInputs', meta_keys=('img_path', 'seg_map_path', 'ori_shape', + 'img_shape', 'pad_shape', 'scale_factor', 'flip', + 'flip_direction', 'reduce_zero_label','resize_shape')) +] + +test_dataloader = dict( + batch_size=1, + num_workers=4, + persistent_workers=True, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + data_prefix=dict( + img_path='images/validation', + seg_map_path='annotations/validation'), + pipeline=test_pipeline)) \ No newline at end of file diff --git a/downstream/ProxyCLIP_TPAMI/configs/eva_declip/cfg_city_scapes.py b/downstream/ProxyCLIP_TPAMI/configs/eva_declip/cfg_city_scapes.py new file mode 100644 index 0000000000000000000000000000000000000000..3ce57ebfcdc6be0856aab566fc26fa89527ea2db --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/configs/eva_declip/cfg_city_scapes.py @@ -0,0 +1,51 @@ +_base_ = './base_config.py' +# model settings +# model = dict( +# name_path='./configs/proxyclip/cls_city_scapes.txt', +# slide_stride=112, +# slide_crop=336, +# vfm=None, +# type='DeCLIPSegmentation', +# clip_type='EVA02-CLIP-B-16', +# pretrained='eva', +# checkpoint='/mnt/SSD8T/home/wjj/code/decoupledCLIP/logs/OVS/eva_dinov2B_560_0.25_scale/checkpoints/epoch_6.pt', +# mode="qq", +# ) + +model = dict( + name_path='./configs/proxyclip/cls_city_scapes.txt', + vfm=None, + type='DeCLIPSegmentation', + clip_type='EVA02-CLIP-B-16', + pretrained='eva', + checkpoint="/mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/logs/declip_plus_seg/epoch_6.pt", + mode="csa", +) + + +# dataset settings +dataset_type = 'CityscapesDataset' +data_root = '/opt/tiger/xiaomoguhzz/dataset/cityscapes' + +test_pipeline = [ + dict(type='LoadImageFromFile'), + dict(type='Resize', scale=(4096, 560), keep_ratio=True), + # add loading annotation after ``Resize`` because ground truth + # does not need to do resize data transform + dict(type='LoadAnnotations'), + dict(type='PackSegInputs', meta_keys=('img_path', 'seg_map_path', 'ori_shape', + 'img_shape', 'pad_shape', 'scale_factor', 'flip', + 'flip_direction', 'reduce_zero_label','resize_shape')) +] + +test_dataloader = dict( + batch_size=1, + num_workers=4, + persistent_workers=True, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + data_prefix=dict( + img_path='leftImg8bit/val', seg_map_path='gtFine/val'), + pipeline=test_pipeline)) \ No newline at end of file diff --git a/downstream/ProxyCLIP_TPAMI/configs/eva_declip/cfg_coco_object.py b/downstream/ProxyCLIP_TPAMI/configs/eva_declip/cfg_coco_object.py new file mode 100644 index 0000000000000000000000000000000000000000..fe3e5de67d78cd16b66f11d7491cd25610d8f628 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/configs/eva_declip/cfg_coco_object.py @@ -0,0 +1,61 @@ +_base_ = './base_config.py' + +# model settings +# model = dict( +# name_path='./configs/proxyclip/cls_coco_object.txt', +# vfm=None, +# type='DeCLIPSegmentation', +# clip_type='EVA02-CLIP-B-16', +# pretrained='eva', +# checkpoint='/mnt/SSD8T/home/wjj/code/decoupledCLIP/logs/eva_dinov2_560_0.25_w/scale/checkpoints/epoch_6.pt', +# mode="qq", +# prob_thd=0.25, # 0.25 OURS 0.1 CLIP +# ) + +# model = dict( +# name_path='./configs/proxyclip/cls_coco_object.txt', +# vfm=None, +# type='DeCLIPSegmentation', +# clip_type='EVA02-CLIP-B-16', +# pretrained='eva', +# checkpoint="/mnt/SSD8T/home/wjj/code/DeCLIP/logs/EVAB_dinov2B_csa_560_plus_exp90/checkpoints/epoch_6.pt", +# mode="csa", +# prob_thd=0.2, +# ) + + +model = dict( + name_path='./configs/proxyclip/cls_coco_object.txt', + vfm=None, + type='DeCLIPSegmentation', + clip_type='EVA02-CLIP-B-16', + pretrained='eva', + checkpoint="/mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/logs/declip_plus_seg/epoch_6.pt", + mode="csa", + prob_thd=0.3, # 0.3 +) +# dataset settings +dataset_type = 'COCOObjectDataset' +data_root = '/opt/tiger/xiaomoguhzz/dataset/coco_obj' + +test_pipeline = [ + dict(type='LoadImageFromFile'), + dict(type='Resize', scale=(2048, 448), keep_ratio=True), + dict(type='LoadAnnotations'), + dict(type='PackSegInputs', meta_keys=('img_path', 'seg_map_path', 'ori_shape', + 'img_shape', 'pad_shape', 'scale_factor', 'flip', + 'flip_direction', 'reduce_zero_label','resize_shape')) +] + +test_dataloader = dict( + batch_size=1, + num_workers=4, + persistent_workers=True, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + reduce_zero_label=False, + data_prefix=dict( + img_path='images/val2017', seg_map_path='annotations/val2017'), + pipeline=test_pipeline)) \ No newline at end of file diff --git a/downstream/ProxyCLIP_TPAMI/configs/eva_declip/cfg_coco_stuff164k.py b/downstream/ProxyCLIP_TPAMI/configs/eva_declip/cfg_coco_stuff164k.py new file mode 100644 index 0000000000000000000000000000000000000000..b3d73e0f3f330b869e09b5f8543b2cb4707aa80c --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/configs/eva_declip/cfg_coco_stuff164k.py @@ -0,0 +1,49 @@ +_base_ = './base_config.py' + +# model settings +# model = dict( +# name_path='./configs/proxyclip/cls_coco_stuff.txt', +# vfm=None, +# type='DeCLIPSegmentation', +# clip_type='EVA02-CLIP-B-16', +# pretrained='eva', +# checkpoint='/mnt/SSD8T/home/wjj/code/decoupledCLIP/logs/OVS/eva_dinov2B_csa_560_0.25_1.0/checkpoints/epoch_6.pt', +# mode="csa", +# ) + +model = dict( + name_path='./configs/proxyclip/cls_coco_stuff.txt', + vfm=None, + type='DeCLIPSegmentation', + clip_type='EVA02-CLIP-B-16', + pretrained='eva', + # DeCLIP checkpoint - 正确路径 + checkpoint='/mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/logs/declip_plus_seg/epoch_6.pt', + mode='csa', +) + +# dataset settings +dataset_type = 'COCOStuffDataset' +data_root = '' + +test_pipeline = [ + dict(type='LoadImageFromFile'), + dict(type='Resize', scale=(4096, 448), keep_ratio=True), + dict(type='LoadAnnotations'), + dict(type='PackSegInputs', meta_keys=('img_path', 'seg_map_path', 'ori_shape', + 'img_shape', 'pad_shape', 'scale_factor', 'flip', + 'flip_direction', 'reduce_zero_label','resize_shape')) + ] + +test_dataloader = dict( + batch_size=1, + num_workers=4, + persistent_workers=True, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + data_prefix=dict( + img_path='/opt/tiger/xiaomoguhzz/standard_coco/val2017', + seg_map_path='/opt/tiger/xiaomoguhzz/standard_coco/annotations/val2017'), + pipeline=test_pipeline)) diff --git a/downstream/ProxyCLIP_TPAMI/configs/eva_declip/cfg_context59.py b/downstream/ProxyCLIP_TPAMI/configs/eva_declip/cfg_context59.py new file mode 100644 index 0000000000000000000000000000000000000000..cad16d870361c142a9e50766486f2f12b5966c93 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/configs/eva_declip/cfg_context59.py @@ -0,0 +1,48 @@ +_base_ = './base_config.py' + +# model settings +# model = dict( +# name_path='./configs/proxyclip/cls_context59.txt', +# vfm=None, +# type='DeCLIPSegmentation', +# clip_type='EVA02-CLIP-B-16', +# pretrained='eva', +# checkpoint='/mnt/SSD8T/home/wjj/code/decoupledCLIP/logs/OVS/eva_dinov2B_csa_560_0.25_1.0/checkpoints/epoch_6.pt', +# mode="csa", +# ) + +model = dict( + name_path='./configs/proxyclip/cls_context59.txt', + vfm=None, + type='DeCLIPSegmentation', + clip_type='EVA02-CLIP-B-16', + pretrained='eva', + checkpoint="/mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/logs/declip_plus_seg/epoch_6.pt", + mode="csa", +) + +# dataset settings +dataset_type = 'PascalContext59Dataset' +data_root = '/opt/tiger/xiaomoguhzz/dataset/VOCdevkit/VOC2010' + +test_pipeline = [ + dict(type='LoadImageFromFile'), + dict(type='Resize', scale=(4096, 448), keep_ratio=True), + dict(type='LoadAnnotations', reduce_zero_label=True), + dict(type='PackSegInputs', meta_keys=('img_path', 'seg_map_path', 'ori_shape', + 'img_shape', 'pad_shape', 'scale_factor', 'flip', + 'flip_direction', 'reduce_zero_label','resize_shape')) +] + +test_dataloader = dict( + batch_size=1, + num_workers=4, + persistent_workers=True, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + data_prefix=dict( + img_path='JPEGImages', seg_map_path='SegmentationClassContext'), + ann_file='ImageSets/SegmentationContext/val.txt', + pipeline=test_pipeline)) \ No newline at end of file diff --git a/downstream/ProxyCLIP_TPAMI/configs/eva_declip/cfg_context60.py b/downstream/ProxyCLIP_TPAMI/configs/eva_declip/cfg_context60.py new file mode 100644 index 0000000000000000000000000000000000000000..f957c904718fbb15bafe51637005baee215fd7db --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/configs/eva_declip/cfg_context60.py @@ -0,0 +1,63 @@ +_base_ = './base_config.py' + +# model settings +# model = dict( +# name_path='./configs/proxyclip/cls_context60.txt', +# vfm=None, +# type='DeCLIPSegmentation', +# clip_type='EVA02-CLIP-B-16', +# pretrained='eva', +# checkpoint='/mnt/SSD8T/home/wjj/code/decoupledCLIP/logs/eva_dinov2_560_0.25_w/scale/checkpoints/epoch_6.pt', +# mode="qq", +# prob_thd=0.15, +# logit_scale=40, +# ) +# model = dict( +# name_path='./configs/proxyclip/cls_context60.txt', +# vfm=None, +# type='DeCLIPSegmentation', +# clip_type='EVA02-CLIP-B-16', +# pretrained='eva', +# checkpoint="/mnt/SSD8T/home/wjj/code/DeCLIP/logs/EVAB_dinov2B_csa_560_plus_exp90/checkpoints/epoch_6.pt", +# mode="csa", +# prob_thd=0.15, +# logit_scale=40, +# ) + +model = dict( + name_path='./configs/proxyclip/cls_context60.txt', + vfm=None, + type='DeCLIPSegmentation', + clip_type='EVA02-CLIP-B-16', + pretrained='eva', + checkpoint="/mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/logs/declip_plus_seg/epoch_6.pt", + mode="csa", + prob_thd=0.15, + logit_scale=40, +) + +# dataset settings +dataset_type = 'PascalContext60Dataset' +data_root = '/opt/tiger/xiaomoguhzz/dataset/VOCdevkit/VOC2010' + +test_pipeline = [ + dict(type='LoadImageFromFile'), + dict(type='Resize', scale=(4096, 448), keep_ratio=True), + dict(type='LoadAnnotations'), + dict(type='PackSegInputs', meta_keys=('img_path', 'seg_map_path', 'ori_shape', + 'img_shape', 'pad_shape', 'scale_factor', 'flip', + 'flip_direction', 'reduce_zero_label','resize_shape')) +] + +test_dataloader = dict( + batch_size=1, + num_workers=4, + persistent_workers=True, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + data_prefix=dict( + img_path='JPEGImages', seg_map_path='SegmentationClassContext'), + ann_file='ImageSets/SegmentationContext/val.txt', + pipeline=test_pipeline)) \ No newline at end of file diff --git a/downstream/ProxyCLIP_TPAMI/configs/eva_declip/cfg_voc20.py b/downstream/ProxyCLIP_TPAMI/configs/eva_declip/cfg_voc20.py new file mode 100644 index 0000000000000000000000000000000000000000..fadfb7375cef4d341bbabca2ba74872496b1b6d1 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/configs/eva_declip/cfg_voc20.py @@ -0,0 +1,46 @@ +_base_ = './base_config.py' + +# model settings +# model = dict( +# name_path='./configs/proxyclip/cls_voc20.txt', +# vfm=None, +# type='DeCLIPSegmentation', +# clip_type='EVA02-CLIP-B-16', +# pretrained='eva', +# checkpoint='/mnt/SSD8T/home/wjj/code/my_CLIPSelf/checkpoints/EVA02_CLIP_B_psz16_s8B.pt', +# mode="vanilla", +# ) +model = dict( + name_path='./configs/proxyclip/cls_voc20.txt', + vfm=None, + type='DeCLIPSegmentation', + clip_type='EVA02-CLIP-B-16', + pretrained='eva', + checkpoint="/mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/logs/declip_plus_seg/epoch_6.pt", + mode="csa", +) +# dataset settings +dataset_type = 'PascalVOC20Dataset' +data_root = '/opt/tiger/xiaomoguhzz/dataset/VOCdevkit/VOC2012' + +test_pipeline = [ + dict(type='LoadImageFromFile'), + dict(type='Resize', scale=(4096, 448), keep_ratio=True), + dict(type='LoadAnnotations'), + dict(type='PackSegInputs', meta_keys=('img_path', 'seg_map_path', 'ori_shape', + 'img_shape', 'pad_shape', 'scale_factor', 'flip', + 'flip_direction', 'reduce_zero_label','resize_shape')) +] + +test_dataloader = dict( + batch_size=1, + num_workers=4, + persistent_workers=True, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + data_prefix=dict( + img_path='JPEGImages', seg_map_path='SegmentationClass'), + ann_file='ImageSets/Segmentation/val.txt', + pipeline=test_pipeline)) \ No newline at end of file diff --git a/downstream/ProxyCLIP_TPAMI/configs/eva_declip/cfg_voc21.py b/downstream/ProxyCLIP_TPAMI/configs/eva_declip/cfg_voc21.py new file mode 100644 index 0000000000000000000000000000000000000000..cd910603e3b4dd607cd383f34dc4de92bd447043 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/configs/eva_declip/cfg_voc21.py @@ -0,0 +1,63 @@ +_base_ = './base_config.py' + +# model settings +# model = dict( +# name_path='./configs/proxyclip/cls_voc21.txt', +# vfm=None, +# type='DeCLIPSegmentation', +# clip_type='EVA02-CLIP-B-16', +# pretrained='eva', +# checkpoint='/mnt/SSD8T/home/wjj/code/decoupledCLIP/logs/eva_dinov2_560_0.25_w/scale/checkpoints/epoch_6.pt', +# mode="qq", +# prob_thd=0.4, +# logit_scale=80, +# ) +# model = dict( +# name_path='./configs/proxyclip/cls_voc21.txt', +# vfm=None, +# type='DeCLIPSegmentation', +# clip_type='EVA02-CLIP-B-16', +# pretrained='eva', +# checkpoint="/mnt/SSD8T/home/wjj/code/DeCLIP/logs/EVAB_dinov2B_csa_560_plus_exp90/checkpoints/epoch_6.pt", +# mode="csa", +# prob_thd=0.4, +# logit_scale=80, +# ) + +model = dict( + name_path='./configs/proxyclip/cls_voc21.txt', + vfm=None, + type='DeCLIPSegmentation', + clip_type='EVA02-CLIP-B-16', + pretrained='eva', + checkpoint="/mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/logs/declip_plus_seg/epoch_6.pt", + mode="csa", + prob_thd=0.5, # 0.5 + logit_scale=80, +) + +# dataset settings +dataset_type = 'PascalVOCDataset' +data_root = '/opt/tiger/xiaomoguhzz/dataset/VOCdevkit/VOC2012' + +test_pipeline = [ + dict(type='LoadImageFromFile'), + dict(type='Resize', scale=(4096, 448), keep_ratio=True), + dict(type='LoadAnnotations'), + dict(type='PackSegInputs', meta_keys=('img_path', 'seg_map_path', 'ori_shape', + 'img_shape', 'pad_shape', 'scale_factor', 'flip', + 'flip_direction', 'reduce_zero_label','resize_shape')) +] + +test_dataloader = dict( + batch_size=1, + num_workers=4, + persistent_workers=True, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + data_prefix=dict( + img_path='JPEGImages', seg_map_path='SegmentationClass'), + ann_file='ImageSets/Segmentation/val.txt', + pipeline=test_pipeline)) \ No newline at end of file diff --git a/downstream/ProxyCLIP_TPAMI/configs/proxyclip/base_config.py b/downstream/ProxyCLIP_TPAMI/configs/proxyclip/base_config.py new file mode 100644 index 0000000000000000000000000000000000000000..7e4bca367388d5abdb45602bb83f8b78c629ceae --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/configs/proxyclip/base_config.py @@ -0,0 +1,31 @@ +# base configurations +model = dict( + type='ProxyCLIPSegmentation', + clip_type='openai', + model_type='ViT-B/16', + vfm_model='dino', # sam, mae, dino, dinov2 + checkpoint=None, +) + +test_evaluator = dict(type='IoUMetric', iou_metrics=['mIoU']) +default_scope = 'mmseg' +env_cfg = dict( + cudnn_benchmark=True, + mp_cfg=dict(mp_start_method='fork', opencv_num_threads=0), + dist_cfg=dict(backend='nccl'), +) +vis_backends = [dict(type='LocalVisBackend')] +visualizer = dict( + type='SegLocalVisualizer', vis_backends=vis_backends, alpha=1.0, name='visualizer') +log_processor = dict(by_epoch=False) +log_level = 'INFO' +load_from = None +resume = False +test_cfg = dict(type='TestLoop') +default_hooks = dict( + timer=dict(type='IterTimerHook'), + logger=dict(type='LoggerHook', interval=50, log_metric_by_epoch=False), + param_scheduler=dict(type='ParamSchedulerHook'), + checkpoint=dict(type='CheckpointHook', by_epoch=False, interval=2000), + sampler_seed=dict(type='DistSamplerSeedHook'), + visualization=dict(type='SegVisualizationHook', draw=True,interval=20)) \ No newline at end of file diff --git a/downstream/ProxyCLIP_TPAMI/configs/proxyclip/cfg_ade20k.py b/downstream/ProxyCLIP_TPAMI/configs/proxyclip/cfg_ade20k.py new file mode 100644 index 0000000000000000000000000000000000000000..1b1046a91060dd308c7126ddeb1ace64e8b22b18 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/configs/proxyclip/cfg_ade20k.py @@ -0,0 +1,30 @@ +_base_ = './base_config.py' + +# model settings +model = dict( + name_path='./cls_ade20k.txt' +) + +# dataset settings +dataset_type = 'ADE20KDataset' +data_root = '' + +test_pipeline = [ + dict(type='LoadImageFromFile'), + dict(type='Resize', scale=(2048, 448), keep_ratio=True), + dict(type='LoadAnnotations', reduce_zero_label=True), + dict(type='PackSegInputs') +] + +test_dataloader = dict( + batch_size=1, + num_workers=4, + persistent_workers=True, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + data_prefix=dict( + img_path='images/validation', + seg_map_path='annotations/validation'), + pipeline=test_pipeline)) \ No newline at end of file diff --git a/downstream/ProxyCLIP_TPAMI/configs/proxyclip/cfg_ade847.py b/downstream/ProxyCLIP_TPAMI/configs/proxyclip/cfg_ade847.py new file mode 100644 index 0000000000000000000000000000000000000000..3ad6aaca7bf36e62e57b74b0a7ea7413fdeaa0ef --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/configs/proxyclip/cfg_ade847.py @@ -0,0 +1,31 @@ +_base_ = './base_config.py' + +# model settings +model = dict( + name_path='./cls_ade20k847.txt' +) + +# dataset settings +dataset_type = 'ADE20K847Dataset' +data_root = '' + +test_pipeline = [ + dict(type='LoadImageFromFile'), + dict(type='Resize', scale=(2048, 448), keep_ratio=True), + dict(type='MyLoadAnnotations', reduce_zero_label=False), + dict(type='PackSegInputs') +] + +test_dataloader = dict( + batch_size=1, + num_workers=4, + persistent_workers=True, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + data_prefix=dict( + img_path='images_detectron2/validation', + seg_map_path='annotations_detectron2/validation'), + ann_file='validation.txt', + pipeline=test_pipeline)) \ No newline at end of file diff --git a/downstream/ProxyCLIP_TPAMI/configs/proxyclip/cfg_city_scapes.py b/downstream/ProxyCLIP_TPAMI/configs/proxyclip/cfg_city_scapes.py new file mode 100644 index 0000000000000000000000000000000000000000..ea96d9b3f2fb2b06aebf791371cf70ef76416425 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/configs/proxyclip/cfg_city_scapes.py @@ -0,0 +1,33 @@ +_base_ = './base_config.py' + +# model settings +model = dict( + name_path='./cls_city_scapes.txt', + slide_stride=112, + slide_crop=224 +) + +# dataset settings +dataset_type = 'CityscapesDataset' +data_root = '' + +test_pipeline = [ + dict(type='LoadImageFromFile'), + dict(type='Resize', scale=(2048, 448), keep_ratio=True), + # add loading annotation after ``Resize`` because ground truth + # does not need to do resize data transform + dict(type='LoadAnnotations'), + dict(type='PackSegInputs') +] + +test_dataloader = dict( + batch_size=1, + num_workers=4, + persistent_workers=True, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + data_prefix=dict( + img_path='leftImg8bit/val', seg_map_path='gtFine/val'), + pipeline=test_pipeline)) \ No newline at end of file diff --git a/downstream/ProxyCLIP_TPAMI/configs/proxyclip/cfg_coco_object.py b/downstream/ProxyCLIP_TPAMI/configs/proxyclip/cfg_coco_object.py new file mode 100644 index 0000000000000000000000000000000000000000..b4326888bd2ffe969818639e82fd8f1cefc66a97 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/configs/proxyclip/cfg_coco_object.py @@ -0,0 +1,31 @@ +_base_ = './base_config.py' + +# model settings +model = dict( + name_path='./cls_coco_object.txt', + prob_thd=0.25, # 0.25 OURS 0.1 CLIP +) + +# dataset settings +dataset_type = 'COCOObjectDataset' +data_root = '' + +test_pipeline = [ + dict(type='LoadImageFromFile'), + dict(type='Resize', scale=(2048, 336), keep_ratio=True), + dict(type='LoadAnnotations'), + dict(type='PackSegInputs') +] + +test_dataloader = dict( + batch_size=1, + num_workers=4, + persistent_workers=True, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + reduce_zero_label=False, + data_prefix=dict( + img_path='images/val2017', seg_map_path='annotations/val2017'), + pipeline=test_pipeline)) \ No newline at end of file diff --git a/downstream/ProxyCLIP_TPAMI/configs/proxyclip/cfg_coco_stuff164k.py b/downstream/ProxyCLIP_TPAMI/configs/proxyclip/cfg_coco_stuff164k.py new file mode 100644 index 0000000000000000000000000000000000000000..e9f297fffcad8206cbb664754d1b325991bcd597 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/configs/proxyclip/cfg_coco_stuff164k.py @@ -0,0 +1,30 @@ +_base_ = './base_config.py' + +# model settings +model = dict( + name_path='./cls_coco_stuff.txt' +) + +# dataset settings +dataset_type = 'COCOStuffDataset' +data_root = '' + +test_pipeline = [ + dict(type='LoadImageFromFile'), + dict(type='Resize', scale=(2048, 336), keep_ratio=True), + dict(type='LoadAnnotations'), + dict(type='PackSegInputs') +] + +test_dataloader = dict( + batch_size=1, + num_workers=4, + persistent_workers=True, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + data_prefix=dict( + img_path='/mnt/SSD8T/home/wjj/dataset/standard_coco/val2017', + seg_map_path='/mnt/SSD8T/home/wjj/dataset/standard_coco/annotations/val2017'), + pipeline=test_pipeline)) \ No newline at end of file diff --git a/downstream/ProxyCLIP_TPAMI/configs/proxyclip/cfg_context459.py b/downstream/ProxyCLIP_TPAMI/configs/proxyclip/cfg_context459.py new file mode 100644 index 0000000000000000000000000000000000000000..068aedb211698f5aec7c33eafd9861248614d1b2 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/configs/proxyclip/cfg_context459.py @@ -0,0 +1,30 @@ +_base_ = './base_config.py' + +# model settings +model = dict( + name_path='./cls_context459.txt' +) + +# dataset settings +dataset_type = 'PascalContext459Dataset' +data_root = '' + +test_pipeline = [ + dict(type='LoadImageFromFile'), + dict(type='Resize', scale=(2048, 448), keep_ratio=True), + dict(type='MyLoadAnnotations', reduce_zero_label=False), + dict(type='PackSegInputs') +] + +test_dataloader = dict( + batch_size=1, + num_workers=4, + persistent_workers=True, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + data_prefix=dict( + img_path='JPEGImages', seg_map_path='annotations_detectron2/pc459_val'), + ann_file='ImageSets/SegmentationContext/val.txt', + pipeline=test_pipeline)) \ No newline at end of file diff --git a/downstream/ProxyCLIP_TPAMI/configs/proxyclip/cfg_context59.py b/downstream/ProxyCLIP_TPAMI/configs/proxyclip/cfg_context59.py new file mode 100644 index 0000000000000000000000000000000000000000..0c236a8f04bfc89d95b8d51e3d16f41f22869ed2 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/configs/proxyclip/cfg_context59.py @@ -0,0 +1,30 @@ +_base_ = './base_config.py' + +# model settings +model = dict( + name_path='./cls_context59.txt' +) + +# dataset settings +dataset_type = 'PascalContext59Dataset' +data_root = '' + +test_pipeline = [ + dict(type='LoadImageFromFile'), + dict(type='Resize', scale=(2048, 336), keep_ratio=True), + dict(type='LoadAnnotations', reduce_zero_label=True), + dict(type='PackSegInputs') +] + +test_dataloader = dict( + batch_size=1, + num_workers=4, + persistent_workers=True, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + data_prefix=dict( + img_path='JPEGImages', seg_map_path='SegmentationClassContext'), + ann_file='ImageSets/SegmentationContext/val.txt', + pipeline=test_pipeline)) \ No newline at end of file diff --git a/downstream/ProxyCLIP_TPAMI/configs/proxyclip/cfg_context60.py b/downstream/ProxyCLIP_TPAMI/configs/proxyclip/cfg_context60.py new file mode 100644 index 0000000000000000000000000000000000000000..56038016e1c95c65c20d2371d80337fb6905e7ad --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/configs/proxyclip/cfg_context60.py @@ -0,0 +1,31 @@ +_base_ = './base_config.py' + +# model settings +model = dict( + name_path='./cls_context60.txt', + prob_thd=0.15 # 0.15 OURS 0.05 CLIP +) + +# dataset settings +dataset_type = 'PascalContext60Dataset' +data_root = '' + +test_pipeline = [ + dict(type='LoadImageFromFile'), + dict(type='Resize', scale=(2048, 336), keep_ratio=True), + dict(type='LoadAnnotations'), + dict(type='PackSegInputs') +] + +test_dataloader = dict( + batch_size=1, + num_workers=4, + persistent_workers=True, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + data_prefix=dict( + img_path='JPEGImages', seg_map_path='SegmentationClassContext'), + ann_file='ImageSets/SegmentationContext/val.txt', + pipeline=test_pipeline)) \ No newline at end of file diff --git a/downstream/ProxyCLIP_TPAMI/configs/proxyclip/cfg_voc20.py b/downstream/ProxyCLIP_TPAMI/configs/proxyclip/cfg_voc20.py new file mode 100644 index 0000000000000000000000000000000000000000..f7758e4226c83fb7bffcb68e599bdbc11334e0cb --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/configs/proxyclip/cfg_voc20.py @@ -0,0 +1,30 @@ +_base_ = './base_config.py' + +# model settings +model = dict( + name_path='./cls_voc20.txt' +) + +# dataset settings +dataset_type = 'PascalVOC20Dataset' +data_root = '' + +test_pipeline = [ + dict(type='LoadImageFromFile'), + dict(type='Resize', scale=(2048, 336), keep_ratio=True), + dict(type='LoadAnnotations'), + dict(type='PackSegInputs') +] + +test_dataloader = dict( + batch_size=1, + num_workers=4, + persistent_workers=True, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + data_prefix=dict( + img_path='JPEGImages', seg_map_path='SegmentationClass'), + ann_file='ImageSets/Segmentation/val.txt', + pipeline=test_pipeline)) \ No newline at end of file diff --git a/downstream/ProxyCLIP_TPAMI/configs/proxyclip/cfg_voc21.py b/downstream/ProxyCLIP_TPAMI/configs/proxyclip/cfg_voc21.py new file mode 100644 index 0000000000000000000000000000000000000000..faf5a218138dd614cd99a29a9ed3ae44f24521bd --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/configs/proxyclip/cfg_voc21.py @@ -0,0 +1,31 @@ +_base_ = './base_config.py' + +# model settings +model = dict( + name_path='./cls_voc21.txt', + prob_thd= 0.2 # 0.2 OURS 0.1 CLIP-B/16 +) + +# dataset settings +dataset_type = 'PascalVOCDataset' +data_root = '' + +test_pipeline = [ + dict(type='LoadImageFromFile'), + dict(type='Resize', scale=(2048, 336), keep_ratio=True), + dict(type='LoadAnnotations'), + dict(type='PackSegInputs') +] + +test_dataloader = dict( + batch_size=1, + num_workers=4, + persistent_workers=True, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + data_prefix=dict( + img_path='JPEGImages', seg_map_path='SegmentationClass'), + ann_file='ImageSets/Segmentation/val.txt', + pipeline=test_pipeline)) \ No newline at end of file diff --git a/downstream/ProxyCLIP_TPAMI/configs/proxyclip/cls_ade20k.txt b/downstream/ProxyCLIP_TPAMI/configs/proxyclip/cls_ade20k.txt new file mode 100644 index 0000000000000000000000000000000000000000..dba5aa2ce0c703b9dbf07dea5ee5e5230c8b51d3 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/configs/proxyclip/cls_ade20k.txt @@ -0,0 +1,150 @@ +wall +building +sky +floor +tree +ceiling +road +bed +windowpane +grass +cabinet +sidewalk +person +earth +door +table +mountain +plant +curtain +chair +car +water +painting +sofa +shelf +house +sea +mirror +rug +field +armchair +seat +fence +desk +rock +wardrobe +lamp +bathtub +railing +cushion +base +box +column +signboard +chestofdrawers +counter +sand +sink +skyscraper +fireplace +refrigerator +grandstand +path +stairs +runway +case +pooltable +pillow +screendoor +stairway +river +bridge +bookcase +blind +coffeetable +toilet +flower +book +hill +bench +countertop +stove +palm +kitchenisland +computer +swivelchair +boat +bar +arcademachine +hovel +bus +towel +light +truck +tower +chandelier +awning +streetlight +booth +televisionreceiver +airplane +dirttrack +apparel +pole +land +bannister +escalator +ottoman +bottle +buffet +poster +stage +van +ship +fountain +conveyerbelt +canopy +washer +plaything +swimmingpool +stool +barrel +basket +waterfall +tent +bag +minibike +cradle +oven +ball +food +step +tank +tradename +microwave +pot +animal +bicycle +lake +dishwasher +screen +blanket +sculpture +hood +sconce +vase +trafficlight +tray +ashcan +fan +pier +crtscreen +plate +monitor +bulletinboard +shower +radiator +glass +clock +flag \ No newline at end of file diff --git a/downstream/ProxyCLIP_TPAMI/configs/proxyclip/cls_ade20k847.txt b/downstream/ProxyCLIP_TPAMI/configs/proxyclip/cls_ade20k847.txt new file mode 100644 index 0000000000000000000000000000000000000000..eed13afb4820bd4918fa979db7487e38600ed4dc --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/configs/proxyclip/cls_ade20k847.txt @@ -0,0 +1,847 @@ +wall +building, edifice +sky +tree +road, route +floor, flooring +ceiling +bed +sidewalk, pavement +earth, ground +cabinet +person, individual, someone, somebody, mortal, soul +grass +windowpane, window +car, auto, automobile, machine, motorcar +mountain, mount +plant, flora, plant life +table +chair +curtain, drape, drapery, mantle, pall +door +sofa, couch, lounge +sea +painting, picture +water +mirror +house +rug, carpet, carpeting +shelf +armchair +fence, fencing +field +lamp +rock, stone +seat +river +desk +bathtub, bathing tub, bath, tub +railing, rail +signboard, sign +cushion +path +work surface +stairs, steps +column, pillar +sink +wardrobe, closet, press +snow +refrigerator, icebox +base, pedestal, stand +bridge, span +blind, screen +runway +cliff, drop, drop-off +sand +fireplace, hearth, open fireplace +pillow +screen door, screen +toilet, can, commode, crapper, pot, potty, stool, throne +skyscraper +grandstand, covered stand +box +pool table, billiard table, snooker table +palm, palm tree +double door +coffee table, cocktail table +counter +countertop +chest of drawers, chest, bureau, dresser +kitchen island +boat +waterfall, falls +stove, kitchen stove, range, kitchen range, cooking stove +flower +bookcase +controls +book +stairway, staircase +streetlight, street lamp +computer, computing machine, computing device, data processor, electronic computer, information processing system +bus, autobus, coach, charabanc, double-decker, jitney, motorbus, motorcoach, omnibus, passenger vehicle +swivel chair +light, light source +bench +case, display case, showcase, vitrine +towel +fountain +embankment +television receiver, television, television set, tv, tv set, idiot box, boob tube, telly, goggle box +van +hill +awning, sunshade, sunblind +poster, posting, placard, notice, bill, card +truck, motortruck +airplane, aeroplane, plane +pole +tower +court +ball +aircraft carrier, carrier, flattop, attack aircraft carrier +buffet, counter, sideboard +hovel, hut, hutch, shack, shanty +apparel, wearing apparel, dress, clothes +minibike, motorbike +animal, animate being, beast, brute, creature, fauna +chandelier, pendant, pendent +step, stair +booth, cubicle, stall, kiosk +bicycle, bike, wheel, cycle +doorframe, doorcase +sconce +pond +trade name, brand name, brand, marque +bannister, banister, balustrade, balusters, handrail +bag +traffic light, traffic signal, stoplight +gazebo +escalator, moving staircase, moving stairway +land, ground, soil +board, plank +arcade machine +eiderdown, duvet, continental quilt +bar +stall, stand, sales booth +playground +ship +ottoman, pouf, pouffe, puff, hassock +ashcan, trash can, garbage can, wastebin, ash bin, ash-bin, ashbin, dustbin, trash barrel, trash bin +bottle +cradle +pot, flowerpot +conveyer belt, conveyor belt, conveyer, conveyor, transporter +train, railroad train +stool +lake +tank, storage tank +ice, water ice +basket, handbasket +manhole +tent, collapsible shelter +canopy +microwave, microwave oven +barrel, cask +dirt track +beam +dishwasher, dish washer, dishwashing machine +plate +screen, crt screen +ruins +washer, automatic washer, washing machine +blanket, cover +plaything, toy +food, solid food +screen, silver screen, projection screen +oven +stage +beacon, lighthouse, beacon light, pharos +umbrella +sculpture +aqueduct +container +scaffolding, staging +hood, exhaust hood +curb, curbing, kerb +roller coaster +horse, equus caballus +catwalk +glass, drinking glass +vase +central reservation +carousel +radiator +closet +machine +pier, wharf, wharfage, dock +fan +inflatable bounce game +pitch +paper +arcade, colonnade +hot tub +helicopter +tray +partition, divider +vineyard +bowl +bullring +flag +pot +footbridge, overcrossing, pedestrian bridge +shower +bag, traveling bag, travelling bag, grip, suitcase +bulletin board, notice board +confessional booth +trunk, tree trunk, bole +forest +elevator door +laptop, laptop computer +instrument panel +bucket, pail +tapestry, tapis +platform +jacket +gate +monitor, monitoring device +telephone booth, phone booth, call box, telephone box, telephone kiosk +spotlight, spot +ring +control panel +blackboard, chalkboard +air conditioner, air conditioning +chest +clock +sand dune +pipe, pipage, piping +vault +table football +cannon +swimming pool, swimming bath, natatorium +fluorescent, fluorescent fixture +statue +loudspeaker, speaker, speaker unit, loudspeaker system, speaker system +exhibitor +ladder +carport +dam +pulpit +skylight, fanlight +water tower +grill, grille, grillwork +display board +pane, pane of glass, window glass +rubbish, trash, scrap +ice rink +fruit +patio +vending machine +telephone, phone, telephone set +net +backpack, back pack, knapsack, packsack, rucksack, haversack +jar +track +magazine +shutter +roof +banner, streamer +landfill +post +altarpiece, reredos +hat, chapeau, lid +arch, archway +table game +bag, handbag, pocketbook, purse +document, written document, papers +dome +pier +shanties +forecourt +crane +dog, domestic dog, canis familiaris +piano, pianoforte, forte-piano +drawing +cabin +ad, advertisement, advertizement, advertising, advertizing, advert +amphitheater, amphitheatre, coliseum +monument +henhouse +cockpit +heater, warmer +windmill, aerogenerator, wind generator +pool +elevator, lift +decoration, ornament, ornamentation +labyrinth +text, textual matter +printer +mezzanine, first balcony +mattress +straw +stalls +patio, terrace +billboard, hoarding +bus stop +trouser, pant +console table, console +rack +notebook +shrine +pantry +cart +steam shovel +porch +postbox, mailbox, letter box +figurine, statuette +recycling bin +folding screen +telescope +deck chair, beach chair +kennel +coffee maker +altar, communion table, lords table +fish +easel +artificial golf green +iceberg +candlestick, candle holder +shower stall, shower bath +television stand +wall socket, wall plug, electric outlet, electrical outlet, outlet, electric receptacle +skeleton +grand piano, grand +candy, confect +grille door +pedestal, plinth, footstall +jersey, t-shirt, tee shirt +shoe +gravestone, headstone, tombstone +shanty +structure +rocking chair, rocker +bird +place mat +tomb +big top +gas pump, gasoline pump, petrol pump, island dispenser +lockers +cage +finger +bleachers +ferris wheel +hairdresser chair +mat +stands +aquarium, fish tank, marine museum +streetcar, tram, tramcar, trolley, trolley car +napkin, table napkin, serviette +dummy +booklet, brochure, folder, leaflet, pamphlet +sand trap +shop, store +table cloth +service station +coffin +drawer +cages +slot machine, coin machine +balcony +volleyball court +table tennis +control table +shirt +merchandise, ware, product +railway +parterre +chimney +can, tin, tin can +tanks +fabric, cloth, material, textile +alga, algae +system +map +greenhouse +mug +barbecue +trailer +toilet tissue, toilet paper, bathroom tissue +organ +dishrag, dishcloth +island +keyboard +trench +basket, basketball hoop, hoop +steering wheel, wheel +pitcher, ewer +goal +bread, breadstuff, staff of life +beds +wood +file cabinet +newspaper, paper +motorboat +rope +guitar +rubble +scarf +barrels +cap +leaves +control tower +dashboard +bandstand +lectern +switch, electric switch, electrical switch +baseboard, mopboard, skirting board +shower room +smoke +faucet, spigot +bulldozer +saucepan +shops +meter +crevasse +gear +candelabrum, candelabra +sofa bed +tunnel +pallet +wire, conducting wire +kettle, boiler +bidet +baby buggy, baby carriage, carriage, perambulator, pram, stroller, go-cart, pushchair, pusher +music stand +pipe, tube +cup +parking meter +ice hockey rink +shelter +weeds +temple +patty, cake +ski slope +panel +wallet +wheel +towel rack, towel horse +roundabout +canister, cannister, tin +rod +soap dispenser +bell +canvas +box office, ticket office, ticket booth +teacup +trellis +workbench +valley, vale +toaster +knife +podium +ramp +tumble dryer +fireplug, fire hydrant, plug +gym shoe, sneaker, tennis shoe +lab bench +equipment +rocky formation +plastic +calendar +caravan +check-in-desk +ticket counter +brush +mill +covered bridge +bowling alley +hanger +excavator +trestle +revolving door +blast furnace +scale, weighing machine +projector +soap +locker +tractor +stretcher +frame +grating +alembic +candle, taper, wax light +barrier +cardboard +cave +puddle +tarp +price tag +watchtower +meters +light bulb, lightbulb, bulb, incandescent lamp, electric light, electric-light bulb +tracks +hair dryer +skirt +viaduct +paper towel +coat +sheet +fire extinguisher, extinguisher, asphyxiator +water wheel +pottery, clayware +magazine rack +teapot +microphone, mike +support +forklift +canyon +cash register, register +leaf, leafage, foliage +remote control, remote +soap dish +windshield, windscreen +cat +cue, cue stick, pool cue, pool stick +vent, venthole, vent-hole, blowhole +videos +shovel +eaves +antenna, aerial, transmitting aerial +shipyard +hen, biddy +traffic cone +washing machines +truck crane +cds +niche +scoreboard +briefcase +boot +sweater, jumper +hay +pack +bottle rack +glacier +pergola +building materials +television camera +first floor +rifle +tennis table +stadium +safety belt +cover +dish rack +synthesizer +pumpkin +gutter +fruit stand +ice floe, floe +handle, grip, handgrip, hold +wheelchair +mousepad, mouse mat +diploma +fairground ride +radio +hotplate +junk +wheelbarrow +stream +toll plaza +punching bag +trough +throne +chair desk +weighbridge +extractor fan +hanging clothes +dish, dish aerial, dish antenna, saucer +alarm clock, alarm +ski lift +chain +garage +mechanical shovel +wine rack +tramway +treadmill +menu +block +well +witness stand +branch +duck +casserole +frying pan +desk organizer +mast +spectacles, specs, eyeglasses, glasses +service elevator +dollhouse +hammock +clothes hanging +photocopier +notepad +golf cart +footpath +cross +baptismal font +boiler +skip +rotisserie +tables +water mill +helmet +cover curtain +brick +table runner +ashtray +street box +stick +hangers +cells +urinal +centerpiece +portable fridge +dvds +golf club +skirting board +water cooler +clipboard +camera, photographic camera +pigeonhole +chips +food processor +post box +lid +drum +blender +cave entrance +dental chair +obelisk +canoe +mobile +monitors +pool ball +cue rack +baggage carts +shore +fork +paper filer +bicycle rack +coat rack +garland +sports bag +fish tank +towel dispenser +carriage +brochure +plaque +stringer +iron +spoon +flag pole +toilet brush +book stand +water faucet, water tap, tap, hydrant +ticket office +broom +dvd +ice bucket +carapace, shell, cuticle, shield +tureen +folders +chess +root +sewing machine +model +pen +violin +sweatshirt +recycling materials +mitten +chopping board, cutting board +mask +log +mouse, computer mouse +grill +hole +target +trash bag +chalk +sticks +balloon +score +hair spray +roll +runner +engine +inflatable glove +games +pallets +baskets +coop +dvd player +rocking horse +buckets +bread rolls +shawl +watering can +spotlights +post-it +bowls +security camera +runner cloth +lock +alarm, warning device, alarm system +side +roulette +bone +cutlery +pool balls +wheels +spice rack +plant pots +towel ring +bread box +video +funfair +breads +tripod +ironing board +skimmer +hollow +scratching post +tricycle +file box +mountain pass +tombstones +cooker +card game, cards +golf bag +towel paper +chaise lounge +sun +toilet paper holder +rake +key +umbrella stand +dartboard +transformer +fireplace utensils +sweatshirts +cellular telephone, cellular phone, cellphone, cell, mobile phone +tallboy +stapler +sauna +test tube +palette +shopping carts +tools +push button, push, button +star +roof rack +barbed wire +spray +ear +sponge +racket +tins +eyeglasses +file +scarfs +sugar bowl +flip flop +headstones +laptop bag +leash +climbing frame +suit hanger +floor spotlight +plate rack +sewer +hard drive +sprinkler +tools box +necklace +bulbs +steel industry +club +jack +door bars +control panel, instrument panel, control board, board, panel +hairbrush +napkin holder +office +smoke detector +utensils +apron +scissors +terminal +grinder +entry phone +newspaper stand +pepper shaker +onions +central processing unit, cpu, c p u , central processor, processor, mainframe +tape +bat +coaster +calculator +potatoes +luggage rack +salt +street number +viewpoint +sword +cd +rowing machine +plug +andiron, firedog, dog, dog-iron +pepper +tongs +bonfire +dog dish +belt +dumbbells +videocassette recorder, vcr +hook +envelopes +shower faucet +watch +padlock +swimming pool ladder +spanners +gravy boat +notice board +trash bags +fire alarm +ladle +stethoscope +rocket +funnel +bowling pins +valve +thermometer +cups +spice jar +night light +soaps +games table +slotted spoon +reel +scourer +sleeping robe +desk mat +dumbbell +hammer +tie +typewriter +shaker +cheese dish +sea star +racquet +butane gas cylinder +paper weight +shaving brush +sunglasses +gear shift +towel rail +adding machine, totalizer, totaliser \ No newline at end of file diff --git a/downstream/ProxyCLIP_TPAMI/configs/proxyclip/cls_city_scapes.txt b/downstream/ProxyCLIP_TPAMI/configs/proxyclip/cls_city_scapes.txt new file mode 100644 index 0000000000000000000000000000000000000000..a1560efb268b4c8a52a68e41df402a4b33171d44 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/configs/proxyclip/cls_city_scapes.txt @@ -0,0 +1,19 @@ +road +sidewalk +building +wall +fence +pole +trafficlight +trafficsign +vegetation +terrain +sky +person +rider +car +truck +bus +train +motorcycle +bicycle \ No newline at end of file diff --git a/downstream/ProxyCLIP_TPAMI/configs/proxyclip/cls_coco_object.txt b/downstream/ProxyCLIP_TPAMI/configs/proxyclip/cls_coco_object.txt new file mode 100644 index 0000000000000000000000000000000000000000..db0f477941c551be23719fdff5036961366d05c9 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/configs/proxyclip/cls_coco_object.txt @@ -0,0 +1,81 @@ +sky; wall; tree; wood; grass; road; sea; river; mountain; sands; desk; bed; building; cloud; floor; hill; rail +person +bicycle +car +motorcycle +airplane +bus +train +truck +boat +traffic light +fire hydrant +stop sign +parking meter +bench +bird +cat +dog +horse +sheep +cow +elephant +bear +zebra +giraffe +backpack +umbrella +handbag +tie +suitcase +frisbee +skis +snowboard +sports ball +kite +baseball bat +baseball glove +skateboard +surfboard +tennis racket +bottle +wine glass +cup +fork +knife +spoon +bowl +banana +apple +sandwich +orange +broccoli +carrot +hot dog +pizza +donut +cake +chair +couch +potted plant +bed +dining table +toilet +tv +laptop +mouse +remote +keyboard +cell phone +microwave +oven +toaster +sink +refrigerator +book +clock +vase +scissors +teddy bear +hair drier +toothbrush \ No newline at end of file diff --git a/downstream/ProxyCLIP_TPAMI/configs/proxyclip/cls_coco_stuff.txt b/downstream/ProxyCLIP_TPAMI/configs/proxyclip/cls_coco_stuff.txt new file mode 100644 index 0000000000000000000000000000000000000000..b76c5a676308c9f328635938cf86f6fd27a985bb --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/configs/proxyclip/cls_coco_stuff.txt @@ -0,0 +1,171 @@ +person +bicycle +car +motorcycle +airplane +bus +train +truck +boat +trafficlight +firehydrant +stopsign +parkingmeter +bench +bird +cat +dog +horse +sheep +cow +elephant +bear +zebra +giraffe +backpack +umbrella +handbag +tie +suitcase +frisbee +skis +snowboard +sportsball +kite +baseballbat +baseballglove +skateboard +surfboard +tennisracket +bottle +wineglass +cup +fork +knife +spoon +bowl +banana +apple +sandwich +orange +broccoli +carrot +hotdog +pizza +donut +cake +chair +couch +pottedplant +bed +diningtable +toilet +tv +laptop +mouse +remote +keyboard +cellphone +microwave +oven +toaster +sink +refrigerator +book +clock +vase +scissors +teddybear +hairdrier +toothbrush +banner +blanket +branch +bridge +building-other +bush +cabinet +cage +cardboard +carpet +ceiling-other +ceiling-tile +cloth +clothes +clouds +counter +cupboard +curtain +desk-stuff +dirt +door-stuff +fence +floor-marble +floor-other +floor-stone +floor-tile +floor-wood +flower +fog +food-other +fruit +furniture-other +grass +gravel +ground-other +hill +house +leaves +light +mat +metal +mirror-stuff +moss +mountain +mud +napkin +net +paper +pavement +pillow +plant-other +plastic +platform +playingfield +railing +railroad +river +road +rock +roof +rug +salad +sand +sea +shelf +sky-other +skyscraper +snow +solid-other +stairs +stone +straw +structural-other +table +tent +textile-other +towel +tree +vegetable +wall-brick +wall-concrete +wall-other +wall-panel +wall-stone +wall-tile +wall-wood +water-other +waterdrops +window-blind +window-other +wood \ No newline at end of file diff --git a/downstream/ProxyCLIP_TPAMI/configs/proxyclip/cls_context459.txt b/downstream/ProxyCLIP_TPAMI/configs/proxyclip/cls_context459.txt new file mode 100644 index 0000000000000000000000000000000000000000..b04d79c30d181f6c9567d52df8e60749f9fae5e2 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/configs/proxyclip/cls_context459.txt @@ -0,0 +1,459 @@ +accordion +aeroplane +air conditioner +antenna +artillery +ashtray +atrium +baby carriage +bag +ball +balloon +bamboo weaving +barrel +baseball bat +basket +basketball backboard +bathtub +bed +bedclothes +beer +bell +bench +bicycle +binoculars +bird +bird cage +bird feeder +bird nest +blackboard +board +boat +bone +book +bottle +bottle opener +bowl +box +bracelet +brick +bridge +broom +brush +bucket +building +bus +cabinet +cabinet door +cage +cake +calculator +calendar +camel +camera +camera lens +can +candle +candle holder +cap +car +card +cart +case +casette recorder +cash register +cat +cd +cd player +ceiling +cell phone +cello +chain +chair +chessboard +chicken +chopstick +clip +clippers +clock +closet +cloth +clothes tree +coffee +coffee machine +comb +computer +concrete +cone +container +control booth +controller +cooker +copying machine +coral +cork +corkscrew +counter +court +cow +crabstick +crane +crate +cross +crutch +cup +curtain +cushion +cutting board +dais +disc +disc case +dishwasher +dock +dog +dolphin +door +drainer +dray +drink dispenser +drinking machine +drop +drug +drum +drum kit +duck +dumbbell +earphone +earrings +egg +electric fan +electric iron +electric pot +electric saw +electronic keyboard +engine +envelope +equipment +escalator +exhibition booth +extinguisher +eyeglass +fan +faucet +fax machine +fence +ferris wheel +fire extinguisher +fire hydrant +fire place +fish +fish tank +fishbowl +fishing net +fishing pole +flag +flagstaff +flame +flashlight +floor +flower +fly +foam +food +footbridge +forceps +fork +forklift +fountain +fox +frame +fridge +frog +fruit +funnel +furnace +game controller +game machine +gas cylinder +gas hood +gas stove +gift box +glass +glass marble +globe +glove +goal +grandstand +grass +gravestone +ground +guardrail +guitar +gun +hammer +hand cart +handle +handrail +hanger +hard disk drive +hat +hay +headphone +heater +helicopter +helmet +holder +hook +horse +horse-drawn carriage +hot-air balloon +hydrovalve +ice +inflator pump +ipod +iron +ironing board +jar +kart +kettle +key +keyboard +kitchen range +kite +knife +knife block +ladder +ladder truck +ladle +laptop +leaves +lid +life buoy +light +light bulb +lighter +line +lion +lobster +lock +machine +mailbox +mannequin +map +mask +mat +match book +mattress +menu +metal +meter box +microphone +microwave +mirror +missile +model +money +monkey +mop +motorbike +mountain +mouse +mouse pad +musical instrument +napkin +net +newspaper +oar +ornament +outlet +oven +oxygen bottle +pack +pan +paper +paper box +paper cutter +parachute +parasol +parterre +patio +pelage +pen +pen container +pencil +person +photo +piano +picture +pig +pillar +pillow +pipe +pitcher +plant +plastic +plate +platform +player +playground +pliers +plume +poker +poker chip +pole +pool table +postcard +poster +pot +pottedplant +printer +projector +pumpkin +rabbit +racket +radiator +radio +rail +rake +ramp +range hood +receiver +recorder +recreational machines +remote control +road +robot +rock +rocket +rocking horse +rope +rug +ruler +runway +saddle +sand +saw +scale +scanner +scissors +scoop +screen +screwdriver +sculpture +scythe +sewer +sewing machine +shed +sheep +shell +shelves +shoe +shopping cart +shovel +sidecar +sidewalk +sign +signal light +sink +skateboard +ski +sky +sled +slippers +smoke +snail +snake +snow +snowmobiles +sofa +spanner +spatula +speaker +speed bump +spice container +spoon +sprayer +squirrel +stage +stair +stapler +stick +sticky note +stone +stool +stove +straw +stretcher +sun +sunglass +sunshade +surveillance camera +swan +sweeper +swim ring +swimming pool +swing +switch +table +tableware +tank +tap +tape +tarp +telephone +telephone booth +tent +tire +toaster +toilet +tong +tool +toothbrush +towel +toy +toy car +track +train +trampoline +trash bin +tray +tree +tricycle +tripod +trophy +truck +tube +turtle +tvmonitor +tweezers +typewriter +umbrella +unknown +vacuum cleaner +vending machine +video camera +video game console +video player +video tape +violin +wakeboard +wall +wallet +wardrobe +washing machine +watch +water +water dispenser +water pipe +water skate board +watermelon +whale +wharf +wheel +wheelchair +window +window blinds +wineglass +wire +wood +wool \ No newline at end of file diff --git a/downstream/ProxyCLIP_TPAMI/configs/proxyclip/cls_context59.txt b/downstream/ProxyCLIP_TPAMI/configs/proxyclip/cls_context59.txt new file mode 100644 index 0000000000000000000000000000000000000000..f9fb2a22f62cbd5a5a27cb2677636506fbbbc551 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/configs/proxyclip/cls_context59.txt @@ -0,0 +1,59 @@ +aeroplane +bag +bed +bedclothes +bench +bicycle +bird +boat +book +bottle +building +bus +cabinet +car +cat +ceiling +chair +cloth +computer +cow +cup +curtain +dog +door +fence +floor +flower +food +grass +ground +horse +keyboard +light +motorbike +mountain +mouse +person +plate +platform +pottedplant +road +rock +sheep +shelves +sidewalk +sign +sky +snow +sofa +table +track +train +tree +truck +tvmonitor +wall +water +window +wood \ No newline at end of file diff --git a/downstream/ProxyCLIP_TPAMI/configs/proxyclip/cls_context60.txt b/downstream/ProxyCLIP_TPAMI/configs/proxyclip/cls_context60.txt new file mode 100644 index 0000000000000000000000000000000000000000..a6209938e2a6e57018af0ed6896176a7f1ace54f --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/configs/proxyclip/cls_context60.txt @@ -0,0 +1,60 @@ +background +aeroplane +bag +bed +bedclothes +bench +bicycle +bird +boat +book +bottle +building +bus +cabinet +car +cat +ceiling +chair +cloth +computer +cow +cup +curtain +dog +door +fence +floor +flower +food +grass +ground +horse +keyboard +light +motorbike +mountain +mouse +person +plate +platform +pottedplant +road +rock +sheep +shelves +sidewalk +sign +sky +snow +sofa +table +track +train +tree +truck +tvmonitor +wall +water +window +wood \ No newline at end of file diff --git a/downstream/ProxyCLIP_TPAMI/configs/proxyclip/cls_voc20.txt b/downstream/ProxyCLIP_TPAMI/configs/proxyclip/cls_voc20.txt new file mode 100644 index 0000000000000000000000000000000000000000..3f073de079b698e44eab182776ea0026009b8973 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/configs/proxyclip/cls_voc20.txt @@ -0,0 +1,20 @@ +aeroplane +bicycle +bird +ship +bottle +bus +car +cat +chair +cow +table +dog +horse +motorbike +person +pottedplant +sheep +sofa +train +tvmonitor \ No newline at end of file diff --git a/downstream/ProxyCLIP_TPAMI/configs/proxyclip/cls_voc21.txt b/downstream/ProxyCLIP_TPAMI/configs/proxyclip/cls_voc21.txt new file mode 100644 index 0000000000000000000000000000000000000000..5b8dc7e2b75c5e604fcb772c8fe9bbb877719624 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/configs/proxyclip/cls_voc21.txt @@ -0,0 +1,21 @@ +sky; wall; tree; wood; grass; road; sea; river; mountain; sands; desk; bed; building; cloud; lamp; door; window; wardrobe; ceiling; shelf; curtain; stair; floor; hill; rail; fence +aeroplane +bicycle +bird +ship +bottle +bus +car +cat +chair +cow +table +dog +horse +motorbike +person +pottedplant +sheep +sofa +train +tvmonitor \ No newline at end of file diff --git a/downstream/ProxyCLIP_TPAMI/configs/proxyclip/my_name.txt b/downstream/ProxyCLIP_TPAMI/configs/proxyclip/my_name.txt new file mode 100644 index 0000000000000000000000000000000000000000..40a1011adbfe8f720fb13debca81b6b7a7afa708 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/configs/proxyclip/my_name.txt @@ -0,0 +1,5 @@ +sky +hill +tree +horse +grass \ No newline at end of file diff --git a/downstream/ProxyCLIP_TPAMI/configs/tinyclip_clearclip/base_config.py b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_clearclip/base_config.py new file mode 100644 index 0000000000000000000000000000000000000000..902ea48a00ed6ba57386ba3c31e2a085e92564ae --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_clearclip/base_config.py @@ -0,0 +1,31 @@ +# base configurations +model = dict( + type='TinyCLIPSegmentation', + clip_type='TinyCLIP-ViT-39M-16-Text-19M', + checkpoint=None, + vfm=None, +) + +test_evaluator = dict(type='IoUMetric', iou_metrics=['mIoU']) +default_scope = 'mmseg' +env_cfg = dict( + cudnn_benchmark=True, + mp_cfg=dict(mp_start_method='fork', opencv_num_threads=0), + dist_cfg=dict(backend='nccl'), +) +vis_backends = [dict(type='LocalVisBackend')] +visualizer = dict( + type='SegLocalVisualizer', vis_backends=vis_backends, alpha=1.0, name='visualizer') +log_processor = dict(by_epoch=False) +log_level = 'INFO' +load_from = None +resume = False +test_cfg = dict(type='TestLoop') +default_hooks = dict( + timer=dict(type='IterTimerHook'), + logger=dict(type='LoggerHook', interval=50, log_metric_by_epoch=False), + param_scheduler=dict(type='ParamSchedulerHook'), + checkpoint=dict(type='CheckpointHook', by_epoch=False, interval=2000), + sampler_seed=dict(type='DistSamplerSeedHook'), + visualization=dict(type='SegVisualizationHook', draw=True,interval=20)) + diff --git a/downstream/ProxyCLIP_TPAMI/configs/tinyclip_clearclip/cfg_ade20k_clearclip.py b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_clearclip/cfg_ade20k_clearclip.py new file mode 100644 index 0000000000000000000000000000000000000000..a1ab5d7f97e589a029afbb368a4e439ef521979a --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_clearclip/cfg_ade20k_clearclip.py @@ -0,0 +1,54 @@ +_base_ = './base_config.py' + +# model settings +# 使用TinyCLIP模型进行分割 - 消融实验:clearclip模式(最后一个block使用qq attention,没有残差连接、LayerNorm和MLP) + +model = dict( + name_path="configs/proxyclip/cls_ade20k.txt", + vfm=None, + type="TinyCLIPSegmentation", + clip_type="TinyCLIP-ViT-39M-16-Text-19M", + checkpoint="/mnt/SSD8T/home/wjj/code/DeCLIP_private/checkpoints/TinyCLIP-ViT-39M-16-Text-19M-YFCC15M.pt", + mode="clearclip", +) + +# dataset settings +dataset_type = "ADE20KDataset" +data_root = "/mnt/SSD8T/home/wjj/dataset/ADEChallengeData2016" + +test_pipeline = [ + dict(type="LoadImageFromFile"), + dict(type="Resize", scale=(2048, 448), keep_ratio=True), + dict(type="LoadAnnotations", reduce_zero_label=True), + dict( + type="PackSegInputs", + meta_keys=( + "img_path", + "seg_map_path", + "ori_shape", + "img_shape", + "pad_shape", + "scale_factor", + "flip", + "flip_direction", + "reduce_zero_label", + "resize_shape", + ), + ), +] + +test_dataloader = dict( + batch_size=1, + num_workers=4, + persistent_workers=True, + sampler=dict(type="DefaultSampler", shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + data_prefix=dict( + img_path="images/validation", seg_map_path="annotations/validation" + ), + pipeline=test_pipeline, + ), +) + diff --git a/downstream/ProxyCLIP_TPAMI/configs/tinyclip_clearclip/cfg_city_scapes_clearclip.py b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_clearclip/cfg_city_scapes_clearclip.py new file mode 100644 index 0000000000000000000000000000000000000000..ba582ddfc788175f7947bdc372c8537daaad51a4 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_clearclip/cfg_city_scapes_clearclip.py @@ -0,0 +1,54 @@ +_base_ = './base_config.py' + +# model settings +# 使用TinyCLIP模型进行分割 - 消融实验:clearclip模式(最后一个block使用qq attention,没有残差连接、LayerNorm和MLP) + +model = dict( + name_path="configs/proxyclip/cls_city_scapes.txt", + vfm=None, + type="TinyCLIPSegmentation", + clip_type="TinyCLIP-ViT-39M-16-Text-19M", + checkpoint="/mnt/SSD8T/home/wjj/code/DeCLIP_private/checkpoints/TinyCLIP-ViT-39M-16-Text-19M-YFCC15M.pt", + mode="clearclip", +) + +# dataset settings +dataset_type = "CityscapesDataset" +data_root = "/mnt/SSD8T/home/wjj/dataset/cityscapes" + +test_pipeline = [ + dict(type="LoadImageFromFile"), + dict(type="Resize", scale=(2048, 448), keep_ratio=True), + # add loading annotation after ``Resize`` because ground truth + # does not need to do resize data transform + dict(type="LoadAnnotations"), + dict( + type="PackSegInputs", + meta_keys=( + "img_path", + "seg_map_path", + "ori_shape", + "img_shape", + "pad_shape", + "scale_factor", + "flip", + "flip_direction", + "reduce_zero_label", + "resize_shape", + ), + ), +] + +test_dataloader = dict( + batch_size=1, + num_workers=4, + persistent_workers=True, + sampler=dict(type="DefaultSampler", shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + data_prefix=dict(img_path="leftImg8bit/val", seg_map_path="gtFine/val"), + pipeline=test_pipeline, + ), +) + diff --git a/downstream/ProxyCLIP_TPAMI/configs/tinyclip_clearclip/cfg_coco_object_clearclip.py b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_clearclip/cfg_coco_object_clearclip.py new file mode 100644 index 0000000000000000000000000000000000000000..fb09ba2ad2462200d85ce71de8c4ff128194c5ae --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_clearclip/cfg_coco_object_clearclip.py @@ -0,0 +1,54 @@ +_base_ = './base_config.py' + +# model settings +# 使用TinyCLIP模型进行分割 - 消融实验:clearclip模式(最后一个block使用qq attention,没有残差连接、LayerNorm和MLP) + +model = dict( + name_path="configs/proxyclip/cls_coco_object.txt", + vfm=None, + type="TinyCLIPSegmentation", + clip_type="TinyCLIP-ViT-39M-16-Text-19M", + checkpoint="/mnt/SSD8T/home/wjj/code/DeCLIP_private/checkpoints/TinyCLIP-ViT-39M-16-Text-19M-YFCC15M.pt", + mode="clearclip", + prob_thd=0.3, +) + +# dataset settings +dataset_type = "COCOObjectDataset" +data_root = "/mnt/SSD8T/home/wjj/dataset/coco_obj" + +test_pipeline = [ + dict(type="LoadImageFromFile"), + dict(type="Resize", scale=(2048, 448), keep_ratio=True), + dict(type="LoadAnnotations"), + dict( + type="PackSegInputs", + meta_keys=( + "img_path", + "seg_map_path", + "ori_shape", + "img_shape", + "pad_shape", + "scale_factor", + "flip", + "flip_direction", + "reduce_zero_label", + "resize_shape", + ), + ), +] + +test_dataloader = dict( + batch_size=1, + num_workers=4, + persistent_workers=True, + sampler=dict(type="DefaultSampler", shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + reduce_zero_label=False, + data_prefix=dict(img_path="images/val2017", seg_map_path="annotations/val2017"), + pipeline=test_pipeline, + ), +) + diff --git a/downstream/ProxyCLIP_TPAMI/configs/tinyclip_clearclip/cfg_coco_stuff164k_clearclip.py b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_clearclip/cfg_coco_stuff164k_clearclip.py new file mode 100644 index 0000000000000000000000000000000000000000..217a7608f01fbe767e04c4e3371ab44b2cc28e71 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_clearclip/cfg_coco_stuff164k_clearclip.py @@ -0,0 +1,55 @@ +_base_ = './base_config.py' + +# model settings +# 使用TinyCLIP模型进行分割 - 消融实验:clearclip模式(最后一个block使用qq attention,没有残差连接、LayerNorm和MLP) + +model = dict( + name_path="configs/proxyclip/cls_coco_stuff.txt", + vfm=None, + type="TinyCLIPSegmentation", + clip_type="TinyCLIP-ViT-39M-16-Text-19M", + checkpoint="/mnt/SSD8T/home/wjj/code/DeCLIP_private/checkpoints/TinyCLIP-ViT-39M-16-Text-19M-YFCC15M.pt", + mode="clearclip", +) + +# dataset settings +dataset_type = "COCOStuffDataset" +data_root = "" + +test_pipeline = [ + dict(type="LoadImageFromFile"), + dict(type="Resize", scale=(2048, 448), keep_ratio=True), + dict(type="LoadAnnotations"), + dict( + type="PackSegInputs", + meta_keys=( + "img_path", + "seg_map_path", + "ori_shape", + "img_shape", + "pad_shape", + "scale_factor", + "flip", + "flip_direction", + "reduce_zero_label", + "resize_shape", + ), + ), +] + +test_dataloader = dict( + batch_size=1, + num_workers=4, + persistent_workers=True, + sampler=dict(type="DefaultSampler", shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + data_prefix=dict( + img_path="/mnt/SSD8T/home/wjj/dataset/standard_coco/val2017", + seg_map_path="/mnt/SSD8T/home/wjj/dataset/standard_coco/annotations/val2017", + ), + pipeline=test_pipeline, + ), +) + diff --git a/downstream/ProxyCLIP_TPAMI/configs/tinyclip_clearclip/cfg_context59_clearclip.py b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_clearclip/cfg_context59_clearclip.py new file mode 100644 index 0000000000000000000000000000000000000000..148b5fff46a0796601a52de09e7e6a9cc82e42f6 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_clearclip/cfg_context59_clearclip.py @@ -0,0 +1,55 @@ +_base_ = './base_config.py' + +# model settings +# 使用TinyCLIP模型进行分割 - 消融实验:clearclip模式(最后一个block使用qq attention,没有残差连接、LayerNorm和MLP) + +model = dict( + name_path="configs/proxyclip/cls_context59.txt", + vfm=None, + type="TinyCLIPSegmentation", + clip_type="TinyCLIP-ViT-39M-16-Text-19M", + checkpoint="/mnt/SSD8T/home/wjj/code/DeCLIP_private/checkpoints/TinyCLIP-ViT-39M-16-Text-19M-YFCC15M.pt", + mode="clearclip", +) + +# dataset settings +dataset_type = "PascalContext59Dataset" +data_root = "/mnt/SSD8T/home/wjj/dataset/VOCdevkit/VOC2010" + +test_pipeline = [ + dict(type="LoadImageFromFile"), + dict(type="Resize", scale=(2048, 448), keep_ratio=True), + dict(type="LoadAnnotations", reduce_zero_label=True), + dict( + type="PackSegInputs", + meta_keys=( + "img_path", + "seg_map_path", + "ori_shape", + "img_shape", + "pad_shape", + "scale_factor", + "flip", + "flip_direction", + "reduce_zero_label", + "resize_shape", + ), + ), +] + +test_dataloader = dict( + batch_size=1, + num_workers=4, + persistent_workers=True, + sampler=dict(type="DefaultSampler", shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + data_prefix=dict( + img_path="JPEGImages", seg_map_path="SegmentationClassContext" + ), + ann_file="ImageSets/SegmentationContext/val.txt", + pipeline=test_pipeline, + ), +) + diff --git a/downstream/ProxyCLIP_TPAMI/configs/tinyclip_clearclip/cfg_context60_clearclip.py b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_clearclip/cfg_context60_clearclip.py new file mode 100644 index 0000000000000000000000000000000000000000..b76ee98be6b0deda5d575790efa6b584f596dd55 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_clearclip/cfg_context60_clearclip.py @@ -0,0 +1,57 @@ +_base_ = './base_config.py' + +# model settings +# 使用TinyCLIP模型进行分割 - 消融实验:clearclip模式(最后一个block使用qq attention,没有残差连接、LayerNorm和MLP) + +model = dict( + name_path="configs/proxyclip/cls_context60.txt", + vfm=None, + type="TinyCLIPSegmentation", + clip_type="TinyCLIP-ViT-39M-16-Text-19M", + checkpoint="/mnt/SSD8T/home/wjj/code/DeCLIP_private/checkpoints/TinyCLIP-ViT-39M-16-Text-19M-YFCC15M.pt", + mode="clearclip", + prob_thd=0.15, + logit_scale=40, +) + +# dataset settings +dataset_type = "PascalContext60Dataset" +data_root = "/mnt/SSD8T/home/wjj/dataset/VOCdevkit/VOC2010" + +test_pipeline = [ + dict(type="LoadImageFromFile"), + dict(type="Resize", scale=(2048, 448), keep_ratio=True), + dict(type="LoadAnnotations"), + dict( + type="PackSegInputs", + meta_keys=( + "img_path", + "seg_map_path", + "ori_shape", + "img_shape", + "pad_shape", + "scale_factor", + "flip", + "flip_direction", + "reduce_zero_label", + "resize_shape", + ), + ), +] + +test_dataloader = dict( + batch_size=1, + num_workers=4, + persistent_workers=True, + sampler=dict(type="DefaultSampler", shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + data_prefix=dict( + img_path="JPEGImages", seg_map_path="SegmentationClassContext" + ), + ann_file="ImageSets/SegmentationContext/val.txt", + pipeline=test_pipeline, + ), +) + diff --git a/downstream/ProxyCLIP_TPAMI/configs/tinyclip_clearclip/cfg_voc20_clearclip.py b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_clearclip/cfg_voc20_clearclip.py new file mode 100644 index 0000000000000000000000000000000000000000..16cc645f6de9426ed99bb3840a129c1595354217 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_clearclip/cfg_voc20_clearclip.py @@ -0,0 +1,53 @@ +_base_ = './base_config.py' + +# model settings +# 使用TinyCLIP模型进行分割 - 消融实验:clearclip模式(最后一个block使用qq attention,没有残差连接、LayerNorm和MLP) + +model = dict( + name_path="configs/proxyclip/cls_voc20.txt", + vfm=None, + type="TinyCLIPSegmentation", + clip_type="TinyCLIP-ViT-39M-16-Text-19M", + checkpoint="/mnt/SSD8T/home/wjj/code/DeCLIP_private/checkpoints/TinyCLIP-ViT-39M-16-Text-19M-YFCC15M.pt", + mode="clearclip", +) + +# dataset settings +dataset_type = "PascalVOC20Dataset" +data_root = "/mnt/SSD8T/home/wjj/dataset/VOCdevkit/VOC2012" + +test_pipeline = [ + dict(type="LoadImageFromFile"), + dict(type="Resize", scale=(2048, 448), keep_ratio=True), + dict(type="LoadAnnotations"), + dict( + type="PackSegInputs", + meta_keys=( + "img_path", + "seg_map_path", + "ori_shape", + "img_shape", + "pad_shape", + "scale_factor", + "flip", + "flip_direction", + "reduce_zero_label", + "resize_shape", + ), + ), +] + +test_dataloader = dict( + batch_size=1, + num_workers=4, + persistent_workers=True, + sampler=dict(type="DefaultSampler", shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + data_prefix=dict(img_path="JPEGImages", seg_map_path="SegmentationClass"), + ann_file="ImageSets/Segmentation/val.txt", + pipeline=test_pipeline, + ), +) + diff --git a/downstream/ProxyCLIP_TPAMI/configs/tinyclip_clearclip/cfg_voc21_clearclip.py b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_clearclip/cfg_voc21_clearclip.py new file mode 100644 index 0000000000000000000000000000000000000000..b3f105273a51c9415fba152af8eed62fddfc7380 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_clearclip/cfg_voc21_clearclip.py @@ -0,0 +1,55 @@ +_base_ = './base_config.py' + +# model settings +# 使用TinyCLIP模型进行分割 - 消融实验:clearclip模式(最后一个block使用qq attention,没有残差连接、LayerNorm和MLP) + +model = dict( + name_path="configs/proxyclip/cls_voc21.txt", + vfm=None, + type="TinyCLIPSegmentation", + clip_type="TinyCLIP-ViT-39M-16-Text-19M", + checkpoint="/mnt/SSD8T/home/wjj/code/DeCLIP_private/checkpoints/TinyCLIP-ViT-39M-16-Text-19M-YFCC15M.pt", + mode="clearclip", + prob_thd=0.5, + logit_scale=80, +) + +# dataset settings +dataset_type = "PascalVOCDataset" +data_root = "/mnt/SSD8T/home/wjj/dataset/VOCdevkit/VOC2012" + +test_pipeline = [ + dict(type="LoadImageFromFile"), + dict(type="Resize", scale=(2048, 448), keep_ratio=True), + dict(type="LoadAnnotations"), + dict( + type="PackSegInputs", + meta_keys=( + "img_path", + "seg_map_path", + "ori_shape", + "img_shape", + "pad_shape", + "scale_factor", + "flip", + "flip_direction", + "reduce_zero_label", + "resize_shape", + ), + ), +] + +test_dataloader = dict( + batch_size=1, + num_workers=4, + persistent_workers=True, + sampler=dict(type="DefaultSampler", shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + data_prefix=dict(img_path="JPEGImages", seg_map_path="SegmentationClass"), + ann_file="ImageSets/Segmentation/val.txt", + pipeline=test_pipeline, + ), +) + diff --git a/downstream/ProxyCLIP_TPAMI/configs/tinyclip_csa_raw/base_config.py b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_csa_raw/base_config.py new file mode 100644 index 0000000000000000000000000000000000000000..902ea48a00ed6ba57386ba3c31e2a085e92564ae --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_csa_raw/base_config.py @@ -0,0 +1,31 @@ +# base configurations +model = dict( + type='TinyCLIPSegmentation', + clip_type='TinyCLIP-ViT-39M-16-Text-19M', + checkpoint=None, + vfm=None, +) + +test_evaluator = dict(type='IoUMetric', iou_metrics=['mIoU']) +default_scope = 'mmseg' +env_cfg = dict( + cudnn_benchmark=True, + mp_cfg=dict(mp_start_method='fork', opencv_num_threads=0), + dist_cfg=dict(backend='nccl'), +) +vis_backends = [dict(type='LocalVisBackend')] +visualizer = dict( + type='SegLocalVisualizer', vis_backends=vis_backends, alpha=1.0, name='visualizer') +log_processor = dict(by_epoch=False) +log_level = 'INFO' +load_from = None +resume = False +test_cfg = dict(type='TestLoop') +default_hooks = dict( + timer=dict(type='IterTimerHook'), + logger=dict(type='LoggerHook', interval=50, log_metric_by_epoch=False), + param_scheduler=dict(type='ParamSchedulerHook'), + checkpoint=dict(type='CheckpointHook', by_epoch=False, interval=2000), + sampler_seed=dict(type='DistSamplerSeedHook'), + visualization=dict(type='SegVisualizationHook', draw=True,interval=20)) + diff --git a/downstream/ProxyCLIP_TPAMI/configs/tinyclip_csa_raw/cfg_ade20k_csa_raw.py b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_csa_raw/cfg_ade20k_csa_raw.py new file mode 100644 index 0000000000000000000000000000000000000000..05cc1edaac55c5c41ee8f35045e47c9ccc0c34d2 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_csa_raw/cfg_ade20k_csa_raw.py @@ -0,0 +1,53 @@ +_base_ = './base_config.py' + +# model settings +# 使用TinyCLIP模型进行分割 - 消融实验:csa_raw模式(使用原始权重,CSA attention + 残差连接+MLP) + +model = dict( + name_path="configs/proxyclip/cls_ade20k.txt", + vfm=None, + type="TinyCLIPSegmentation", + clip_type="TinyCLIP-ViT-39M-16-Text-19M", + checkpoint="/mnt/SSD8T/home/wjj/code/DeCLIP_private/checkpoints/TinyCLIP-ViT-39M-16-Text-19M-YFCC15M.pt", + mode="csa_raw", +) + +# dataset settings +dataset_type = "ADE20KDataset" +data_root = "/mnt/SSD8T/home/wjj/dataset/ADEChallengeData2016" + +test_pipeline = [ + dict(type="LoadImageFromFile"), + dict(type="Resize", scale=(4096, 448), keep_ratio=True), + dict(type="LoadAnnotations", reduce_zero_label=True), + dict( + type="PackSegInputs", + meta_keys=( + "img_path", + "seg_map_path", + "ori_shape", + "img_shape", + "pad_shape", + "scale_factor", + "flip", + "flip_direction", + "reduce_zero_label", + "resize_shape", + ), + ), +] + +test_dataloader = dict( + batch_size=1, + num_workers=4, + persistent_workers=True, + sampler=dict(type="DefaultSampler", shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + data_prefix=dict( + img_path="images/validation", seg_map_path="annotations/validation" + ), + pipeline=test_pipeline, + ), +) diff --git a/downstream/ProxyCLIP_TPAMI/configs/tinyclip_csa_raw/cfg_city_scapes_csa_raw.py b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_csa_raw/cfg_city_scapes_csa_raw.py new file mode 100644 index 0000000000000000000000000000000000000000..de80cbfcca1ba4d0ad56af1aeebf26f4a216ffde --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_csa_raw/cfg_city_scapes_csa_raw.py @@ -0,0 +1,53 @@ +_base_ = './base_config.py' + +# model settings +# 使用TinyCLIP模型进行分割 - 消融实验:csa_raw模式(使用原始权重,CSA attention + 残差连接+MLP) + +model = dict( + name_path="configs/proxyclip/cls_city_scapes.txt", + vfm=None, + type="TinyCLIPSegmentation", + clip_type="TinyCLIP-ViT-39M-16-Text-19M", + checkpoint="/mnt/SSD8T/home/wjj/code/DeCLIP_private/checkpoints/TinyCLIP-ViT-39M-16-Text-19M-YFCC15M.pt", + mode="csa_raw", +) + +# dataset settings +dataset_type = "CityscapesDataset" +data_root = "/mnt/SSD8T/home/wjj/dataset/cityscapes" + +test_pipeline = [ + dict(type="LoadImageFromFile"), + dict(type="Resize", scale=(4096, 448), keep_ratio=True), + # add loading annotation after ``Resize`` because ground truth + # does not need to do resize data transform + dict(type="LoadAnnotations"), + dict( + type="PackSegInputs", + meta_keys=( + "img_path", + "seg_map_path", + "ori_shape", + "img_shape", + "pad_shape", + "scale_factor", + "flip", + "flip_direction", + "reduce_zero_label", + "resize_shape", + ), + ), +] + +test_dataloader = dict( + batch_size=1, + num_workers=4, + persistent_workers=True, + sampler=dict(type="DefaultSampler", shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + data_prefix=dict(img_path="leftImg8bit/val", seg_map_path="gtFine/val"), + pipeline=test_pipeline, + ), +) diff --git a/downstream/ProxyCLIP_TPAMI/configs/tinyclip_csa_raw/cfg_coco_object_csa_raw.py b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_csa_raw/cfg_coco_object_csa_raw.py new file mode 100644 index 0000000000000000000000000000000000000000..297377b1f4e7ab5a62f372adc760b619beb79cb7 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_csa_raw/cfg_coco_object_csa_raw.py @@ -0,0 +1,53 @@ +_base_ = './base_config.py' + +# model settings +# 使用TinyCLIP模型进行分割 - 消融实验:csa_raw模式(使用原始权重,CSA attention + 残差连接+MLP) + +model = dict( + name_path="configs/proxyclip/cls_coco_object.txt", + vfm=None, + type="TinyCLIPSegmentation", + clip_type="TinyCLIP-ViT-39M-16-Text-19M", + checkpoint="/mnt/SSD8T/home/wjj/code/DeCLIP_private/checkpoints/TinyCLIP-ViT-39M-16-Text-19M-YFCC15M.pt", + mode="csa_raw", + prob_thd=0.3, +) + +# dataset settings +dataset_type = "COCOObjectDataset" +data_root = "/mnt/SSD8T/home/wjj/dataset/coco_obj" + +test_pipeline = [ + dict(type="LoadImageFromFile"), + dict(type="Resize", scale=(2048, 448), keep_ratio=True), + dict(type="LoadAnnotations"), + dict( + type="PackSegInputs", + meta_keys=( + "img_path", + "seg_map_path", + "ori_shape", + "img_shape", + "pad_shape", + "scale_factor", + "flip", + "flip_direction", + "reduce_zero_label", + "resize_shape", + ), + ), +] + +test_dataloader = dict( + batch_size=1, + num_workers=4, + persistent_workers=True, + sampler=dict(type="DefaultSampler", shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + reduce_zero_label=False, + data_prefix=dict(img_path="images/val2017", seg_map_path="annotations/val2017"), + pipeline=test_pipeline, + ), +) diff --git a/downstream/ProxyCLIP_TPAMI/configs/tinyclip_csa_raw/cfg_coco_stuff164k_csa_raw.py b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_csa_raw/cfg_coco_stuff164k_csa_raw.py new file mode 100644 index 0000000000000000000000000000000000000000..8987300253a276c954d5935019e72c2efd085c00 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_csa_raw/cfg_coco_stuff164k_csa_raw.py @@ -0,0 +1,54 @@ +_base_ = './base_config.py' + +# model settings +# 使用TinyCLIP模型进行分割 - 消融实验:csa_raw模式(使用原始权重,CSA attention + 残差连接+MLP) + +model = dict( + name_path="configs/proxyclip/cls_coco_stuff.txt", + vfm=None, + type="TinyCLIPSegmentation", + clip_type="TinyCLIP-ViT-39M-16-Text-19M", + checkpoint="/mnt/SSD8T/home/wjj/code/DeCLIP_private/checkpoints/TinyCLIP-ViT-39M-16-Text-19M-YFCC15M.pt", + mode="csa_raw", +) + +# dataset settings +dataset_type = "COCOStuffDataset" +data_root = "" + +test_pipeline = [ + dict(type="LoadImageFromFile"), + dict(type="Resize", scale=(4096, 448), keep_ratio=True), + dict(type="LoadAnnotations"), + dict( + type="PackSegInputs", + meta_keys=( + "img_path", + "seg_map_path", + "ori_shape", + "img_shape", + "pad_shape", + "scale_factor", + "flip", + "flip_direction", + "reduce_zero_label", + "resize_shape", + ), + ), +] + +test_dataloader = dict( + batch_size=1, + num_workers=4, + persistent_workers=True, + sampler=dict(type="DefaultSampler", shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + data_prefix=dict( + img_path="/mnt/SSD8T/home/wjj/dataset/standard_coco/val2017", + seg_map_path="/mnt/SSD8T/home/wjj/dataset/standard_coco/annotations/val2017", + ), + pipeline=test_pipeline, + ), +) diff --git a/downstream/ProxyCLIP_TPAMI/configs/tinyclip_csa_raw/cfg_context59_csa_raw.py b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_csa_raw/cfg_context59_csa_raw.py new file mode 100644 index 0000000000000000000000000000000000000000..0035d6e56732970d785614057ca2541b5cd5c9e4 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_csa_raw/cfg_context59_csa_raw.py @@ -0,0 +1,54 @@ +_base_ = './base_config.py' + +# model settings +# 使用TinyCLIP模型进行分割 - 消融实验:csa_raw模式(使用原始权重,CSA attention + 残差连接+MLP) + +model = dict( + name_path="configs/proxyclip/cls_context59.txt", + vfm=None, + type="TinyCLIPSegmentation", + clip_type="TinyCLIP-ViT-39M-16-Text-19M", + checkpoint="/mnt/SSD8T/home/wjj/code/DeCLIP_private/checkpoints/TinyCLIP-ViT-39M-16-Text-19M-YFCC15M.pt", + mode="csa_raw", +) + +# dataset settings +dataset_type = "PascalContext59Dataset" +data_root = "/mnt/SSD8T/home/wjj/dataset/VOCdevkit/VOC2010" + +test_pipeline = [ + dict(type="LoadImageFromFile"), + dict(type="Resize", scale=(4096, 448), keep_ratio=True), + dict(type="LoadAnnotations", reduce_zero_label=True), + dict( + type="PackSegInputs", + meta_keys=( + "img_path", + "seg_map_path", + "ori_shape", + "img_shape", + "pad_shape", + "scale_factor", + "flip", + "flip_direction", + "reduce_zero_label", + "resize_shape", + ), + ), +] + +test_dataloader = dict( + batch_size=1, + num_workers=4, + persistent_workers=True, + sampler=dict(type="DefaultSampler", shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + data_prefix=dict( + img_path="JPEGImages", seg_map_path="SegmentationClassContext" + ), + ann_file="ImageSets/SegmentationContext/val.txt", + pipeline=test_pipeline, + ), +) diff --git a/downstream/ProxyCLIP_TPAMI/configs/tinyclip_csa_raw/cfg_context60_csa_raw.py b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_csa_raw/cfg_context60_csa_raw.py new file mode 100644 index 0000000000000000000000000000000000000000..be98a144d6e6dfbd5aee10564fe8ca079bea99d8 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_csa_raw/cfg_context60_csa_raw.py @@ -0,0 +1,56 @@ +_base_ = './base_config.py' + +# model settings +# 使用TinyCLIP模型进行分割 - 消融实验:csa_raw模式(使用原始权重,CSA attention + 残差连接+MLP) + +model = dict( + name_path="configs/proxyclip/cls_context60.txt", + vfm=None, + type="TinyCLIPSegmentation", + clip_type="TinyCLIP-ViT-39M-16-Text-19M", + checkpoint="/mnt/SSD8T/home/wjj/code/DeCLIP_private/checkpoints/TinyCLIP-ViT-39M-16-Text-19M-YFCC15M.pt", + mode="csa_raw", + prob_thd=0.15, + logit_scale=40, +) + +# dataset settings +dataset_type = "PascalContext60Dataset" +data_root = "/mnt/SSD8T/home/wjj/dataset/VOCdevkit/VOC2010" + +test_pipeline = [ + dict(type="LoadImageFromFile"), + dict(type="Resize", scale=(4096, 448), keep_ratio=True), + dict(type="LoadAnnotations"), + dict( + type="PackSegInputs", + meta_keys=( + "img_path", + "seg_map_path", + "ori_shape", + "img_shape", + "pad_shape", + "scale_factor", + "flip", + "flip_direction", + "reduce_zero_label", + "resize_shape", + ), + ), +] + +test_dataloader = dict( + batch_size=1, + num_workers=4, + persistent_workers=True, + sampler=dict(type="DefaultSampler", shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + data_prefix=dict( + img_path="JPEGImages", seg_map_path="SegmentationClassContext" + ), + ann_file="ImageSets/SegmentationContext/val.txt", + pipeline=test_pipeline, + ), +) diff --git a/downstream/ProxyCLIP_TPAMI/configs/tinyclip_csa_raw/cfg_voc20_csa_raw.py b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_csa_raw/cfg_voc20_csa_raw.py new file mode 100644 index 0000000000000000000000000000000000000000..870bc7ae93fb7f355505b279c32296b5daafc285 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_csa_raw/cfg_voc20_csa_raw.py @@ -0,0 +1,52 @@ +_base_ = './base_config.py' + +# model settings +# 使用TinyCLIP模型进行分割 - 消融实验:csa_raw模式(使用原始权重,CSA attention + 残差连接+MLP) + +model = dict( + name_path="configs/proxyclip/cls_voc20.txt", + vfm=None, + type="TinyCLIPSegmentation", + clip_type="TinyCLIP-ViT-39M-16-Text-19M", + checkpoint="/mnt/SSD8T/home/wjj/code/DeCLIP_private/checkpoints/TinyCLIP-ViT-39M-16-Text-19M-YFCC15M.pt", + mode="csa_raw", +) + +# dataset settings +dataset_type = "PascalVOC20Dataset" +data_root = "/mnt/SSD8T/home/wjj/dataset/VOCdevkit/VOC2012" + +test_pipeline = [ + dict(type="LoadImageFromFile"), + dict(type="Resize", scale=(4096, 448), keep_ratio=True), + dict(type="LoadAnnotations"), + dict( + type="PackSegInputs", + meta_keys=( + "img_path", + "seg_map_path", + "ori_shape", + "img_shape", + "pad_shape", + "scale_factor", + "flip", + "flip_direction", + "reduce_zero_label", + "resize_shape", + ), + ), +] + +test_dataloader = dict( + batch_size=1, + num_workers=4, + persistent_workers=True, + sampler=dict(type="DefaultSampler", shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + data_prefix=dict(img_path="JPEGImages", seg_map_path="SegmentationClass"), + ann_file="ImageSets/Segmentation/val.txt", + pipeline=test_pipeline, + ), +) diff --git a/downstream/ProxyCLIP_TPAMI/configs/tinyclip_csa_raw/cfg_voc21_csa_raw.py b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_csa_raw/cfg_voc21_csa_raw.py new file mode 100644 index 0000000000000000000000000000000000000000..8f974d2e3fe59831fb76962a9cd6f51a154f9fa7 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_csa_raw/cfg_voc21_csa_raw.py @@ -0,0 +1,54 @@ +_base_ = './base_config.py' + +# model settings +# 使用TinyCLIP模型进行分割 - 消融实验:csa_raw模式(使用原始权重,CSA attention + 残差连接+MLP) + +model = dict( + name_path="configs/proxyclip/cls_voc21.txt", + vfm=None, + type="TinyCLIPSegmentation", + clip_type="TinyCLIP-ViT-39M-16-Text-19M", + checkpoint="/mnt/SSD8T/home/wjj/code/DeCLIP_private/checkpoints/TinyCLIP-ViT-39M-16-Text-19M-YFCC15M.pt", + mode="csa_raw", + prob_thd=0.5, + logit_scale=80, +) + +# dataset settings +dataset_type = "PascalVOCDataset" +data_root = "/mnt/SSD8T/home/wjj/dataset/VOCdevkit/VOC2012" + +test_pipeline = [ + dict(type="LoadImageFromFile"), + dict(type="Resize", scale=(4096, 448), keep_ratio=True), + dict(type="LoadAnnotations"), + dict( + type="PackSegInputs", + meta_keys=( + "img_path", + "seg_map_path", + "ori_shape", + "img_shape", + "pad_shape", + "scale_factor", + "flip", + "flip_direction", + "reduce_zero_label", + "resize_shape", + ), + ), +] + +test_dataloader = dict( + batch_size=1, + num_workers=4, + persistent_workers=True, + sampler=dict(type="DefaultSampler", shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + data_prefix=dict(img_path="JPEGImages", seg_map_path="SegmentationClass"), + ann_file="ImageSets/Segmentation/val.txt", + pipeline=test_pipeline, + ), +) diff --git a/downstream/ProxyCLIP_TPAMI/configs/tinyclip_declip/base_config.py b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_declip/base_config.py new file mode 100644 index 0000000000000000000000000000000000000000..902ea48a00ed6ba57386ba3c31e2a085e92564ae --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_declip/base_config.py @@ -0,0 +1,31 @@ +# base configurations +model = dict( + type='TinyCLIPSegmentation', + clip_type='TinyCLIP-ViT-39M-16-Text-19M', + checkpoint=None, + vfm=None, +) + +test_evaluator = dict(type='IoUMetric', iou_metrics=['mIoU']) +default_scope = 'mmseg' +env_cfg = dict( + cudnn_benchmark=True, + mp_cfg=dict(mp_start_method='fork', opencv_num_threads=0), + dist_cfg=dict(backend='nccl'), +) +vis_backends = [dict(type='LocalVisBackend')] +visualizer = dict( + type='SegLocalVisualizer', vis_backends=vis_backends, alpha=1.0, name='visualizer') +log_processor = dict(by_epoch=False) +log_level = 'INFO' +load_from = None +resume = False +test_cfg = dict(type='TestLoop') +default_hooks = dict( + timer=dict(type='IterTimerHook'), + logger=dict(type='LoggerHook', interval=50, log_metric_by_epoch=False), + param_scheduler=dict(type='ParamSchedulerHook'), + checkpoint=dict(type='CheckpointHook', by_epoch=False, interval=2000), + sampler_seed=dict(type='DistSamplerSeedHook'), + visualization=dict(type='SegVisualizationHook', draw=True,interval=20)) + diff --git a/downstream/ProxyCLIP_TPAMI/configs/tinyclip_declip/cfg_ade20k.py b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_declip/cfg_ade20k.py new file mode 100644 index 0000000000000000000000000000000000000000..75192d401636bac309f20ab16dd27f1e70af7d77 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_declip/cfg_ade20k.py @@ -0,0 +1,40 @@ +_base_ = './base_config.py' + +# model settings +# 使用TinyCLIP模型进行分割 + +model = dict( + name_path='configs/proxyclip/cls_ade20k.txt', + vfm=None, + type='TinyCLIPSegmentation', + clip_type='TinyCLIP-ViT-39M-16-Text-19M', + checkpoint='/mnt/SSD8T/home/wjj/code/DeCLIP_private/logs/TinyCLIP_39M_DeCLIP+_dinov2B_csa_560_0.25_1.0_0.05_alpha0.4/checkpoints/epoch_6.pt', + mode="csa", +) + +# dataset settings +dataset_type = 'ADE20KDataset' +data_root = '/mnt/SSD8T/home/wjj/dataset/ADEChallengeData2016' + +test_pipeline = [ + dict(type='LoadImageFromFile'), + dict(type='Resize', scale=(4096, 448), keep_ratio=True), + dict(type='LoadAnnotations', reduce_zero_label=True), + dict(type='PackSegInputs', meta_keys=('img_path', 'seg_map_path', 'ori_shape', + 'img_shape', 'pad_shape', 'scale_factor', 'flip', + 'flip_direction', 'reduce_zero_label','resize_shape')) +] + +test_dataloader = dict( + batch_size=1, + num_workers=4, + persistent_workers=True, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + data_prefix=dict( + img_path='images/validation', + seg_map_path='annotations/validation'), + pipeline=test_pipeline)) + diff --git a/downstream/ProxyCLIP_TPAMI/configs/tinyclip_declip/cfg_city_scapes.py b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_declip/cfg_city_scapes.py new file mode 100644 index 0000000000000000000000000000000000000000..fe7bbc71b5015c293ad4d67638948e87daea5bd7 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_declip/cfg_city_scapes.py @@ -0,0 +1,41 @@ +_base_ = './base_config.py' + +# model settings +# 使用TinyCLIP模型进行分割 + +model = dict( + name_path='configs/proxyclip/cls_city_scapes.txt', + vfm=None, + type='TinyCLIPSegmentation', + clip_type='TinyCLIP-ViT-39M-16-Text-19M', + checkpoint='/mnt/SSD8T/home/wjj/code/DeCLIP_private/logs/TinyCLIP_39M_DeCLIP+_dinov2B_csa_560_0.25_1.0_0.05_alpha0.4/checkpoints/epoch_6.pt', + mode="csa", +) + +# dataset settings +dataset_type = 'CityscapesDataset' +data_root = '/mnt/SSD8T/home/wjj/dataset/cityscapes' + +test_pipeline = [ + dict(type='LoadImageFromFile'), + dict(type='Resize', scale=(4096, 560), keep_ratio=True), + # add loading annotation after ``Resize`` because ground truth + # does not need to do resize data transform + dict(type='LoadAnnotations'), + dict(type='PackSegInputs', meta_keys=('img_path', 'seg_map_path', 'ori_shape', + 'img_shape', 'pad_shape', 'scale_factor', 'flip', + 'flip_direction', 'reduce_zero_label','resize_shape')) +] + +test_dataloader = dict( + batch_size=1, + num_workers=4, + persistent_workers=True, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + data_prefix=dict( + img_path='leftImg8bit/val', seg_map_path='gtFine/val'), + pipeline=test_pipeline)) + diff --git a/downstream/ProxyCLIP_TPAMI/configs/tinyclip_declip/cfg_coco_object.py b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_declip/cfg_coco_object.py new file mode 100644 index 0000000000000000000000000000000000000000..8d103180fc49713e2e8547d74caf7b15d653df12 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_declip/cfg_coco_object.py @@ -0,0 +1,41 @@ +_base_ = './base_config.py' + +# model settings +# 使用TinyCLIP模型进行分割 + +model = dict( + name_path='configs/proxyclip/cls_coco_object.txt', + vfm=None, + type='TinyCLIPSegmentation', + clip_type='TinyCLIP-ViT-39M-16-Text-19M', + checkpoint='/mnt/SSD8T/home/wjj/code/DeCLIP_private/logs/TinyCLIP_39M_DeCLIP+_dinov2B_csa_560_0.25_1.0_0.05_alpha0.4/checkpoints/epoch_6.pt', + mode="csa", + prob_thd=0.3, +) + +# dataset settings +dataset_type = 'COCOObjectDataset' +data_root = '/mnt/SSD8T/home/wjj/dataset/coco_obj' + +test_pipeline = [ + dict(type='LoadImageFromFile'), + dict(type='Resize', scale=(2048, 448), keep_ratio=True), + dict(type='LoadAnnotations'), + dict(type='PackSegInputs', meta_keys=('img_path', 'seg_map_path', 'ori_shape', + 'img_shape', 'pad_shape', 'scale_factor', 'flip', + 'flip_direction', 'reduce_zero_label','resize_shape')) +] + +test_dataloader = dict( + batch_size=1, + num_workers=4, + persistent_workers=True, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + reduce_zero_label=False, + data_prefix=dict( + img_path='images/val2017', seg_map_path='annotations/val2017'), + pipeline=test_pipeline)) + diff --git a/downstream/ProxyCLIP_TPAMI/configs/tinyclip_declip/cfg_coco_stuff164k.py b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_declip/cfg_coco_stuff164k.py new file mode 100644 index 0000000000000000000000000000000000000000..27ae2267eae68b9a099ba132a4b16166b3c80559 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_declip/cfg_coco_stuff164k.py @@ -0,0 +1,40 @@ +_base_ = './base_config.py' + +# model settings +# 使用TinyCLIP模型进行分割 + +model = dict( + name_path='configs/proxyclip/cls_coco_stuff.txt', + vfm=None, + type='TinyCLIPSegmentation', + clip_type='TinyCLIP-ViT-39M-16-Text-19M', + checkpoint='/mnt/SSD8T/home/wjj/code/DeCLIP_private/logs/TinyCLIP_39M_DeCLIP+_dinov2B_csa_560_0.25_1.0_0.05_alpha0.4/checkpoints/epoch_6.pt', + mode="csa", +) + +# dataset settings +dataset_type = 'COCOStuffDataset' +data_root = '' + +test_pipeline = [ + dict(type='LoadImageFromFile'), + dict(type='Resize', scale=(4096, 448), keep_ratio=True), + dict(type='LoadAnnotations'), + dict(type='PackSegInputs', meta_keys=('img_path', 'seg_map_path', 'ori_shape', + 'img_shape', 'pad_shape', 'scale_factor', 'flip', + 'flip_direction', 'reduce_zero_label','resize_shape')) + ] + +test_dataloader = dict( + batch_size=1, + num_workers=4, + persistent_workers=True, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + data_prefix=dict( + img_path='/mnt/SSD8T/home/wjj/dataset/standard_coco/val2017', + seg_map_path='/mnt/SSD8T/home/wjj/dataset/standard_coco/annotations/val2017'), + pipeline=test_pipeline)) + diff --git a/downstream/ProxyCLIP_TPAMI/configs/tinyclip_declip/cfg_context59.py b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_declip/cfg_context59.py new file mode 100644 index 0000000000000000000000000000000000000000..386f2e34769d2cba911f232dc37717a9891d046e --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_declip/cfg_context59.py @@ -0,0 +1,40 @@ +_base_ = './base_config.py' + +# model settings +# 使用TinyCLIP模型进行分割 + +model = dict( + name_path='configs/proxyclip/cls_context59.txt', + vfm=None, + type='TinyCLIPSegmentation', + clip_type='TinyCLIP-ViT-39M-16-Text-19M', + checkpoint='/mnt/SSD8T/home/wjj/code/DeCLIP_private/logs/TinyCLIP_39M_DeCLIP+_dinov2B_csa_560_0.25_1.0_0.05_alpha0.4/checkpoints/epoch_6.pt', + mode="csa", +) + +# dataset settings +dataset_type = 'PascalContext59Dataset' +data_root = '/mnt/SSD8T/home/wjj/dataset/VOCdevkit/VOC2010' + +test_pipeline = [ + dict(type='LoadImageFromFile'), + dict(type='Resize', scale=(4096, 448), keep_ratio=True), + dict(type='LoadAnnotations', reduce_zero_label=True), + dict(type='PackSegInputs', meta_keys=('img_path', 'seg_map_path', 'ori_shape', + 'img_shape', 'pad_shape', 'scale_factor', 'flip', + 'flip_direction', 'reduce_zero_label','resize_shape')) +] + +test_dataloader = dict( + batch_size=1, + num_workers=4, + persistent_workers=True, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + data_prefix=dict( + img_path='JPEGImages', seg_map_path='SegmentationClassContext'), + ann_file='ImageSets/SegmentationContext/val.txt', + pipeline=test_pipeline)) + diff --git a/downstream/ProxyCLIP_TPAMI/configs/tinyclip_declip/cfg_context60.py b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_declip/cfg_context60.py new file mode 100644 index 0000000000000000000000000000000000000000..dbc796101e59ef89d67a3f2d976b297dca0fc1c5 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_declip/cfg_context60.py @@ -0,0 +1,42 @@ +_base_ = './base_config.py' + +# model settings +# 使用TinyCLIP模型进行分割 + +model = dict( + name_path='configs/proxyclip/cls_context60.txt', + vfm=None, + type='TinyCLIPSegmentation', + clip_type='TinyCLIP-ViT-39M-16-Text-19M', + checkpoint='/mnt/SSD8T/home/wjj/code/DeCLIP_private/logs/TinyCLIP_39M_DeCLIP+_dinov2B_csa_560_0.25_1.0_0.05_alpha0.4/checkpoints/epoch_6.pt', + mode="csa", + prob_thd=0.15, + logit_scale=40, +) + +# dataset settings +dataset_type = 'PascalContext60Dataset' +data_root = '/mnt/SSD8T/home/wjj/dataset/VOCdevkit/VOC2010' + +test_pipeline = [ + dict(type='LoadImageFromFile'), + dict(type='Resize', scale=(4096, 448), keep_ratio=True), + dict(type='LoadAnnotations'), + dict(type='PackSegInputs', meta_keys=('img_path', 'seg_map_path', 'ori_shape', + 'img_shape', 'pad_shape', 'scale_factor', 'flip', + 'flip_direction', 'reduce_zero_label','resize_shape')) +] + +test_dataloader = dict( + batch_size=1, + num_workers=4, + persistent_workers=True, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + data_prefix=dict( + img_path='JPEGImages', seg_map_path='SegmentationClassContext'), + ann_file='ImageSets/SegmentationContext/val.txt', + pipeline=test_pipeline)) + diff --git a/downstream/ProxyCLIP_TPAMI/configs/tinyclip_declip/cfg_voc20.py b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_declip/cfg_voc20.py new file mode 100644 index 0000000000000000000000000000000000000000..b5680a10e2667a6d0f5ca63e967185b6b71cee70 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_declip/cfg_voc20.py @@ -0,0 +1,40 @@ +_base_ = './base_config.py' + +# model settings +# 使用TinyCLIP模型进行分割 + +model = dict( + name_path='configs/proxyclip/cls_voc20.txt', + vfm=None, + type='TinyCLIPSegmentation', + clip_type='TinyCLIP-ViT-39M-16-Text-19M', + checkpoint='/mnt/SSD8T/home/wjj/code/DeCLIP_private/logs/TinyCLIP_39M_DeCLIP+_dinov2B_csa_560_0.25_1.0_0.05_alpha0.4/checkpoints/epoch_6.pt', + mode="csa", +) + +# dataset settings +dataset_type = 'PascalVOC20Dataset' +data_root = '/mnt/SSD8T/home/wjj/dataset/VOCdevkit/VOC2012' + +test_pipeline = [ + dict(type='LoadImageFromFile'), + dict(type='Resize', scale=(4096, 448), keep_ratio=True), + dict(type='LoadAnnotations'), + dict(type='PackSegInputs', meta_keys=('img_path', 'seg_map_path', 'ori_shape', + 'img_shape', 'pad_shape', 'scale_factor', 'flip', + 'flip_direction', 'reduce_zero_label','resize_shape')) +] + +test_dataloader = dict( + batch_size=1, + num_workers=4, + persistent_workers=True, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + data_prefix=dict( + img_path='JPEGImages', seg_map_path='SegmentationClass'), + ann_file='ImageSets/Segmentation/val.txt', + pipeline=test_pipeline)) + diff --git a/downstream/ProxyCLIP_TPAMI/configs/tinyclip_declip/cfg_voc21.py b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_declip/cfg_voc21.py new file mode 100644 index 0000000000000000000000000000000000000000..73babc686d2f7cf08c9154ea8c1771c5d862fa88 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_declip/cfg_voc21.py @@ -0,0 +1,42 @@ +_base_ = './base_config.py' + +# model settings +# 使用TinyCLIP模型进行分割 + +model = dict( + name_path='configs/proxyclip/cls_voc21.txt', + vfm=None, + type='TinyCLIPSegmentation', + clip_type='TinyCLIP-ViT-39M-16-Text-19M', + checkpoint='/mnt/SSD8T/home/wjj/code/DeCLIP_private/logs/TinyCLIP_39M_DeCLIP+_dinov2B_csa_560_0.25_1.0_0.05_alpha0.4/checkpoints/epoch_6.pt', + mode="csa", + prob_thd=0.5, + logit_scale=80, +) + +# dataset settings +dataset_type = 'PascalVOCDataset' +data_root = '/mnt/SSD8T/home/wjj/dataset/VOCdevkit/VOC2012' + +test_pipeline = [ + dict(type='LoadImageFromFile'), + dict(type='Resize', scale=(4096, 448), keep_ratio=True), + dict(type='LoadAnnotations'), + dict(type='PackSegInputs', meta_keys=('img_path', 'seg_map_path', 'ori_shape', + 'img_shape', 'pad_shape', 'scale_factor', 'flip', + 'flip_direction', 'reduce_zero_label','resize_shape')) +] + +test_dataloader = dict( + batch_size=1, + num_workers=4, + persistent_workers=True, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + data_prefix=dict( + img_path='JPEGImages', seg_map_path='SegmentationClass'), + ann_file='ImageSets/Segmentation/val.txt', + pipeline=test_pipeline)) + diff --git a/downstream/ProxyCLIP_TPAMI/configs/tinyclip_maskclip/base_config.py b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_maskclip/base_config.py new file mode 100644 index 0000000000000000000000000000000000000000..902ea48a00ed6ba57386ba3c31e2a085e92564ae --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_maskclip/base_config.py @@ -0,0 +1,31 @@ +# base configurations +model = dict( + type='TinyCLIPSegmentation', + clip_type='TinyCLIP-ViT-39M-16-Text-19M', + checkpoint=None, + vfm=None, +) + +test_evaluator = dict(type='IoUMetric', iou_metrics=['mIoU']) +default_scope = 'mmseg' +env_cfg = dict( + cudnn_benchmark=True, + mp_cfg=dict(mp_start_method='fork', opencv_num_threads=0), + dist_cfg=dict(backend='nccl'), +) +vis_backends = [dict(type='LocalVisBackend')] +visualizer = dict( + type='SegLocalVisualizer', vis_backends=vis_backends, alpha=1.0, name='visualizer') +log_processor = dict(by_epoch=False) +log_level = 'INFO' +load_from = None +resume = False +test_cfg = dict(type='TestLoop') +default_hooks = dict( + timer=dict(type='IterTimerHook'), + logger=dict(type='LoggerHook', interval=50, log_metric_by_epoch=False), + param_scheduler=dict(type='ParamSchedulerHook'), + checkpoint=dict(type='CheckpointHook', by_epoch=False, interval=2000), + sampler_seed=dict(type='DistSamplerSeedHook'), + visualization=dict(type='SegVisualizationHook', draw=True,interval=20)) + diff --git a/downstream/ProxyCLIP_TPAMI/configs/tinyclip_maskclip/cfg_ade20k_maskclip.py b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_maskclip/cfg_ade20k_maskclip.py new file mode 100644 index 0000000000000000000000000000000000000000..3470498a28d4a1a5b46ab68711ba97e19aeb079c --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_maskclip/cfg_ade20k_maskclip.py @@ -0,0 +1,55 @@ +_base_ = './base_config.py' + +# model settings +# 使用TinyCLIP模型进行分割 - 消融实验:maskclip模式(使用原始权重,最后一个block采用forward_without_attn) + +model = dict( + name_path="configs/proxyclip/cls_ade20k.txt", + vfm=None, + type="TinyCLIPSegmentation", + clip_type="TinyCLIP-ViT-39M-16-Text-19M", + checkpoint="/mnt/SSD8T/home/wjj/code/DeCLIP_private/checkpoints/TinyCLIP-ViT-39M-16-Text-19M-YFCC15M.pt", + mode="maskclip", +) + +# dataset settings +dataset_type = "ADE20KDataset" +data_root = "/mnt/SSD8T/home/wjj/dataset/ADEChallengeData2016" + +test_pipeline = [ + dict(type="LoadImageFromFile"), + dict(type="Resize", scale=(4096, 448), keep_ratio=True), + dict(type="LoadAnnotations", reduce_zero_label=True), + dict( + type="PackSegInputs", + meta_keys=( + "img_path", + "seg_map_path", + "ori_shape", + "img_shape", + "pad_shape", + "scale_factor", + "flip", + "flip_direction", + "reduce_zero_label", + "resize_shape", + ), + ), +] + +test_dataloader = dict( + batch_size=1, + num_workers=4, + persistent_workers=True, + sampler=dict(type="DefaultSampler", shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + data_prefix=dict( + img_path="images/validation", + seg_map_path="annotations/validation", + ), + pipeline=test_pipeline, + ), +) + diff --git a/downstream/ProxyCLIP_TPAMI/configs/tinyclip_maskclip/cfg_city_scapes_maskclip.py b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_maskclip/cfg_city_scapes_maskclip.py new file mode 100644 index 0000000000000000000000000000000000000000..17b68f818472ffaba0d5d381e22174bf51708035 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_maskclip/cfg_city_scapes_maskclip.py @@ -0,0 +1,56 @@ +_base_ = './base_config.py' + +# model settings +# 使用TinyCLIP模型进行分割 - 消融实验:maskclip模式(使用原始权重,最后一个block采用forward_without_attn) + +model = dict( + name_path="configs/proxyclip/cls_city_scapes.txt", + vfm=None, + type="TinyCLIPSegmentation", + clip_type="TinyCLIP-ViT-39M-16-Text-19M", + checkpoint="/mnt/SSD8T/home/wjj/code/DeCLIP_private/checkpoints/TinyCLIP-ViT-39M-16-Text-19M-YFCC15M.pt", + mode="maskclip", +) + +# dataset settings +dataset_type = "CityscapesDataset" +data_root = "/mnt/SSD8T/home/wjj/dataset/cityscapes" + +test_pipeline = [ + dict(type="LoadImageFromFile"), + dict(type="Resize", scale=(4096, 560), keep_ratio=True), + # add loading annotation after ``Resize`` because ground truth + # does not need to do resize data transform + dict(type="LoadAnnotations"), + dict( + type="PackSegInputs", + meta_keys=( + "img_path", + "seg_map_path", + "ori_shape", + "img_shape", + "pad_shape", + "scale_factor", + "flip", + "flip_direction", + "reduce_zero_label", + "resize_shape", + ), + ), +] + +test_dataloader = dict( + batch_size=1, + num_workers=4, + persistent_workers=True, + sampler=dict(type="DefaultSampler", shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + data_prefix=dict( + img_path="leftImg8bit/val", seg_map_path="gtFine/val" + ), + pipeline=test_pipeline, + ), +) + diff --git a/downstream/ProxyCLIP_TPAMI/configs/tinyclip_maskclip/cfg_coco_object_maskclip.py b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_maskclip/cfg_coco_object_maskclip.py new file mode 100644 index 0000000000000000000000000000000000000000..8e2b7165c8c3e15519372c389190a9dd057ad062 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_maskclip/cfg_coco_object_maskclip.py @@ -0,0 +1,56 @@ +_base_ = './base_config.py' + +# model settings +# 使用TinyCLIP模型进行分割 - 消融实验:maskclip模式(使用原始权重,最后一个block采用forward_without_attn) + +model = dict( + name_path="configs/proxyclip/cls_coco_object.txt", + vfm=None, + type="TinyCLIPSegmentation", + clip_type="TinyCLIP-ViT-39M-16-Text-19M", + checkpoint="/mnt/SSD8T/home/wjj/code/DeCLIP_private/checkpoints/TinyCLIP-ViT-39M-16-Text-19M-YFCC15M.pt", + mode="maskclip", + prob_thd=0.3, +) + +# dataset settings +dataset_type = "COCOObjectDataset" +data_root = "/mnt/SSD8T/home/wjj/dataset/coco_obj" + +test_pipeline = [ + dict(type="LoadImageFromFile"), + dict(type="Resize", scale=(2048, 448), keep_ratio=True), + dict(type="LoadAnnotations"), + dict( + type="PackSegInputs", + meta_keys=( + "img_path", + "seg_map_path", + "ori_shape", + "img_shape", + "pad_shape", + "scale_factor", + "flip", + "flip_direction", + "reduce_zero_label", + "resize_shape", + ), + ), +] + +test_dataloader = dict( + batch_size=1, + num_workers=4, + persistent_workers=True, + sampler=dict(type="DefaultSampler", shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + reduce_zero_label=False, + data_prefix=dict( + img_path="images/val2017", seg_map_path="annotations/val2017" + ), + pipeline=test_pipeline, + ), +) + diff --git a/downstream/ProxyCLIP_TPAMI/configs/tinyclip_maskclip/cfg_coco_stuff164k_maskclip.py b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_maskclip/cfg_coco_stuff164k_maskclip.py new file mode 100644 index 0000000000000000000000000000000000000000..9327c8c27c531cdb67f54444468087dbb0925e3f --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_maskclip/cfg_coco_stuff164k_maskclip.py @@ -0,0 +1,55 @@ +_base_ = './base_config.py' + +# model settings +# 使用TinyCLIP模型进行分割 - 消融实验:maskclip模式(使用原始权重,最后一个block采用forward_without_attn) + +model = dict( + name_path="configs/proxyclip/cls_coco_stuff.txt", + vfm=None, + type="TinyCLIPSegmentation", + clip_type="TinyCLIP-ViT-39M-16-Text-19M", + checkpoint="/mnt/SSD8T/home/wjj/code/DeCLIP_private/checkpoints/TinyCLIP-ViT-39M-16-Text-19M-YFCC15M.pt", + mode="maskclip", +) + +# dataset settings +dataset_type = "COCOStuffDataset" +data_root = "" + +test_pipeline = [ + dict(type="LoadImageFromFile"), + dict(type="Resize", scale=(4096, 448), keep_ratio=True), + dict(type="LoadAnnotations"), + dict( + type="PackSegInputs", + meta_keys=( + "img_path", + "seg_map_path", + "ori_shape", + "img_shape", + "pad_shape", + "scale_factor", + "flip", + "flip_direction", + "reduce_zero_label", + "resize_shape", + ), + ), +] + +test_dataloader = dict( + batch_size=1, + num_workers=4, + persistent_workers=True, + sampler=dict(type="DefaultSampler", shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + data_prefix=dict( + img_path="/mnt/SSD8T/home/wjj/dataset/standard_coco/val2017", + seg_map_path="/mnt/SSD8T/home/wjj/dataset/standard_coco/annotations/val2017", + ), + pipeline=test_pipeline, + ), +) + diff --git a/downstream/ProxyCLIP_TPAMI/configs/tinyclip_maskclip/cfg_context59_maskclip.py b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_maskclip/cfg_context59_maskclip.py new file mode 100644 index 0000000000000000000000000000000000000000..b45af4ba862e1ce7a695ef3f3aef053a059b0dad --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_maskclip/cfg_context59_maskclip.py @@ -0,0 +1,55 @@ +_base_ = './base_config.py' + +# model settings +# 使用TinyCLIP模型进行分割 - 消融实验:maskclip模式(使用原始权重,最后一个block采用forward_without_attn) + +model = dict( + name_path="configs/proxyclip/cls_context59.txt", + vfm=None, + type="TinyCLIPSegmentation", + clip_type="TinyCLIP-ViT-39M-16-Text-19M", + checkpoint="/mnt/SSD8T/home/wjj/code/DeCLIP_private/checkpoints/TinyCLIP-ViT-39M-16-Text-19M-YFCC15M.pt", + mode="maskclip", +) + +# dataset settings +dataset_type = "PascalContext59Dataset" +data_root = "/mnt/SSD8T/home/wjj/dataset/VOCdevkit/VOC2010" + +test_pipeline = [ + dict(type="LoadImageFromFile"), + dict(type="Resize", scale=(4096, 448), keep_ratio=True), + dict(type="LoadAnnotations", reduce_zero_label=True), + dict( + type="PackSegInputs", + meta_keys=( + "img_path", + "seg_map_path", + "ori_shape", + "img_shape", + "pad_shape", + "scale_factor", + "flip", + "flip_direction", + "reduce_zero_label", + "resize_shape", + ), + ), +] + +test_dataloader = dict( + batch_size=1, + num_workers=4, + persistent_workers=True, + sampler=dict(type="DefaultSampler", shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + data_prefix=dict( + img_path="JPEGImages", seg_map_path="SegmentationClassContext" + ), + ann_file="ImageSets/SegmentationContext/val.txt", + pipeline=test_pipeline, + ), +) + diff --git a/downstream/ProxyCLIP_TPAMI/configs/tinyclip_maskclip/cfg_context60_maskclip.py b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_maskclip/cfg_context60_maskclip.py new file mode 100644 index 0000000000000000000000000000000000000000..6dc30d4840ffa445fbac99c8c7973fd01e34ea82 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_maskclip/cfg_context60_maskclip.py @@ -0,0 +1,57 @@ +_base_ = './base_config.py' + +# model settings +# 使用TinyCLIP模型进行分割 - 消融实验:maskclip模式(使用原始权重,最后一个block采用forward_without_attn) + +model = dict( + name_path="configs/proxyclip/cls_context60.txt", + vfm=None, + type="TinyCLIPSegmentation", + clip_type="TinyCLIP-ViT-39M-16-Text-19M", + checkpoint="/mnt/SSD8T/home/wjj/code/DeCLIP_private/checkpoints/TinyCLIP-ViT-39M-16-Text-19M-YFCC15M.pt", + mode="maskclip", + prob_thd=0.15, + logit_scale=40, +) + +# dataset settings +dataset_type = "PascalContext60Dataset" +data_root = "/mnt/SSD8T/home/wjj/dataset/VOCdevkit/VOC2010" + +test_pipeline = [ + dict(type="LoadImageFromFile"), + dict(type="Resize", scale=(4096, 448), keep_ratio=True), + dict(type="LoadAnnotations"), + dict( + type="PackSegInputs", + meta_keys=( + "img_path", + "seg_map_path", + "ori_shape", + "img_shape", + "pad_shape", + "scale_factor", + "flip", + "flip_direction", + "reduce_zero_label", + "resize_shape", + ), + ), +] + +test_dataloader = dict( + batch_size=1, + num_workers=4, + persistent_workers=True, + sampler=dict(type="DefaultSampler", shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + data_prefix=dict( + img_path="JPEGImages", seg_map_path="SegmentationClassContext" + ), + ann_file="ImageSets/SegmentationContext/val.txt", + pipeline=test_pipeline, + ), +) + diff --git a/downstream/ProxyCLIP_TPAMI/configs/tinyclip_maskclip/cfg_voc20_maskclip.py b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_maskclip/cfg_voc20_maskclip.py new file mode 100644 index 0000000000000000000000000000000000000000..1f4a75473f5c83e2b6ed13320aee61fa8b345e58 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_maskclip/cfg_voc20_maskclip.py @@ -0,0 +1,55 @@ +_base_ = './base_config.py' + +# model settings +# 使用TinyCLIP模型进行分割 - 消融实验:maskclip模式(使用原始权重,最后一个block采用forward_without_attn) + +model = dict( + name_path="configs/proxyclip/cls_voc20.txt", + vfm=None, + type="TinyCLIPSegmentation", + clip_type="TinyCLIP-ViT-39M-16-Text-19M", + checkpoint="/mnt/SSD8T/home/wjj/code/DeCLIP_private/checkpoints/TinyCLIP-ViT-39M-16-Text-19M-YFCC15M.pt", + mode="maskclip", +) + +# dataset settings +dataset_type = "PascalVOC20Dataset" +data_root = "/mnt/SSD8T/home/wjj/dataset/VOCdevkit/VOC2012" + +test_pipeline = [ + dict(type="LoadImageFromFile"), + dict(type="Resize", scale=(4096, 448), keep_ratio=True), + dict(type="LoadAnnotations"), + dict( + type="PackSegInputs", + meta_keys=( + "img_path", + "seg_map_path", + "ori_shape", + "img_shape", + "pad_shape", + "scale_factor", + "flip", + "flip_direction", + "reduce_zero_label", + "resize_shape", + ), + ), +] + +test_dataloader = dict( + batch_size=1, + num_workers=4, + persistent_workers=True, + sampler=dict(type="DefaultSampler", shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + data_prefix=dict( + img_path="JPEGImages", seg_map_path="SegmentationClass" + ), + ann_file="ImageSets/Segmentation/val.txt", + pipeline=test_pipeline, + ), +) + diff --git a/downstream/ProxyCLIP_TPAMI/configs/tinyclip_maskclip/cfg_voc21_maskclip.py b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_maskclip/cfg_voc21_maskclip.py new file mode 100644 index 0000000000000000000000000000000000000000..304aa675b2f5b311e5dbba58aafe0d6948c824ed --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_maskclip/cfg_voc21_maskclip.py @@ -0,0 +1,57 @@ +_base_ = './base_config.py' + +# model settings +# 使用TinyCLIP模型进行分割 - 消融实验:maskclip模式(使用原始权重,最后一个block采用forward_without_attn) + +model = dict( + name_path="configs/proxyclip/cls_voc21.txt", + vfm=None, + type="TinyCLIPSegmentation", + clip_type="TinyCLIP-ViT-39M-16-Text-19M", + checkpoint="/mnt/SSD8T/home/wjj/code/DeCLIP_private/checkpoints/TinyCLIP-ViT-39M-16-Text-19M-YFCC15M.pt", + mode="maskclip", + prob_thd=0.5, + logit_scale=80, +) + +# dataset settings +dataset_type = "PascalVOCDataset" +data_root = "/mnt/SSD8T/home/wjj/dataset/VOCdevkit/VOC2012" + +test_pipeline = [ + dict(type="LoadImageFromFile"), + dict(type="Resize", scale=(4096, 448), keep_ratio=True), + dict(type="LoadAnnotations"), + dict( + type="PackSegInputs", + meta_keys=( + "img_path", + "seg_map_path", + "ori_shape", + "img_shape", + "pad_shape", + "scale_factor", + "flip", + "flip_direction", + "reduce_zero_label", + "resize_shape", + ), + ), +] + +test_dataloader = dict( + batch_size=1, + num_workers=4, + persistent_workers=True, + sampler=dict(type="DefaultSampler", shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + data_prefix=dict( + img_path="JPEGImages", seg_map_path="SegmentationClass" + ), + ann_file="ImageSets/Segmentation/val.txt", + pipeline=test_pipeline, + ), +) + diff --git a/downstream/ProxyCLIP_TPAMI/configs/tinyclip_proxy/base_config.py b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_proxy/base_config.py new file mode 100644 index 0000000000000000000000000000000000000000..c0842ab7452cc1eb882a1e91f4c961ceb8805d51 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_proxy/base_config.py @@ -0,0 +1,32 @@ +# base configurations for TinyCLIPProxySegmentation +model = dict( + type='TinyCLIPProxySegmentation', + clip_type='TinyCLIP-ViT-39M-16-Text-19M', + vfm_model='dino-B-8', # sam, mae, dino, dinov2 + checkpoint=None, + mode='proxyclip', +) + +test_evaluator = dict(type='IoUMetric', iou_metrics=['mIoU']) +default_scope = 'mmseg' +env_cfg = dict( + cudnn_benchmark=True, + mp_cfg=dict(mp_start_method='fork', opencv_num_threads=0), + dist_cfg=dict(backend='nccl'), +) +vis_backends = [dict(type='LocalVisBackend')] +visualizer = dict( + type='SegLocalVisualizer', vis_backends=vis_backends, alpha=1.0, name='visualizer') +log_processor = dict(by_epoch=False) +log_level = 'INFO' +load_from = None +resume = False +test_cfg = dict(type='TestLoop') +default_hooks = dict( + timer=dict(type='IterTimerHook'), + logger=dict(type='LoggerHook', interval=50, log_metric_by_epoch=False), + param_scheduler=dict(type='ParamSchedulerHook'), + checkpoint=dict(type='CheckpointHook', by_epoch=False, interval=2000), + sampler_seed=dict(type='DistSamplerSeedHook'), + visualization=dict(type='SegVisualizationHook', draw=True,interval=20)) + diff --git a/downstream/ProxyCLIP_TPAMI/configs/tinyclip_proxy/cfg_ade20k_proxy.py b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_proxy/cfg_ade20k_proxy.py new file mode 100644 index 0000000000000000000000000000000000000000..59b46343e1dcdee27fb81cb1342238af2b187614 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_proxy/cfg_ade20k_proxy.py @@ -0,0 +1,63 @@ +_base_ = './base_config.py' + +# model settings +# 使用TinyCLIP+ProxyCLIP模型进行分割 +# 模型: TinyCLIP-ViT-39M-16-Text-19M +# VFM: DINO-B-8 +# 模式: proxyclip + +model = dict( + name_path="configs/proxyclip/cls_ade20k.txt", + vfm_model="dino-B-8", # Options: 'sam-B', 'sam-L', 'dinov2-B', 'dinov2-L', 'dino-B-8', 'dino-B-16' + type="TinyCLIPProxySegmentation", + clip_type="TinyCLIP-ViT-39M-16-Text-19M", + checkpoint="/mnt/SSD8T/home/wjj/code/DeCLIP_private/checkpoints/TinyCLIP-ViT-39M-16-Text-19M-YFCC15M.pt", + mode="proxyclip", # Use proxyclip mode + beta=1.2, # ProxyCLIP beta parameter + gamma=3.0, # ProxyCLIP gamma parameter + prob_thd=0.0, + logit_scale=40, + slide_stride=112, + slide_crop=336, +) + +# dataset settings +dataset_type = "ADE20KDataset" +data_root = "/mnt/SSD8T/home/wjj/dataset/ADEChallengeData2016" + +test_pipeline = [ + dict(type="LoadImageFromFile"), + dict(type="Resize", scale=(4096, 448), keep_ratio=True), + dict(type="LoadAnnotations", reduce_zero_label=True), + dict( + type="PackSegInputs", + meta_keys=( + "img_path", + "seg_map_path", + "ori_shape", + "img_shape", + "pad_shape", + "scale_factor", + "flip", + "flip_direction", + "reduce_zero_label", + "resize_shape", + ), + ), +] + +test_dataloader = dict( + batch_size=1, + num_workers=4, + persistent_workers=True, + sampler=dict(type="DefaultSampler", shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + data_prefix=dict( + img_path="images/validation", seg_map_path="annotations/validation" + ), + pipeline=test_pipeline, + ), +) + diff --git a/downstream/ProxyCLIP_TPAMI/configs/tinyclip_proxy/cfg_city_scapes_proxy.py b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_proxy/cfg_city_scapes_proxy.py new file mode 100644 index 0000000000000000000000000000000000000000..87886dc1a015369720a6fdb9e5fd1fee8cec53ee --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_proxy/cfg_city_scapes_proxy.py @@ -0,0 +1,61 @@ +_base_ = './base_config.py' + +# model settings +# 使用TinyCLIP+ProxyCLIP模型进行分割 +# 模型: TinyCLIP-ViT-39M-16-Text-19M +# VFM: DINO-B-8 +# 模式: proxyclip + +model = dict( + name_path="configs/proxyclip/cls_city_scapes.txt", + vfm_model="dino-B-8", # Options: 'sam-B', 'sam-L', 'dinov2-B', 'dinov2-L', 'dino-B-8', 'dino-B-16' + type="TinyCLIPProxySegmentation", + clip_type="TinyCLIP-ViT-39M-16-Text-19M", + checkpoint="/mnt/SSD8T/home/wjj/code/DeCLIP_private/checkpoints/TinyCLIP-ViT-39M-16-Text-19M-YFCC15M.pt", + mode="proxyclip", # Use proxyclip mode + beta=1.2, # ProxyCLIP beta parameter + gamma=3.0, # ProxyCLIP gamma parameter + prob_thd=0.0, + logit_scale=40, + slide_stride=112, + slide_crop=336, +) + +# dataset settings +dataset_type = "CityscapesDataset" +data_root = "/mnt/SSD8T/home/wjj/dataset/cityscapes" + +test_pipeline = [ + dict(type="LoadImageFromFile"), + dict(type="Resize", scale=(4096, 448), keep_ratio=True), + dict(type="LoadAnnotations"), + dict( + type="PackSegInputs", + meta_keys=( + "img_path", + "seg_map_path", + "ori_shape", + "img_shape", + "pad_shape", + "scale_factor", + "flip", + "flip_direction", + "reduce_zero_label", + "resize_shape", + ), + ), +] + +test_dataloader = dict( + batch_size=1, + num_workers=4, + persistent_workers=True, + sampler=dict(type="DefaultSampler", shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + data_prefix=dict(img_path="leftImg8bit/val", seg_map_path="gtFine/val"), + pipeline=test_pipeline, + ), +) + diff --git a/downstream/ProxyCLIP_TPAMI/configs/tinyclip_proxy/cfg_coco_object_proxy.py b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_proxy/cfg_coco_object_proxy.py new file mode 100644 index 0000000000000000000000000000000000000000..2c83dd9745f6dffe780322a0b18e8b4e063bd09c --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_proxy/cfg_coco_object_proxy.py @@ -0,0 +1,64 @@ +_base_ = './base_config.py' + +# model settings +# 使用TinyCLIP+ProxyCLIP模型进行分割 +# 模型: TinyCLIP-ViT-39M-16-Text-19M +# VFM: DINO-B-8 +# 模式: proxyclip + +model = dict( + name_path="configs/proxyclip/cls_coco_object.txt", + vfm_model="dino-B-8", # Options: 'sam-B', 'sam-L', 'dinov2-B', 'dinov2-L', 'dino-B-8', 'dino-B-16' + type="TinyCLIPProxySegmentation", + clip_type="TinyCLIP-ViT-39M-16-Text-19M", + checkpoint="/mnt/SSD8T/home/wjj/code/DeCLIP_private/checkpoints/TinyCLIP-ViT-39M-16-Text-19M-YFCC15M.pt", + mode="proxyclip", # Use proxyclip mode + beta=1.2, # ProxyCLIP beta parameter + gamma=3.0, # ProxyCLIP gamma parameter + prob_thd=0.3, + logit_scale=40, + slide_stride=112, + slide_crop=336, +) + +# dataset settings +dataset_type = "COCOObjectDataset" +data_root = "/mnt/SSD8T/home/wjj/dataset/coco_obj" + +test_pipeline = [ + dict(type="LoadImageFromFile"), + dict(type="Resize", scale=(2048, 336), keep_ratio=True), + dict(type="LoadAnnotations"), + dict( + type="PackSegInputs", + meta_keys=( + "img_path", + "seg_map_path", + "ori_shape", + "img_shape", + "pad_shape", + "scale_factor", + "flip", + "flip_direction", + "reduce_zero_label", + "resize_shape", + ), + ), +] + +test_dataloader = dict( + batch_size=1, + num_workers=4, + persistent_workers=True, + sampler=dict(type="DefaultSampler", shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + reduce_zero_label=False, + data_prefix=dict( + img_path="images/val2017", seg_map_path="annotations/val2017" + ), + pipeline=test_pipeline, + ), +) + diff --git a/downstream/ProxyCLIP_TPAMI/configs/tinyclip_proxy/cfg_coco_stuff164k_proxy.py b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_proxy/cfg_coco_stuff164k_proxy.py new file mode 100644 index 0000000000000000000000000000000000000000..27aac52eabb26351b15ac04e948c77e78f3297ef --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_proxy/cfg_coco_stuff164k_proxy.py @@ -0,0 +1,64 @@ +_base_ = './base_config.py' + +# model settings +# 使用TinyCLIP+ProxyCLIP模型进行分割 +# 模型: TinyCLIP-ViT-39M-16-Text-19M +# VFM: DINO-B-8 +# 模式: proxyclip + +model = dict( + name_path="configs/proxyclip/cls_coco_stuff.txt", + vfm_model="dino-B-8", # Options: 'sam-B', 'sam-L', 'dinov2-B', 'dinov2-L', 'dino-B-8', 'dino-B-16' + type="TinyCLIPProxySegmentation", + clip_type="TinyCLIP-ViT-39M-16-Text-19M", + checkpoint="/mnt/SSD8T/home/wjj/code/DeCLIP_private/checkpoints/TinyCLIP-ViT-39M-16-Text-19M-YFCC15M.pt", + mode="proxyclip", # Use proxyclip mode + beta=1.2, # ProxyCLIP beta parameter + gamma=3.0, # ProxyCLIP gamma parameter + prob_thd=0.0, + logit_scale=40, + slide_stride=112, + slide_crop=336, +) + +# dataset settings +dataset_type = "COCOStuffDataset" +data_root = "" + +test_pipeline = [ + dict(type="LoadImageFromFile"), + dict(type="Resize", scale=(2048, 336), keep_ratio=True), + dict(type="LoadAnnotations"), + dict( + type="PackSegInputs", + meta_keys=( + "img_path", + "seg_map_path", + "ori_shape", + "img_shape", + "pad_shape", + "scale_factor", + "flip", + "flip_direction", + "reduce_zero_label", + "resize_shape", + ), + ), +] + +test_dataloader = dict( + batch_size=1, + num_workers=4, + persistent_workers=True, + sampler=dict(type="DefaultSampler", shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + data_prefix=dict( + img_path="/mnt/SSD8T/home/wjj/dataset/standard_coco/val2017", + seg_map_path="/mnt/SSD8T/home/wjj/dataset/standard_coco/annotations/val2017", + ), + pipeline=test_pipeline, + ), +) + diff --git a/downstream/ProxyCLIP_TPAMI/configs/tinyclip_proxy/cfg_context59_proxy.py b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_proxy/cfg_context59_proxy.py new file mode 100644 index 0000000000000000000000000000000000000000..be93f4f2b0686741a0875fcb60002cc04aacc0d8 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_proxy/cfg_context59_proxy.py @@ -0,0 +1,64 @@ +_base_ = './base_config.py' + +# model settings +# 使用TinyCLIP+ProxyCLIP模型进行分割 +# 模型: TinyCLIP-ViT-39M-16-Text-19M +# VFM: DINO-B-8 +# 模式: proxyclip + +model = dict( + name_path="configs/proxyclip/cls_context59.txt", + vfm_model="dino-B-8", # Options: 'sam-B', 'sam-L', 'dinov2-B', 'dinov2-L', 'dino-B-8', 'dino-B-16' + type="TinyCLIPProxySegmentation", + clip_type="TinyCLIP-ViT-39M-16-Text-19M", + checkpoint="/mnt/SSD8T/home/wjj/code/DeCLIP_private/checkpoints/TinyCLIP-ViT-39M-16-Text-19M-YFCC15M.pt", + mode="proxyclip", # Use proxyclip mode + beta=1.2, # ProxyCLIP beta parameter + gamma=3.0, # ProxyCLIP gamma parameter + prob_thd=0.0, + logit_scale=40, + slide_stride=112, + slide_crop=336, +) + +# dataset settings +dataset_type = "PascalContext59Dataset" +data_root = "/mnt/SSD8T/home/wjj/dataset/VOCdevkit/VOC2010" + +test_pipeline = [ + dict(type="LoadImageFromFile"), + dict(type="Resize", scale=(2048, 336), keep_ratio=True), + dict(type="LoadAnnotations", reduce_zero_label=True), + dict( + type="PackSegInputs", + meta_keys=( + "img_path", + "seg_map_path", + "ori_shape", + "img_shape", + "pad_shape", + "scale_factor", + "flip", + "flip_direction", + "reduce_zero_label", + "resize_shape", + ), + ), +] + +test_dataloader = dict( + batch_size=1, + num_workers=4, + persistent_workers=True, + sampler=dict(type="DefaultSampler", shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + data_prefix=dict( + img_path="JPEGImages", seg_map_path="SegmentationClassContext" + ), + ann_file="ImageSets/SegmentationContext/val.txt", + pipeline=test_pipeline, + ), +) + diff --git a/downstream/ProxyCLIP_TPAMI/configs/tinyclip_proxy/cfg_context60_proxy.py b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_proxy/cfg_context60_proxy.py new file mode 100644 index 0000000000000000000000000000000000000000..ea4fcc99321c968b014ab841b7bd93a280cd83d9 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_proxy/cfg_context60_proxy.py @@ -0,0 +1,64 @@ +_base_ = './base_config.py' + +# model settings +# 使用TinyCLIP+ProxyCLIP模型进行分割 +# 模型: TinyCLIP-ViT-39M-16-Text-19M +# VFM: DINO-B-8 +# 模式: proxyclip + +model = dict( + name_path="configs/proxyclip/cls_context60.txt", + vfm_model="dino-B-8", # Options: 'sam-B', 'sam-L', 'dinov2-B', 'dinov2-L', 'dino-B-8', 'dino-B-16' + type="TinyCLIPProxySegmentation", + clip_type="TinyCLIP-ViT-39M-16-Text-19M", + checkpoint="/mnt/SSD8T/home/wjj/code/DeCLIP_private/checkpoints/TinyCLIP-ViT-39M-16-Text-19M-YFCC15M.pt", + mode="proxyclip", # Use proxyclip mode + beta=1.2, # ProxyCLIP beta parameter + gamma=3.0, # ProxyCLIP gamma parameter + prob_thd=0.15, + logit_scale=40, + slide_stride=112, + slide_crop=336, +) + +# dataset settings +dataset_type = "PascalContext60Dataset" +data_root = "/mnt/SSD8T/home/wjj/dataset/VOCdevkit/VOC2010" + +test_pipeline = [ + dict(type="LoadImageFromFile"), + dict(type="Resize", scale=(2048, 336), keep_ratio=True), + dict(type="LoadAnnotations"), + dict( + type="PackSegInputs", + meta_keys=( + "img_path", + "seg_map_path", + "ori_shape", + "img_shape", + "pad_shape", + "scale_factor", + "flip", + "flip_direction", + "reduce_zero_label", + "resize_shape", + ), + ), +] + +test_dataloader = dict( + batch_size=1, + num_workers=4, + persistent_workers=True, + sampler=dict(type="DefaultSampler", shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + data_prefix=dict( + img_path="JPEGImages", seg_map_path="SegmentationClassContext" + ), + ann_file="ImageSets/SegmentationContext/val.txt", + pipeline=test_pipeline, + ), +) + diff --git a/downstream/ProxyCLIP_TPAMI/configs/tinyclip_proxy/cfg_voc20_proxy.py b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_proxy/cfg_voc20_proxy.py new file mode 100644 index 0000000000000000000000000000000000000000..08e9e9324e544188f16d683f69ddbd2bc663923c --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_proxy/cfg_voc20_proxy.py @@ -0,0 +1,64 @@ +_base_ = './base_config.py' + +# model settings +# 使用TinyCLIP+ProxyCLIP模型进行分割 +# 模型: TinyCLIP-ViT-39M-16-Text-19M +# VFM: DINO-B-8 +# 模式: proxyclip + +model = dict( + name_path="configs/proxyclip/cls_voc20.txt", + vfm_model="dino-B-8", # Options: 'sam-B', 'sam-L', 'dinov2-B', 'dinov2-L', 'dino-B-8', 'dino-B-16' + type="TinyCLIPProxySegmentation", + clip_type="TinyCLIP-ViT-39M-16-Text-19M", + checkpoint="/mnt/SSD8T/home/wjj/code/DeCLIP_private/checkpoints/TinyCLIP-ViT-39M-16-Text-19M-YFCC15M.pt", + mode="proxyclip", # Use proxyclip mode + beta=1.2, # ProxyCLIP beta parameter + gamma=3.0, # ProxyCLIP gamma parameter + prob_thd=0.0, + logit_scale=40, + slide_stride=112, + slide_crop=336, +) + +# dataset settings +dataset_type = "PascalVOC20Dataset" +data_root = "/mnt/SSD8T/home/wjj/dataset/VOCdevkit/VOC2012" + +test_pipeline = [ + dict(type="LoadImageFromFile"), + dict(type="Resize", scale=(2048, 336), keep_ratio=True), + dict(type="LoadAnnotations"), + dict( + type="PackSegInputs", + meta_keys=( + "img_path", + "seg_map_path", + "ori_shape", + "img_shape", + "pad_shape", + "scale_factor", + "flip", + "flip_direction", + "reduce_zero_label", + "resize_shape", + ), + ), +] + +test_dataloader = dict( + batch_size=1, + num_workers=4, + persistent_workers=True, + sampler=dict(type="DefaultSampler", shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + data_prefix=dict( + img_path="JPEGImages", seg_map_path="SegmentationClass" + ), + ann_file="ImageSets/Segmentation/val.txt", + pipeline=test_pipeline, + ), +) + diff --git a/downstream/ProxyCLIP_TPAMI/configs/tinyclip_proxy/cfg_voc21_proxy.py b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_proxy/cfg_voc21_proxy.py new file mode 100644 index 0000000000000000000000000000000000000000..fd3ec9160763f4799bbe7195f95acd9965172fa9 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_proxy/cfg_voc21_proxy.py @@ -0,0 +1,64 @@ +_base_ = './base_config.py' + +# model settings +# 使用TinyCLIP+ProxyCLIP模型进行分割 +# 模型: TinyCLIP-ViT-39M-16-Text-19M +# VFM: DINO-B-8 +# 模式: proxyclip + +model = dict( + name_path="configs/proxyclip/cls_voc21.txt", + vfm_model="dino-B-8", # Options: 'sam-B', 'sam-L', 'dinov2-B', 'dinov2-L', 'dino-B-8', 'dino-B-16' + type="TinyCLIPProxySegmentation", + clip_type="TinyCLIP-ViT-39M-16-Text-19M", + checkpoint="/mnt/SSD8T/home/wjj/code/DeCLIP_private/checkpoints/TinyCLIP-ViT-39M-16-Text-19M-YFCC15M.pt", + mode="proxyclip", # Use proxyclip mode + beta=1.2, # ProxyCLIP beta parameter + gamma=3.0, # ProxyCLIP gamma parameter + prob_thd=0.5, + logit_scale=80, + slide_stride=112, + slide_crop=336, +) + +# dataset settings +dataset_type = "PascalVOCDataset" +data_root = "/mnt/SSD8T/home/wjj/dataset/VOCdevkit/VOC2012" + +test_pipeline = [ + dict(type="LoadImageFromFile"), + dict(type="Resize", scale=(2048, 336), keep_ratio=True), + dict(type="LoadAnnotations"), + dict( + type="PackSegInputs", + meta_keys=( + "img_path", + "seg_map_path", + "ori_shape", + "img_shape", + "pad_shape", + "scale_factor", + "flip", + "flip_direction", + "reduce_zero_label", + "resize_shape", + ), + ), +] + +test_dataloader = dict( + batch_size=1, + num_workers=4, + persistent_workers=True, + sampler=dict(type="DefaultSampler", shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + data_prefix=dict( + img_path="JPEGImages", seg_map_path="SegmentationClass" + ), + ann_file="ImageSets/Segmentation/val.txt", + pipeline=test_pipeline, + ), +) + diff --git a/downstream/ProxyCLIP_TPAMI/configs/tinyclip_proxy_sam/base_config.py b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_proxy_sam/base_config.py new file mode 100644 index 0000000000000000000000000000000000000000..c83b34baca0b6ecc248dab7a67d12210869d285c --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_proxy_sam/base_config.py @@ -0,0 +1,32 @@ +# base configurations for TinyCLIPProxySegmentation (SAM version) +model = dict( + type='TinyCLIPProxySegmentation', + clip_type='TinyCLIP-ViT-39M-16-Text-19M', + vfm_model='sam-B', # sam-B for SAM Base model + checkpoint=None, + mode='proxyclip', +) + +test_evaluator = dict(type='IoUMetric', iou_metrics=['mIoU']) +default_scope = 'mmseg' +env_cfg = dict( + cudnn_benchmark=True, + mp_cfg=dict(mp_start_method='fork', opencv_num_threads=0), + dist_cfg=dict(backend='nccl'), +) +vis_backends = [dict(type='LocalVisBackend')] +visualizer = dict( + type='SegLocalVisualizer', vis_backends=vis_backends, alpha=1.0, name='visualizer') +log_processor = dict(by_epoch=False) +log_level = 'INFO' +load_from = None +resume = False +test_cfg = dict(type='TestLoop') +default_hooks = dict( + timer=dict(type='IterTimerHook'), + logger=dict(type='LoggerHook', interval=50, log_metric_by_epoch=False), + param_scheduler=dict(type='ParamSchedulerHook'), + checkpoint=dict(type='CheckpointHook', by_epoch=False, interval=2000), + sampler_seed=dict(type='DistSamplerSeedHook'), + visualization=dict(type='SegVisualizationHook', draw=True,interval=20)) + diff --git a/downstream/ProxyCLIP_TPAMI/configs/tinyclip_proxy_sam/cfg_ade20k_proxy.py b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_proxy_sam/cfg_ade20k_proxy.py new file mode 100644 index 0000000000000000000000000000000000000000..fbb37babd6fa26d26b0a8c54fe93b6bb66b4ee4a --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_proxy_sam/cfg_ade20k_proxy.py @@ -0,0 +1,63 @@ +_base_ = './base_config.py' + +# model settings +# 使用TinyCLIP+ProxyCLIP模型进行分割 +# 模型: TinyCLIP-ViT-39M-16-Text-19M +# VFM: SAM-B +# 模式: proxyclip + +model = dict( + name_path="configs/proxyclip/cls_ade20k.txt", + vfm_model="sam-B", # Options: 'sam-B', 'sam-L', 'dinov2-B', 'dinov2-L', 'dino-B-8', 'dino-B-16' + type="TinyCLIPProxySegmentation", + clip_type="TinyCLIP-ViT-39M-16-Text-19M", + checkpoint="/mnt/SSD8T/home/wjj/code/DeCLIP_private/checkpoints/TinyCLIP-ViT-39M-16-Text-19M-YFCC15M.pt", + mode="proxyclip", # Use proxyclip mode + beta=1.2, # ProxyCLIP beta parameter + gamma=3.0, # ProxyCLIP gamma parameter + prob_thd=0.0, + logit_scale=40, + slide_stride=112, + slide_crop=336, +) + +# dataset settings +dataset_type = "ADE20KDataset" +data_root = "/mnt/SSD8T/home/wjj/dataset/ADEChallengeData2016" + +test_pipeline = [ + dict(type="LoadImageFromFile"), + dict(type="Resize", scale=(4096, 448), keep_ratio=True), + dict(type="LoadAnnotations", reduce_zero_label=True), + dict( + type="PackSegInputs", + meta_keys=( + "img_path", + "seg_map_path", + "ori_shape", + "img_shape", + "pad_shape", + "scale_factor", + "flip", + "flip_direction", + "reduce_zero_label", + "resize_shape", + ), + ), +] + +test_dataloader = dict( + batch_size=1, + num_workers=4, + persistent_workers=True, + sampler=dict(type="DefaultSampler", shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + data_prefix=dict( + img_path="images/validation", seg_map_path="annotations/validation" + ), + pipeline=test_pipeline, + ), +) + diff --git a/downstream/ProxyCLIP_TPAMI/configs/tinyclip_proxy_sam/cfg_city_scapes_proxy.py b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_proxy_sam/cfg_city_scapes_proxy.py new file mode 100644 index 0000000000000000000000000000000000000000..491a685208caa7cbb548ceb600992a80b3754447 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_proxy_sam/cfg_city_scapes_proxy.py @@ -0,0 +1,61 @@ +_base_ = './base_config.py' + +# model settings +# 使用TinyCLIP+ProxyCLIP模型进行分割 +# 模型: TinyCLIP-ViT-39M-16-Text-19M +# VFM: SAM-B +# 模式: proxyclip + +model = dict( + name_path="configs/proxyclip/cls_city_scapes.txt", + vfm_model="sam-B", # Options: 'sam-B', 'sam-L', 'dinov2-B', 'dinov2-L', 'dino-B-8', 'dino-B-16' + type="TinyCLIPProxySegmentation", + clip_type="TinyCLIP-ViT-39M-16-Text-19M", + checkpoint="/mnt/SSD8T/home/wjj/code/DeCLIP_private/checkpoints/TinyCLIP-ViT-39M-16-Text-19M-YFCC15M.pt", + mode="proxyclip", # Use proxyclip mode + beta=1.2, # ProxyCLIP beta parameter + gamma=3.0, # ProxyCLIP gamma parameter + prob_thd=0.0, + logit_scale=40, + slide_stride=112, + slide_crop=336, +) + +# dataset settings +dataset_type = "CityscapesDataset" +data_root = "/mnt/SSD8T/home/wjj/dataset/cityscapes" + +test_pipeline = [ + dict(type="LoadImageFromFile"), + dict(type="Resize", scale=(4096, 448), keep_ratio=True), + dict(type="LoadAnnotations"), + dict( + type="PackSegInputs", + meta_keys=( + "img_path", + "seg_map_path", + "ori_shape", + "img_shape", + "pad_shape", + "scale_factor", + "flip", + "flip_direction", + "reduce_zero_label", + "resize_shape", + ), + ), +] + +test_dataloader = dict( + batch_size=1, + num_workers=4, + persistent_workers=True, + sampler=dict(type="DefaultSampler", shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + data_prefix=dict(img_path="leftImg8bit/val", seg_map_path="gtFine/val"), + pipeline=test_pipeline, + ), +) + diff --git a/downstream/ProxyCLIP_TPAMI/configs/tinyclip_proxy_sam/cfg_coco_object_proxy.py b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_proxy_sam/cfg_coco_object_proxy.py new file mode 100644 index 0000000000000000000000000000000000000000..e939b729a822b0d5f5ddd8a5ffdb0e9f5c219e18 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_proxy_sam/cfg_coco_object_proxy.py @@ -0,0 +1,64 @@ +_base_ = './base_config.py' + +# model settings +# 使用TinyCLIP+ProxyCLIP模型进行分割 +# 模型: TinyCLIP-ViT-39M-16-Text-19M +# VFM: SAM-B +# 模式: proxyclip + +model = dict( + name_path="configs/proxyclip/cls_coco_object.txt", + vfm_model="sam-B", # Options: 'sam-B', 'sam-L', 'dinov2-B', 'dinov2-L', 'dino-B-8', 'dino-B-16' + type="TinyCLIPProxySegmentation", + clip_type="TinyCLIP-ViT-39M-16-Text-19M", + checkpoint="/mnt/SSD8T/home/wjj/code/DeCLIP_private/checkpoints/TinyCLIP-ViT-39M-16-Text-19M-YFCC15M.pt", + mode="proxyclip", # Use proxyclip mode + beta=1.2, # ProxyCLIP beta parameter + gamma=3.0, # ProxyCLIP gamma parameter + prob_thd=0.3, + logit_scale=40, + slide_stride=112, + slide_crop=336, +) + +# dataset settings +dataset_type = "COCOObjectDataset" +data_root = "/mnt/SSD8T/home/wjj/dataset/coco_obj" + +test_pipeline = [ + dict(type="LoadImageFromFile"), + dict(type="Resize", scale=(2048, 336), keep_ratio=True), + dict(type="LoadAnnotations"), + dict( + type="PackSegInputs", + meta_keys=( + "img_path", + "seg_map_path", + "ori_shape", + "img_shape", + "pad_shape", + "scale_factor", + "flip", + "flip_direction", + "reduce_zero_label", + "resize_shape", + ), + ), +] + +test_dataloader = dict( + batch_size=1, + num_workers=4, + persistent_workers=True, + sampler=dict(type="DefaultSampler", shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + reduce_zero_label=False, + data_prefix=dict( + img_path="images/val2017", seg_map_path="annotations/val2017" + ), + pipeline=test_pipeline, + ), +) + diff --git a/downstream/ProxyCLIP_TPAMI/configs/tinyclip_proxy_sam/cfg_coco_stuff164k_proxy.py b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_proxy_sam/cfg_coco_stuff164k_proxy.py new file mode 100644 index 0000000000000000000000000000000000000000..adea2de02fe57406fcb92a8f6d263156740df22c --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_proxy_sam/cfg_coco_stuff164k_proxy.py @@ -0,0 +1,64 @@ +_base_ = './base_config.py' + +# model settings +# 使用TinyCLIP+ProxyCLIP模型进行分割 +# 模型: TinyCLIP-ViT-39M-16-Text-19M +# VFM: SAM-B +# 模式: proxyclip + +model = dict( + name_path="configs/proxyclip/cls_coco_stuff.txt", + vfm_model="sam-B", # Options: 'sam-B', 'sam-L', 'dinov2-B', 'dinov2-L', 'dino-B-8', 'dino-B-16' + type="TinyCLIPProxySegmentation", + clip_type="TinyCLIP-ViT-39M-16-Text-19M", + checkpoint="/mnt/SSD8T/home/wjj/code/DeCLIP_private/checkpoints/TinyCLIP-ViT-39M-16-Text-19M-YFCC15M.pt", + mode="proxyclip", # Use proxyclip mode + beta=1.2, # ProxyCLIP beta parameter + gamma=3.0, # ProxyCLIP gamma parameter + prob_thd=0.0, + logit_scale=40, + slide_stride=112, + slide_crop=336, +) + +# dataset settings +dataset_type = "COCOStuffDataset" +data_root = "" + +test_pipeline = [ + dict(type="LoadImageFromFile"), + dict(type="Resize", scale=(2048, 336), keep_ratio=True), + dict(type="LoadAnnotations"), + dict( + type="PackSegInputs", + meta_keys=( + "img_path", + "seg_map_path", + "ori_shape", + "img_shape", + "pad_shape", + "scale_factor", + "flip", + "flip_direction", + "reduce_zero_label", + "resize_shape", + ), + ), +] + +test_dataloader = dict( + batch_size=1, + num_workers=4, + persistent_workers=True, + sampler=dict(type="DefaultSampler", shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + data_prefix=dict( + img_path="/mnt/SSD8T/home/wjj/dataset/standard_coco/val2017", + seg_map_path="/mnt/SSD8T/home/wjj/dataset/standard_coco/annotations/val2017", + ), + pipeline=test_pipeline, + ), +) + diff --git a/downstream/ProxyCLIP_TPAMI/configs/tinyclip_proxy_sam/cfg_context59_proxy.py b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_proxy_sam/cfg_context59_proxy.py new file mode 100644 index 0000000000000000000000000000000000000000..b19c8c829cd424380fc54c574e73cf38b9d1046e --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_proxy_sam/cfg_context59_proxy.py @@ -0,0 +1,64 @@ +_base_ = './base_config.py' + +# model settings +# 使用TinyCLIP+ProxyCLIP模型进行分割 +# 模型: TinyCLIP-ViT-39M-16-Text-19M +# VFM: SAM-B +# 模式: proxyclip + +model = dict( + name_path="configs/proxyclip/cls_context59.txt", + vfm_model="sam-B", # Options: 'sam-B', 'sam-L', 'dinov2-B', 'dinov2-L', 'dino-B-8', 'dino-B-16' + type="TinyCLIPProxySegmentation", + clip_type="TinyCLIP-ViT-39M-16-Text-19M", + checkpoint="/mnt/SSD8T/home/wjj/code/DeCLIP_private/checkpoints/TinyCLIP-ViT-39M-16-Text-19M-YFCC15M.pt", + mode="proxyclip", # Use proxyclip mode + beta=1.2, # ProxyCLIP beta parameter + gamma=3.0, # ProxyCLIP gamma parameter + prob_thd=0.0, + logit_scale=40, + slide_stride=112, + slide_crop=336, +) + +# dataset settings +dataset_type = "PascalContext59Dataset" +data_root = "/mnt/SSD8T/home/wjj/dataset/VOCdevkit/VOC2010" + +test_pipeline = [ + dict(type="LoadImageFromFile"), + dict(type="Resize", scale=(2048, 336), keep_ratio=True), + dict(type="LoadAnnotations", reduce_zero_label=True), + dict( + type="PackSegInputs", + meta_keys=( + "img_path", + "seg_map_path", + "ori_shape", + "img_shape", + "pad_shape", + "scale_factor", + "flip", + "flip_direction", + "reduce_zero_label", + "resize_shape", + ), + ), +] + +test_dataloader = dict( + batch_size=1, + num_workers=4, + persistent_workers=True, + sampler=dict(type="DefaultSampler", shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + data_prefix=dict( + img_path="JPEGImages", seg_map_path="SegmentationClassContext" + ), + ann_file="ImageSets/SegmentationContext/val.txt", + pipeline=test_pipeline, + ), +) + diff --git a/downstream/ProxyCLIP_TPAMI/configs/tinyclip_proxy_sam/cfg_context60_proxy.py b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_proxy_sam/cfg_context60_proxy.py new file mode 100644 index 0000000000000000000000000000000000000000..9d591bf7f9597ce26df51cf1dad81df364d85732 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_proxy_sam/cfg_context60_proxy.py @@ -0,0 +1,64 @@ +_base_ = './base_config.py' + +# model settings +# 使用TinyCLIP+ProxyCLIP模型进行分割 +# 模型: TinyCLIP-ViT-39M-16-Text-19M +# VFM: SAM-B +# 模式: proxyclip + +model = dict( + name_path="configs/proxyclip/cls_context60.txt", + vfm_model="sam-B", # Options: 'sam-B', 'sam-L', 'dinov2-B', 'dinov2-L', 'dino-B-8', 'dino-B-16' + type="TinyCLIPProxySegmentation", + clip_type="TinyCLIP-ViT-39M-16-Text-19M", + checkpoint="/mnt/SSD8T/home/wjj/code/DeCLIP_private/checkpoints/TinyCLIP-ViT-39M-16-Text-19M-YFCC15M.pt", + mode="proxyclip", # Use proxyclip mode + beta=1.2, # ProxyCLIP beta parameter + gamma=3.0, # ProxyCLIP gamma parameter + prob_thd=0.15, + logit_scale=40, + slide_stride=112, + slide_crop=336, +) + +# dataset settings +dataset_type = "PascalContext60Dataset" +data_root = "/mnt/SSD8T/home/wjj/dataset/VOCdevkit/VOC2010" + +test_pipeline = [ + dict(type="LoadImageFromFile"), + dict(type="Resize", scale=(2048, 336), keep_ratio=True), + dict(type="LoadAnnotations"), + dict( + type="PackSegInputs", + meta_keys=( + "img_path", + "seg_map_path", + "ori_shape", + "img_shape", + "pad_shape", + "scale_factor", + "flip", + "flip_direction", + "reduce_zero_label", + "resize_shape", + ), + ), +] + +test_dataloader = dict( + batch_size=1, + num_workers=4, + persistent_workers=True, + sampler=dict(type="DefaultSampler", shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + data_prefix=dict( + img_path="JPEGImages", seg_map_path="SegmentationClassContext" + ), + ann_file="ImageSets/SegmentationContext/val.txt", + pipeline=test_pipeline, + ), +) + diff --git a/downstream/ProxyCLIP_TPAMI/configs/tinyclip_proxy_sam/cfg_voc20_proxy.py b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_proxy_sam/cfg_voc20_proxy.py new file mode 100644 index 0000000000000000000000000000000000000000..e5237521be027d5eca303df53ba5b37aaccba7a8 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_proxy_sam/cfg_voc20_proxy.py @@ -0,0 +1,64 @@ +_base_ = './base_config.py' + +# model settings +# 使用TinyCLIP+ProxyCLIP模型进行分割 +# 模型: TinyCLIP-ViT-39M-16-Text-19M +# VFM: SAM-B +# 模式: proxyclip + +model = dict( + name_path="configs/proxyclip/cls_voc20.txt", + vfm_model="sam-B", # Options: 'sam-B', 'sam-L', 'dinov2-B', 'dinov2-L', 'dino-B-8', 'dino-B-16' + type="TinyCLIPProxySegmentation", + clip_type="TinyCLIP-ViT-39M-16-Text-19M", + checkpoint="/mnt/SSD8T/home/wjj/code/DeCLIP_private/checkpoints/TinyCLIP-ViT-39M-16-Text-19M-YFCC15M.pt", + mode="proxyclip", # Use proxyclip mode + beta=1.2, # ProxyCLIP beta parameter + gamma=3.0, # ProxyCLIP gamma parameter + prob_thd=0.0, + logit_scale=40, + slide_stride=112, + slide_crop=336, +) + +# dataset settings +dataset_type = "PascalVOC20Dataset" +data_root = "/mnt/SSD8T/home/wjj/dataset/VOCdevkit/VOC2012" + +test_pipeline = [ + dict(type="LoadImageFromFile"), + dict(type="Resize", scale=(2048, 336), keep_ratio=True), + dict(type="LoadAnnotations"), + dict( + type="PackSegInputs", + meta_keys=( + "img_path", + "seg_map_path", + "ori_shape", + "img_shape", + "pad_shape", + "scale_factor", + "flip", + "flip_direction", + "reduce_zero_label", + "resize_shape", + ), + ), +] + +test_dataloader = dict( + batch_size=1, + num_workers=4, + persistent_workers=True, + sampler=dict(type="DefaultSampler", shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + data_prefix=dict( + img_path="JPEGImages", seg_map_path="SegmentationClass" + ), + ann_file="ImageSets/Segmentation/val.txt", + pipeline=test_pipeline, + ), +) + diff --git a/downstream/ProxyCLIP_TPAMI/configs/tinyclip_proxy_sam/cfg_voc21_proxy.py b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_proxy_sam/cfg_voc21_proxy.py new file mode 100644 index 0000000000000000000000000000000000000000..93b8198b2b806c78df38fda9b9012829ee7e3534 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/configs/tinyclip_proxy_sam/cfg_voc21_proxy.py @@ -0,0 +1,64 @@ +_base_ = './base_config.py' + +# model settings +# 使用TinyCLIP+ProxyCLIP模型进行分割 +# 模型: TinyCLIP-ViT-39M-16-Text-19M +# VFM: SAM-B +# 模式: proxyclip + +model = dict( + name_path="configs/proxyclip/cls_voc21.txt", + vfm_model="sam-B", # Options: 'sam-B', 'sam-L', 'dinov2-B', 'dinov2-L', 'dino-B-8', 'dino-B-16' + type="TinyCLIPProxySegmentation", + clip_type="TinyCLIP-ViT-39M-16-Text-19M", + checkpoint="/mnt/SSD8T/home/wjj/code/DeCLIP_private/checkpoints/TinyCLIP-ViT-39M-16-Text-19M-YFCC15M.pt", + mode="proxyclip", # Use proxyclip mode + beta=1.2, # ProxyCLIP beta parameter + gamma=3.0, # ProxyCLIP gamma parameter + prob_thd=0.5, + logit_scale=80, + slide_stride=112, + slide_crop=336, +) + +# dataset settings +dataset_type = "PascalVOCDataset" +data_root = "/mnt/SSD8T/home/wjj/dataset/VOCdevkit/VOC2012" + +test_pipeline = [ + dict(type="LoadImageFromFile"), + dict(type="Resize", scale=(2048, 336), keep_ratio=True), + dict(type="LoadAnnotations"), + dict( + type="PackSegInputs", + meta_keys=( + "img_path", + "seg_map_path", + "ori_shape", + "img_shape", + "pad_shape", + "scale_factor", + "flip", + "flip_direction", + "reduce_zero_label", + "resize_shape", + ), + ), +] + +test_dataloader = dict( + batch_size=1, + num_workers=4, + persistent_workers=True, + sampler=dict(type="DefaultSampler", shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + data_prefix=dict( + img_path="JPEGImages", seg_map_path="SegmentationClass" + ), + ann_file="ImageSets/Segmentation/val.txt", + pipeline=test_pipeline, + ), +) + diff --git a/downstream/ProxyCLIP_TPAMI/env_setup/.gitignore b/downstream/ProxyCLIP_TPAMI/env_setup/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..3b30d26dad9474359b901279d4947829e79d8741 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/env_setup/.gitignore @@ -0,0 +1 @@ +annotation_archives/ diff --git a/downstream/ProxyCLIP_TPAMI/env_setup/DATASETS_AND_WEIGHTS.md b/downstream/ProxyCLIP_TPAMI/env_setup/DATASETS_AND_WEIGHTS.md new file mode 100644 index 0000000000000000000000000000000000000000..6ba09d4855e9b742c67109e06442d76fed055674 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/env_setup/DATASETS_AND_WEIGHTS.md @@ -0,0 +1,322 @@ +# ProxyCLIP TPAMI - 数据集与预训练权重说明 + +## 📊 数据集 + +### 1. ADE20K +- **用途**: 场景解析(150类) +- **原始路径**: `/mnt/SSD8T/home/wjj/dataset/ADEChallengeData2016` +- **目录结构**: + ``` + ADEChallengeData2016/ + ├── images/ + │ ├── training/ + │ └── validation/ + └── annotations/ + ├── training/ + └── validation/ + ``` +- **下载**: http://sceneparsing.csail.mit.edu/ + +### 2. Cityscapes +- **用途**: 城市场景分割(19类) +- **原始路径**: `/mnt/SSD8T/home/wjj/dataset/cityscapes` +- **目录结构**: + ``` + cityscapes/ + ├── leftImg8bit/ + │ ├── train/ + │ └── val/ + └── gtFine/ + ├── train/ + └── val/ + ``` +- **下载**: https://www.cityscapes-dataset.com/ + +### 3. COCO-Stuff 164K +- **用途**: 复杂场景分割(171类) +- **原始路径**: `/mnt/SSD8T/home/wjj/dataset/standard_coco` +- **目录结构**: + ``` + standard_coco/ + ├── val2017/ # 图像 + └── annotations/ + └── val2017/ # 分割标注 + ``` +- **下载**: https://github.com/nightrome/cocostuff + +### 4. COCO-Object +- **用途**: 物体分割(81类,含背景) +- **原始路径**: `/mnt/SSD8T/home/wjj/dataset/coco_obj` +- **目录结构**: + ``` + coco_obj/ + ├── images/ + └── annotations/ + ``` + +### 5. PASCAL VOC 2012 +- **用途**: VOC20/VOC21 分割 +- **原始路径**: `/mnt/SSD8T/home/wjj/dataset/VOCdevkit/VOC2012` +- **目录结构**: + ``` + VOCdevkit/ + └── VOC2012/ + ├── JPEGImages/ + ├── SegmentationClass/ + └── ImageSets/ + └── Segmentation/ + ``` +- **下载**: http://host.robots.ox.ac.uk/pascal/VOC/voc2012/ + +### 6. PASCAL Context (VOC2010) +- **用途**: 上下文分割(59/60/459类) +- **原始路径**: `/mnt/SSD8T/home/wjj/dataset/VOCdevkit/VOC2010` +- **目录结构**: + ``` + VOCdevkit/ + └── VOC2010/ + ├── JPEGImages/ + ├── SegmentationClassContext/ + └── ImageSets/ + └── SegmentationContext/ + ``` +- **下载**: https://cs.stanford.edu/~roozbeh/pascal-context/ + +--- + +## 🔧 预训练权重 + +### 1. SAM (Segment Anything Model) +| 文件名 | 模型 | 大小 | 用途 | +|--------|------|------|------| +| `sam_vit_b_01ec64.pth` | ViT-B | 375MB | ProxyCLIP VFM | +| `sam_vit_l_0b3195.pth` | ViT-L | 1.2GB | ProxyCLIP VFM | + +- **下载**: https://github.com/facebookresearch/segment-anything +- **存放路径**: `sam_ckpts/` + +### 2. TinyCLIP (预训练) +| 文件名 | 描述 | +|--------|------| +| `TinyCLIP-ViT-39M-16-Text-19M-YFCC15M.pt` | TinyCLIP 原始预训练权重 | + +- **下载**: https://github.com/microsoft/Cream/tree/main/TinyCLIP +- **存放路径**: `checkpoints/` + +### 3. DeCLIP 训练权重 (EVA-CLIP) +| 文件名 | 描述 | +|--------|------| +| `EVA-B_DINOv2-B_csa_560_declip2_0.25_1.0_0.05/epoch_6.pt` | EVA-CLIP + DeCLIP 训练 | + +- **存放路径**: `checkpoints/eva_declip/` + +### 4. DeCLIP 训练权重 (TinyCLIP) +| 文件名 | 描述 | +|--------|------| +| `TinyCLIP_39M_DeCLIP+_dinov2B_csa_560_0.25_1.0_0.05_alpha0.4/epoch_6.pt` | TinyCLIP + DeCLIP 训练 | + +- **存放路径**: `checkpoints/tinyclip_declip/` + +### 5. DINOv2 / DINO +- **下载方式**: 通过 `torch.hub` 自动下载 +- **缓存路径**: `~/.cache/torch/hub/` +- **支持的模型**: + - `dinov2_vitb14_reg`, `dinov2_vitl14_reg` + - `dinov2_vitb14`, `dinov2_vitl14` + - `dino_vitb8`, `dino_vitb16` + +--- + +## 📁 新机器目录结构建议 + +``` +/path/to/your/data/ +├── datasets/ +│ ├── ADEChallengeData2016/ +│ ├── cityscapes/ +│ ├── standard_coco/ +│ ├── coco_obj/ +│ └── VOCdevkit/ +│ ├── VOC2010/ +│ └── VOC2012/ +└── checkpoints/ + ├── sam/ + │ ├── sam_vit_b_01ec64.pth + │ └── sam_vit_l_0b3195.pth + ├── tinyclip/ + │ └── TinyCLIP-ViT-39M-16-Text-19M-YFCC15M.pt + ├── eva_declip/ + │ └── epoch_6.pt + └── tinyclip_declip/ + └── epoch_6.pt +``` + +--- + +## 🔄 配置路径更新 + +在新机器上,需要更新配置文件中的路径。可以使用环境变量或直接修改: + +### 方式一:使用环境变量(推荐) +```bash +export DATASET_ROOT=/path/to/datasets +export CHECKPOINT_ROOT=/path/to/checkpoints +``` + +### 方式二:批量替换路径 +```bash +# 在项目根目录运行 +find configs -name "*.py" -exec sed -i 's|/mnt/SSD8T/home/wjj/dataset|/your/new/path|g' {} \; +find configs -name "*.py" -exec sed -i 's|/mnt/SSD8T/home/wjj/code/DeCLIP|/your/new/path|g' {} \; +``` + +--- + +## 🌐 从 HuggingFace 下载 + +### 下载权重 +```python +from huggingface_hub import hf_hub_download, snapshot_download + +# 下载整个权重仓库 +snapshot_download( + repo_id="xiaomoguhzz/xiaomogu_pami", + local_dir="./checkpoints", + repo_type="model" +) +``` + +### 下载数据集标注 +```python +from huggingface_hub import snapshot_download + +# 下载数据集标注 +snapshot_download( + repo_id="xiaomoguhzz/xiaomogu_pami_dataset", + local_dir="./datasets", + repo_type="dataset" +) +``` + +或使用命令行: +```bash +# 下载权重 +huggingface-cli download xiaomoguhzz/xiaomogu_pami --local-dir ./checkpoints + +# 下载数据集标注 +huggingface-cli download xiaomoguhzz/xiaomogu_pami_dataset --local-dir ./datasets --repo-type dataset +``` + +--- + +## 📦 数据集标注说明 + +HuggingFace 数据集仓库中只包含**标注文件**(不含原始图片),以减小下载体积。 + +### 标注压缩包列表 + +| 文件名 | 大小 | 内容 | +|--------|------|------| +| `ade20k_annotations.tar.gz` | 84MB | ADE20K 分割标注 | +| `cityscapes_gtfine.tar.gz` | 367MB | Cityscapes gtFine 标注 | +| `coco_object_annotations.tar.gz` | 321MB | COCO-Object 分割标注 | +| `coco_stuff_annotations.tar.gz` | 3.5GB | COCO-Stuff 标注 (含 refcoco 等) | +| `voc2010_context_annotations.tar.gz` | 38MB | PASCAL Context 标注 | +| `voc2012_annotations.tar.gz` | 38MB | PASCAL VOC 2012 标注 | + +### 解压标注 + +```bash +cd datasets/annotations + +# 解压 ADE20K +mkdir -p ADEChallengeData2016 && tar -xzf ade20k_annotations.tar.gz -C ADEChallengeData2016 + +# 解压 Cityscapes +mkdir -p cityscapes && tar -xzf cityscapes_gtfine.tar.gz -C cityscapes + +# 解压 COCO-Stuff +mkdir -p standard_coco && tar -xzf coco_stuff_annotations.tar.gz -C standard_coco + +# 解压 COCO-Object +mkdir -p coco_obj && tar -xzf coco_object_annotations.tar.gz -C coco_obj + +# 解压 VOC2012 +mkdir -p VOCdevkit/VOC2012 && tar -xzf voc2012_annotations.tar.gz -C VOCdevkit/VOC2012 + +# 解压 VOC2010 (Context) +mkdir -p VOCdevkit/VOC2010 && tar -xzf voc2010_context_annotations.tar.gz -C VOCdevkit/VOC2010 +``` + +### 获取原始图片 + +#### 方式一:使用一键下载脚本(推荐) + +```bash +cd env_setup + +# 交互式选择下载 +./download_datasets.sh + +# 或直接下载全部 (约35GB) +DATA_ROOT=/path/to/datasets ./download_datasets.sh --all + +# 下载单个数据集 +./download_datasets.sh --ade20k +./download_datasets.sh --coco +./download_datasets.sh --voc2012 +./download_datasets.sh --pascal-context +./download_datasets.sh --cityscapes # 需要 Cityscapes 账号 +``` + +#### 方式二:手动下载 + +| 数据集 | 大小 | 下载地址 | +|--------|------|----------| +| ADE20K | ~1.1GB | http://sceneparsing.csail.mit.edu/ | +| Cityscapes | ~12GB | https://www.cityscapes-dataset.com/ (需注册) | +| COCO 2017 | ~20GB | https://cocodataset.org/ | +| PASCAL VOC 2012 | ~2GB | http://host.robots.ox.ac.uk/pascal/VOC/voc2012/ | +| PASCAL Context | ~1GB | https://cs.stanford.edu/~roozbeh/pascal-context/ | + +下载后将图片放入对应目录: +- ADE20K: `images/training/`, `images/validation/` +- Cityscapes: `leftImg8bit/train/`, `leftImg8bit/val/` +- COCO: `val2017/`, `train2017/` +- VOC: `JPEGImages/` + +--- + +## 🚀 完整迁移流程 + +在新机器上的完整操作步骤: + +```bash +# 1. 克隆代码 +git clone https://github.com/xiaomoguhz/ProxyCLIP_TPAMI.git +cd ProxyCLIP_TPAMI + +# 2. 配置 Python 环境 +cd env_setup && ./setup_env.sh + +# 3. 下载权重 (从 HuggingFace) +conda activate proxyclip_tpami +python download_from_hf.py --download-weights --output-dir ../checkpoints + +# 4. 下载标注 (从 HuggingFace) +python download_from_hf.py --download-datasets --output-dir ./datasets + +# 5. 解压标注 +cd datasets/annotations +for f in *.tar.gz; do + name="${f%.tar.gz}" + mkdir -p "../$name" && tar -xzf "$f" -C "../$name" +done + +# 6. 下载图片 (选择需要的数据集) +cd ../../ +DATA_ROOT=./datasets ./download_datasets.sh --all + +# 7. 更新配置路径 +python update_paths.py --dataset-root ./datasets --checkpoint-root ./checkpoints +``` diff --git a/downstream/ProxyCLIP_TPAMI/env_setup/README.md b/downstream/ProxyCLIP_TPAMI/env_setup/README.md new file mode 100644 index 0000000000000000000000000000000000000000..e482b0f12350768a5d7b376b7c1230f564002ce2 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/env_setup/README.md @@ -0,0 +1,230 @@ +# ProxyCLIP TPAMI 环境配置指南 + +本文件夹包含项目一键迁移所需的所有配置文件和脚本。 + +## 📁 文件列表 + +| 文件 | 用途 | +|------|------| +| `setup_env.sh` | 一键配置 Python 环境 | +| `requirements.txt` | pip 依赖列表 | +| `pyproject.toml` | uv 项目配置 | +| `environment.yml` | conda 环境配置 | +| `install_local_packages.sh` | 安装本地包脚本 | +| `upload_to_hf.py` | 上传权重/数据集到 HuggingFace | +| `download_from_hf.py` | 从 HuggingFace 下载权重/数据集 | +| `update_paths.py` | 批量更新配置文件路径 | +| `DATASETS_AND_WEIGHTS.md` | 数据集和权重详细说明 | + +## 🚀 快速开始 + +### 方式一:使用 uv 一键配置(推荐) + +```bash +cd env_setup +chmod +x setup_env.sh + +# 默认配置 (CUDA 11.8, Python 3.10) +./setup_env.sh + +# 自定义 CUDA 版本 +./setup_env.sh --cuda-version 12.1 + +# 自定义环境名称 +./setup_env.sh --env-name my_env --cuda-version 12.4 +``` + +### 方式二:手动配置 + +#### 1. 安装 PyTorch + +根据你的 CUDA 版本选择: + +```bash +# CUDA 11.8 +pip install torch==2.0.0 torchvision==0.15.1 --index-url https://download.pytorch.org/whl/cu118 + +# CUDA 12.1 +pip install torch==2.1.0 torchvision==0.16.0 --index-url https://download.pytorch.org/whl/cu121 + +# CUDA 12.4 +pip install torch==2.4.0 torchvision==0.19.0 --index-url https://download.pytorch.org/whl/cu124 +``` + +#### 2. 安装核心依赖 + +```bash +pip install -r env_setup/requirements.txt +``` + +#### 3. 安装本地包 + +```bash +# 安装 clipself (CLIP 修改版) +cd clipself && pip install -e . && cd .. + +# 安装 segment_anything +cd segment_anything && pip install -e . && cd .. + +# 安装 imagecorruptions (鲁棒性测试) +cd imagecorruptions && pip install -e . && cd .. +``` + +## 依赖说明 + +### 核心依赖 + +| 包名 | 版本 | 用途 | +|------|------|------| +| torch | 2.0.0+ | 深度学习框架 | +| torchvision | 0.15.1+ | 视觉处理 | +| mmcv | 2.1.0 | OpenMMLab 基础库 | +| mmengine | 0.10.4 | OpenMMLab 引擎 | +| mmsegmentation | 1.2.2 | 语义分割框架 | +| timm | 1.0.0+ | 预训练模型 | +| einops | 0.8.0+ | 张量操作 | +| Pillow | 9.4.0+ | 图像处理 | +| opencv-python | 4.8.0+ | 计算机视觉 | + +### 本地包 + +- **clipself**: 修改版 OpenCLIP,支持密集特征提取 +- **segment_anything**: Meta SAM 模型 +- **imagecorruptions**: 图像损坏模拟,用于鲁棒性测试 + +## 数据准备 + +### 数据集目录结构 + +``` +data/ +├── ADEChallengeData2016/ # ADE20K +├── VOCdevkit/ # PASCAL VOC +│ └── VOC2012/ +├── cityscapes/ # Cityscapes +└── coco_stuff164k/ # COCO-Stuff 164K +``` + +### 预训练模型 + +SAM 模型权重放置位置: +``` +sam_ckpts/ +├── sam_vit_b_01ec64.pth +└── sam_vit_l_0b3195.pth +``` + +DINOv2 模型会通过 `torch.hub` 自动下载到 `~/.cache/torch/hub/` + +## 验证安装 + +```bash +python -c " +import torch +import mmseg +import open_clip +print(f'PyTorch: {torch.__version__}') +print(f'CUDA: {torch.cuda.is_available()}') +print(f'MMSeg: {mmseg.__version__}') +print('Installation successful!') +" +``` + +## 运行评估 + +```bash +# ADE20K +python eval.py --config configs/proxyclip/cfg_ade20k.py + +# PASCAL Context 59 +python eval.py --config configs/proxyclip/cfg_voc_context59.py + +# Cityscapes +python eval.py --config configs/proxyclip/cfg_cityscapes.py +``` + +## 常见问题 + +### Q: CUDA 版本不匹配 + +检查你的 NVIDIA 驱动支持的最高 CUDA 版本: +```bash +nvidia-smi +``` + +### Q: mmcv 安装失败 + +尝试使用预编译版本: +```bash +pip install mmcv==2.1.0 -f https://download.openmmlab.com/mmcv/dist/cu118/torch2.0/index.html +``` + +### Q: 内存不足 + +减小 batch size 或使用更小的 crop size: +```python +# 在配置文件中修改 +slide_crop=224 # 减小 crop size +``` + +--- + +## 🔄 完整迁移流程 + +### 在旧机器上(上传) + +```bash +cd env_setup + +# 1. 上传权重到 HuggingFace(预览) +python upload_to_hf.py --upload-weights --dry-run + +# 2. 确认后实际上传 +python upload_to_hf.py --upload-weights + +# 3. (可选) 上传数据集 +python upload_to_hf.py --upload-datasets +``` + +### 在新机器上(下载) + +```bash +# 1. 克隆项目 +git clone +cd ProxyCLIP_TPAMI/env_setup + +# 2. 配置环境 +chmod +x setup_env.sh +./setup_env.sh --cuda-version 11.8 # 根据新机器调整 + +# 3. 激活环境 +source ../.venv_proxyclip_tpami/bin/activate + +# 4. 下载权重 +python download_from_hf.py --download-weights --weights-dir ../checkpoints + +# 5. 下载数据集 (或手动准备) +python download_from_hf.py --download-datasets --datasets-dir /path/to/datasets + +# 6. 更新配置文件中的路径 +python update_paths.py \ + --dataset-root /path/to/datasets \ + --checkpoint-root ../checkpoints + +# 7. 运行测试 +cd .. +python eval.py --config configs/proxyclip/cfg_ade20k.py +``` + +### HuggingFace 仓库 + +| 仓库 | 内容 | 地址 | +|------|------|------| +| 权重 | SAM, TinyCLIP, DeCLIP 等 | `xiaomoguhzz/xiaomogu_pami` | +| 数据集 | 标注文件压缩包 (不含图片) | `xiaomoguhzz/xiaomogu_pami_dataset` | + +### 数据集说明 + +HuggingFace 数据集仓库只包含**标注文件**,原始图片需从官方渠道下载。 + +详见 [DATASETS_AND_WEIGHTS.md](./DATASETS_AND_WEIGHTS.md) diff --git a/downstream/ProxyCLIP_TPAMI/env_setup/compress_datasets.py b/downstream/ProxyCLIP_TPAMI/env_setup/compress_datasets.py new file mode 100644 index 0000000000000000000000000000000000000000..5adc738aee6d00d3eecf7f467e0b77f028fb952f --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/env_setup/compress_datasets.py @@ -0,0 +1,212 @@ +#!/usr/bin/env python3 +""" +压缩数据集并上传到 HuggingFace +===================================================== +每个数据集单独压缩为 tar.gz 文件,便于下载和管理 +===================================================== +""" + +import os +import tarfile +import argparse +from pathlib import Path +from tqdm import tqdm + +try: + from huggingface_hub import HfApi, login, upload_file +except ImportError: + print("请先安装 huggingface_hub: pip install huggingface_hub") + exit(1) + +# HuggingFace 仓库 +DATASET_REPO = "xiaomoguhzz/xiaomogu_pami_dataset" + +# 数据集配置 +DATASETS = { + "ade20k": { + "source": "/mnt/SSD8T/home/wjj/dataset/ADEChallengeData2016", + "archive_name": "ADEChallengeData2016.tar.gz", + "description": "ADE20K Dataset (150 classes)" + }, + "cityscapes": { + "source": "/mnt/SSD8T/home/wjj/dataset/cityscapes", + "archive_name": "cityscapes.tar.gz", + "description": "Cityscapes Dataset (19 classes)" + }, + "coco_stuff": { + "source": "/mnt/SSD8T/home/wjj/dataset/standard_coco", + "archive_name": "coco_stuff_164k.tar.gz", + "description": "COCO-Stuff 164K Dataset (171 classes)" + }, + "coco_obj": { + "source": "/mnt/SSD8T/home/wjj/dataset/coco_obj", + "archive_name": "coco_object.tar.gz", + "description": "COCO-Object Dataset (81 classes)" + }, + "voc2012": { + "source": "/mnt/SSD8T/home/wjj/dataset/VOCdevkit/VOC2012", + "archive_name": "VOC2012.tar.gz", + "description": "PASCAL VOC 2012" + }, + "voc2010": { + "source": "/mnt/SSD8T/home/wjj/dataset/VOCdevkit/VOC2010", + "archive_name": "VOC2010_context.tar.gz", + "description": "PASCAL Context (VOC2010)" + }, +} + + +def get_dir_size(path: Path) -> int: + """获取目录大小""" + total = 0 + for f in path.rglob('*'): + if f.is_file(): + total += f.stat().st_size + return total + + +def compress_dataset(name: str, config: dict, output_dir: Path, dry_run: bool = False) -> Path: + """压缩单个数据集""" + source = Path(config["source"]) + archive_name = config["archive_name"] + output_path = output_dir / archive_name + + print(f"\n{'='*60}") + print(f"📦 [{name}] {config['description']}") + print(f"{'='*60}") + print(f"源路径: {source}") + print(f"输出文件: {output_path}") + + if not source.exists(): + print(f"⚠️ 源路径不存在,跳过") + return None + + # 计算源目录大小 + size_bytes = get_dir_size(source) + size_gb = size_bytes / (1024**3) + print(f"源目录大小: {size_gb:.2f} GB") + + if dry_run: + print(f"🔍 [DRY RUN] 将压缩为: {archive_name}") + return output_path + + if output_path.exists(): + existing_size = output_path.stat().st_size / (1024**3) + print(f"✅ 已存在压缩文件 ({existing_size:.2f} GB)") + return output_path + + # 创建 tar.gz 压缩文件 + print(f"⏳ 正在压缩...") + + try: + with tarfile.open(output_path, "w:gz") as tar: + # 使用 arcname 保持目录结构 + tar.add(source, arcname=source.name) + + compressed_size = output_path.stat().st_size / (1024**3) + compression_ratio = (1 - compressed_size / size_gb) * 100 if size_gb > 0 else 0 + print(f"✅ 压缩完成: {compressed_size:.2f} GB (压缩率: {compression_ratio:.1f}%)") + return output_path + except Exception as e: + print(f"❌ 压缩失败: {e}") + return None + + +def upload_datasets(api: HfApi, archives: dict, dry_run: bool = False): + """上传压缩的数据集到 HuggingFace""" + print(f"\n{'='*60}") + print(f"📤 上传到 HuggingFace: {DATASET_REPO}") + print(f"{'='*60}") + + for name, archive_path in archives.items(): + if archive_path is None or not archive_path.exists(): + continue + + size_gb = archive_path.stat().st_size / (1024**3) + print(f"\n[{name}] {archive_path.name} ({size_gb:.2f} GB)") + + if dry_run: + print(f" 🔍 [DRY RUN] 将上传到: {archive_path.name}") + continue + + try: + print(f" ⏳ 正在上传...") + api.upload_file( + path_or_fileobj=str(archive_path), + path_in_repo=archive_path.name, + repo_id=DATASET_REPO, + repo_type="dataset", + ) + print(f" ✅ 上传完成") + except Exception as e: + print(f" ❌ 上传失败: {e}") + + +def main(): + parser = argparse.ArgumentParser(description="压缩数据集并上传到 HuggingFace") + parser.add_argument("--compress-only", action="store_true", help="仅压缩,不上传") + parser.add_argument("--upload-only", action="store_true", help="仅上传已压缩的文件") + parser.add_argument("--output-dir", type=str, default="./dataset_archives", help="压缩文件输出目录") + parser.add_argument("--datasets", type=str, nargs="+", + choices=list(DATASETS.keys()) + ["all"], + default=["all"], help="要处理的数据集") + parser.add_argument("--dry-run", action="store_true", help="预览模式") + parser.add_argument("--token", type=str, help="HuggingFace token") + args = parser.parse_args() + + # 输出目录 + output_dir = Path(args.output_dir).resolve() + output_dir.mkdir(parents=True, exist_ok=True) + + # 确定要处理的数据集 + if "all" in args.datasets: + datasets_to_process = DATASETS + else: + datasets_to_process = {k: v for k, v in DATASETS.items() if k in args.datasets} + + print("="*60) + print("📊 数据集压缩与上传工具") + print("="*60) + print(f"输出目录: {output_dir}") + print(f"处理数据集: {list(datasets_to_process.keys())}") + + if args.dry_run: + print("\n🔍 [DRY RUN] 预览模式\n") + + archives = {} + + # 压缩数据集 + if not args.upload_only: + for name, config in datasets_to_process.items(): + archive_path = compress_dataset(name, config, output_dir, dry_run=args.dry_run) + archives[name] = archive_path + else: + # 仅上传模式,查找已有的压缩文件 + for name, config in datasets_to_process.items(): + archive_path = output_dir / config["archive_name"] + if archive_path.exists(): + archives[name] = archive_path + else: + print(f"⚠️ 未找到: {archive_path}") + + # 上传到 HuggingFace + if not args.compress_only: + if not args.dry_run: + print("\n🔐 登录 HuggingFace...") + if args.token: + login(token=args.token) + else: + login() + api = HfApi() + else: + api = None + + upload_datasets(api, archives, dry_run=args.dry_run) + + print(f"\n{'='*60}") + print("✅ 操作完成!") + print("="*60) + + +if __name__ == "__main__": + main() diff --git a/downstream/ProxyCLIP_TPAMI/env_setup/create_github_repo.md b/downstream/ProxyCLIP_TPAMI/env_setup/create_github_repo.md new file mode 100644 index 0000000000000000000000000000000000000000..41b9a924020cc6b6cd92064a067eeb50833039c7 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/env_setup/create_github_repo.md @@ -0,0 +1,52 @@ +# 创建 GitHub 私有仓库 + +由于需要认证才能创建仓库,请按以下步骤操作: + +## 方式一:在 GitHub 网页创建 + +1. 打开 https://github.com/new +2. 仓库名称: `ProxyCLIP_TPAMI` +3. 选择 `Private` +4. **不要**勾选 "Add a README file" +5. 点击 "Create repository" + +## 方式二:使用 GitHub CLI + +```bash +# 安装 gh CLI (如果没有) +# Ubuntu/Debian +sudo apt install gh + +# 登录 +gh auth login + +# 创建私有仓库 +gh repo create ProxyCLIP_TPAMI --private --source=. --remote=origin --push +``` + +## 推送代码 + +创建仓库后,运行推送脚本: + +```bash +# 启动代理 (如需要) +# ... + +# 推送 +cd env_setup +chmod +x push_to_github.sh +./push_to_github.sh +``` + +或手动推送: + +```bash +cd /mnt/SSD8T/home/wjj/code/ProxyCLIP_TPAMI + +# 配置代理 (如需要) +git config http.proxy http://127.0.0.1:7897 +git config https.proxy http://127.0.0.1:7897 + +# 推送 +git push -u origin main +``` diff --git a/downstream/ProxyCLIP_TPAMI/env_setup/download_datasets.sh b/downstream/ProxyCLIP_TPAMI/env_setup/download_datasets.sh new file mode 100644 index 0000000000000000000000000000000000000000..e4b0dccdd20e45ff79476a961d5ddb2b3764ee56 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/env_setup/download_datasets.sh @@ -0,0 +1,318 @@ +#!/bin/bash +# ============================================================================= +# 数据集一键下载脚本 +# 参考: https://github.com/open-mmlab/mmsegmentation/blob/main/docs/en/user_guides/2_dataset_prepare.md +# ============================================================================= + +set -e + +# 数据集根目录 (可修改) +DATA_ROOT="${DATA_ROOT:-./data}" + +# 颜色输出 +RED='\033[0;31m' +GREEN='\033[0;32m' +YELLOW='\033[1;33m' +BLUE='\033[0;34m' +NC='\033[0m' # No Color + +echo_info() { echo -e "${BLUE}[INFO]${NC} $1"; } +echo_success() { echo -e "${GREEN}[SUCCESS]${NC} $1"; } +echo_warn() { echo -e "${YELLOW}[WARN]${NC} $1"; } +echo_error() { echo -e "${RED}[ERROR]${NC} $1"; } + +# 创建数据目录 +mkdir -p "$DATA_ROOT" +cd "$DATA_ROOT" + +echo "============================================================" +echo "📦 数据集下载脚本" +echo "============================================================" +echo "数据目录: $(pwd)" +echo "" + +# ============================================================================= +# 1. ADE20K +# ============================================================================= +download_ade20k() { + echo_info "下载 ADE20K 数据集..." + + if [ -d "ADEChallengeData2016/images" ]; then + echo_warn "ADE20K 已存在,跳过下载" + return + fi + + # 官方下载地址 + wget -c http://data.csail.mit.edu/places/ADEchallenge/ADEChallengeData2016.zip + unzip -q ADEChallengeData2016.zip + rm ADEChallengeData2016.zip + + echo_success "ADE20K 下载完成" +} + +# ============================================================================= +# 2. Cityscapes (需要注册) +# ============================================================================= +download_cityscapes() { + echo_info "Cityscapes 数据集需要注册下载" + echo "" + echo " 1. 访问 https://www.cityscapes-dataset.com/register/" + echo " 2. 注册账号并登录" + echo " 3. 下载以下文件:" + echo " - leftImg8bit_trainvaltest.zip (11GB)" + echo " - gtFine_trainvaltest.zip (241MB)" + echo " 4. 解压到 $DATA_ROOT/cityscapes/" + echo "" + + mkdir -p cityscapes + + # 如果有 csDownload 工具 (pip install cityscapesscripts) + if command -v csDownload &> /dev/null; then + echo_info "检测到 csDownload,尝试自动下载..." + echo "请输入 Cityscapes 账号信息:" + read -p "用户名: " CS_USER + read -sp "密码: " CS_PASS + echo "" + + csDownload -d cityscapes -l "$CS_USER" -p "$CS_PASS" gtFine_trainvaltest.zip leftImg8bit_trainvaltest.zip + + cd cityscapes + unzip -q gtFine_trainvaltest.zip + unzip -q leftImg8bit_trainvaltest.zip + rm -f *.zip + cd .. + + echo_success "Cityscapes 下载完成" + else + echo_warn "请手动下载 Cityscapes 数据集" + echo " 提示: pip install cityscapesscripts 可使用自动下载工具" + fi +} + +# ============================================================================= +# 3. COCO 2017 (用于 COCO-Stuff 和 COCO-Object) +# ============================================================================= +download_coco() { + echo_info "下载 COCO 2017 数据集..." + + mkdir -p coco + cd coco + + if [ -d "val2017" ] && [ -d "train2017" ]; then + echo_warn "COCO 图片已存在,跳过下载" + else + # 验证集 (常用) + if [ ! -d "val2017" ]; then + echo_info "下载 val2017 (1GB)..." + wget -c http://images.cocodataset.org/zips/val2017.zip + unzip -q val2017.zip + rm val2017.zip + fi + + # 训练集 (较大) + if [ ! -d "train2017" ]; then + echo_info "下载 train2017 (18GB)..." + wget -c http://images.cocodataset.org/zips/train2017.zip + unzip -q train2017.zip + rm train2017.zip + fi + fi + + # COCO-Stuff 标注 + if [ ! -d "annotations/stuffthingmaps_trainval2017" ]; then + echo_info "下载 COCO-Stuff 标注..." + wget -c http://calvin.inf.ed.ac.uk/wp-content/uploads/data/cocostuffdataset/stuffthingmaps_trainval2017.zip + unzip -q stuffthingmaps_trainval2017.zip -d annotations/ + rm stuffthingmaps_trainval2017.zip + fi + + cd .. + echo_success "COCO 下载完成" +} + +# ============================================================================= +# 4. PASCAL VOC 2012 +# ============================================================================= +download_voc2012() { + echo_info "下载 PASCAL VOC 2012 数据集..." + + mkdir -p VOCdevkit + cd VOCdevkit + + if [ -d "VOC2012/JPEGImages" ]; then + echo_warn "VOC2012 已存在,跳过下载" + else + wget -c http://host.robots.ox.ac.uk/pascal/VOC/voc2012/VOCtrainval_11-May-2012.tar + tar -xf VOCtrainval_11-May-2012.tar + rm VOCtrainval_11-May-2012.tar + fi + + # 下载 SBD 增强标注 (SegmentationClassAug) + if [ ! -d "VOC2012/SegmentationClassAug" ]; then + echo_info "下载 SBD 增强标注..." + # benchmark.tgz from SBD + wget -c https://www2.eecs.berkeley.edu/Research/Projects/CS/vision/grouping/semantic_contours/benchmark.tgz + tar -xzf benchmark.tgz + + # 复制增强标注 + mkdir -p VOC2012/SegmentationClassAug + cp benchmark_RELEASE/dataset/cls/*.mat VOC2012/SegmentationClassAug/ 2>/dev/null || true + + # 转换 mat 到 png (需要 Python) + echo_info "转换 SBD 标注格式..." + python3 << 'EOF' +import os +import numpy as np +from scipy.io import loadmat +from PIL import Image + +src_dir = "benchmark_RELEASE/dataset/cls" +dst_dir = "VOC2012/SegmentationClassAug" +os.makedirs(dst_dir, exist_ok=True) + +for f in os.listdir(src_dir): + if f.endswith('.mat'): + mat = loadmat(os.path.join(src_dir, f)) + seg = mat['GTcls'][0]['Segmentation'][0].astype(np.uint8) + img = Image.fromarray(seg) + img.save(os.path.join(dst_dir, f.replace('.mat', '.png'))) +print(f"Converted {len(os.listdir(dst_dir))} files") +EOF + + rm -rf benchmark_RELEASE benchmark.tgz + fi + + cd .. + echo_success "VOC2012 下载完成" +} + +# ============================================================================= +# 5. PASCAL Context (VOC2010) +# ============================================================================= +download_pascal_context() { + echo_info "下载 PASCAL Context 数据集..." + + mkdir -p VOCdevkit + cd VOCdevkit + + if [ -d "VOC2010/JPEGImages" ]; then + echo_warn "VOC2010 已存在,跳过下载" + else + wget -c http://host.robots.ox.ac.uk/pascal/VOC/voc2010/VOCtrainval_03-May-2010.tar + tar -xf VOCtrainval_03-May-2010.tar + rm VOCtrainval_03-May-2010.tar + fi + + # 下载 Context 标注 + if [ ! -d "VOC2010/trainval" ]; then + echo_info "下载 PASCAL Context 标注..." + wget -c https://cs.stanford.edu/~roozbeh/pascal-context/trainval.tar.gz + tar -xzf trainval.tar.gz -C VOC2010/ + rm trainval.tar.gz + fi + + # 下载 59 类标注 (常用) + if [ ! -f "VOC2010/trainval_merged.json" ]; then + wget -c https://codalabuser.blob.core.windows.net/public/trainval_merged.json -O VOC2010/trainval_merged.json + fi + + cd .. + echo_success "PASCAL Context 下载完成" +} + +# ============================================================================= +# 主菜单 +# ============================================================================= +show_menu() { + echo "" + echo "请选择要下载的数据集 (可多选,用空格分隔):" + echo " 1) ADE20K (~1.1GB)" + echo " 2) Cityscapes (~12GB, 需注册)" + echo " 3) COCO 2017 (~20GB)" + echo " 4) PASCAL VOC 2012 (~2GB)" + echo " 5) PASCAL Context (~1GB)" + echo " a) 全部下载" + echo " q) 退出" + echo "" +} + +# 解析命令行参数 +if [ $# -gt 0 ]; then + case "$1" in + --all|-a) + download_ade20k + download_cityscapes + download_coco + download_voc2012 + download_pascal_context + ;; + --ade20k) download_ade20k ;; + --cityscapes) download_cityscapes ;; + --coco) download_coco ;; + --voc2012) download_voc2012 ;; + --pascal-context) download_pascal_context ;; + --help|-h) + echo "用法: $0 [选项]" + echo "" + echo "选项:" + echo " --all, -a 下载所有数据集" + echo " --ade20k 下载 ADE20K" + echo " --cityscapes 下载 Cityscapes" + echo " --coco 下载 COCO 2017" + echo " --voc2012 下载 PASCAL VOC 2012" + echo " --pascal-context 下载 PASCAL Context" + echo "" + echo "环境变量:" + echo " DATA_ROOT 数据集根目录 (默认: ./data)" + exit 0 + ;; + *) + echo_error "未知选项: $1" + echo "使用 --help 查看帮助" + exit 1 + ;; + esac + exit 0 +fi + +# 交互式菜单 +while true; do + show_menu + read -p "选择: " choices + + case "$choices" in + q|Q) + echo "退出" + exit 0 + ;; + a|A) + download_ade20k + download_cityscapes + download_coco + download_voc2012 + download_pascal_context + break + ;; + *) + for choice in $choices; do + case "$choice" in + 1) download_ade20k ;; + 2) download_cityscapes ;; + 3) download_coco ;; + 4) download_voc2012 ;; + 5) download_pascal_context ;; + *) echo_warn "无效选项: $choice" ;; + esac + done + break + ;; + esac +done + +echo "" +echo "============================================================" +echo_success "数据集下载完成!" +echo "============================================================" +echo "" +echo "目录结构:" +ls -la "$DATA_ROOT" diff --git a/downstream/ProxyCLIP_TPAMI/env_setup/download_from_hf.py b/downstream/ProxyCLIP_TPAMI/env_setup/download_from_hf.py new file mode 100644 index 0000000000000000000000000000000000000000..106c679318d8bf5ebe8da9ae21a3fe48a393762f --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/env_setup/download_from_hf.py @@ -0,0 +1,173 @@ +#!/usr/bin/env python3 +""" +从 HuggingFace 下载预训练权重和数据集 +===================================================== +使用方法: + python download_from_hf.py --download-weights # 下载权重 + python download_from_hf.py --download-datasets # 下载数据集 + python download_from_hf.py --all # 下载全部 +===================================================== +""" + +import os +import argparse +from pathlib import Path + +try: + from huggingface_hub import snapshot_download, hf_hub_download, login +except ImportError: + print("请先安装 huggingface_hub: pip install huggingface_hub") + exit(1) + +# HuggingFace 仓库配置 +WEIGHTS_REPO = "xiaomoguhzz/xiaomogu_pami" +DATASET_REPO = "xiaomoguhzz/xiaomogu_pami_dataset" + +# 默认下载路径 +DEFAULT_WEIGHTS_DIR = "./checkpoints" +DEFAULT_DATASETS_DIR = "./datasets" + + +def download_weights(local_dir: str, token: str = None): + """从 HuggingFace 下载预训练权重""" + print("\n" + "=" * 60) + print("📦 下载预训练权重") + print("=" * 60) + print(f"仓库: {WEIGHTS_REPO}") + print(f"目标路径: {local_dir}") + + local_path = Path(local_dir) + local_path.mkdir(parents=True, exist_ok=True) + + try: + snapshot_download( + repo_id=WEIGHTS_REPO, + local_dir=str(local_path), + repo_type="model", + token=token, + ) + print(f"\n✅ 权重下载完成!") + print(f"📁 保存位置: {local_path.absolute()}") + except Exception as e: + print(f"\n❌ 下载失败: {e}") + return False + + return True + + +def download_datasets(local_dir: str, token: str = None): + """从 HuggingFace 下载数据集""" + print("\n" + "=" * 60) + print("📊 下载数据集") + print("=" * 60) + print(f"仓库: {DATASET_REPO}") + print(f"目标路径: {local_dir}") + print("\n⚠️ 注意: 数据集可能很大,下载需要较长时间") + + local_path = Path(local_dir) + local_path.mkdir(parents=True, exist_ok=True) + + try: + snapshot_download( + repo_id=DATASET_REPO, + local_dir=str(local_path), + repo_type="dataset", + token=token, + ) + print(f"\n✅ 数据集下载完成!") + print(f"📁 保存位置: {local_path.absolute()}") + except Exception as e: + print(f"\n❌ 下载失败: {e}") + return False + + return True + + +def setup_symlinks(project_root: str, weights_dir: str, datasets_dir: str): + """创建符号链接,将下载的文件链接到项目中""" + print("\n" + "=" * 60) + print("🔗 创建符号链接") + print("=" * 60) + + project_path = Path(project_root) + weights_path = Path(weights_dir) + datasets_path = Path(datasets_dir) + + # SAM 权重链接 + sam_ckpts_dir = project_path / "sam_ckpts" + sam_source = weights_path / "sam" + if sam_source.exists() and not sam_ckpts_dir.exists(): + sam_ckpts_dir.symlink_to(sam_source.absolute()) + print(f"✅ sam_ckpts -> {sam_source}") + + print("\n📝 请手动更新配置文件中的路径:") + print(f" - 数据集路径: {datasets_path.absolute()}") + print(f" - 权重路径: {weights_path.absolute()}") + + +def print_usage_guide(weights_dir: str, datasets_dir: str): + """打印使用指南""" + print("\n" + "=" * 60) + print("📖 使用指南") + print("=" * 60) + + print(f""" +下载完成后,请更新配置文件中的路径。 + +1. 更新数据集路径: + 在 configs/ 目录下的配置文件中,将 data_root 修改为: + data_root = "{Path(datasets_dir).absolute()}/ADEChallengeData2016" # ADE20K + data_root = "{Path(datasets_dir).absolute()}/cityscapes" # Cityscapes + 等... + +2. 更新权重路径: + checkpoint = "{Path(weights_dir).absolute()}/tinyclip/TinyCLIP-ViT-39M-16-Text-19M-YFCC15M.pt" + + SAM 权重路径 (在代码中需要更新): + sam_ckpts = {{ + "sam-B": "{Path(weights_dir).absolute()}/sam/sam_vit_b_01ec64.pth", + "sam-L": "{Path(weights_dir).absolute()}/sam/sam_vit_l_0b3195.pth", + }} + +3. 或者使用批量替换脚本: + python env_setup/update_paths.py --dataset-root {Path(datasets_dir).absolute()} --checkpoint-root {Path(weights_dir).absolute()} +""") + + +def main(): + parser = argparse.ArgumentParser(description="从 HuggingFace 下载权重和数据集") + parser.add_argument("--download-weights", action="store_true", help="下载预训练权重") + parser.add_argument("--download-datasets", action="store_true", help="下载数据集") + parser.add_argument("--all", action="store_true", help="下载全部") + parser.add_argument("--weights-dir", type=str, default=DEFAULT_WEIGHTS_DIR, help="权重保存路径") + parser.add_argument("--datasets-dir", type=str, default=DEFAULT_DATASETS_DIR, help="数据集保存路径") + parser.add_argument("--token", type=str, help="HuggingFace token (如果是私有仓库)") + parser.add_argument("--setup-symlinks", action="store_true", help="创建符号链接") + args = parser.parse_args() + + if not (args.download_weights or args.download_datasets or args.all): + parser.print_help() + print("\n请指定要下载的内容: --download-weights, --download-datasets, 或 --all") + return + + success = True + + if args.download_weights or args.all: + success = download_weights(args.weights_dir, args.token) and success + + if args.download_datasets or args.all: + success = download_datasets(args.datasets_dir, args.token) and success + + if success and args.setup_symlinks: + setup_symlinks(".", args.weights_dir, args.datasets_dir) + + if success: + print_usage_guide(args.weights_dir, args.datasets_dir) + + print("\n" + "=" * 60) + print("✅ 操作完成!" if success else "⚠️ 部分操作失败") + print("=" * 60) + + +if __name__ == "__main__": + main() diff --git a/downstream/ProxyCLIP_TPAMI/env_setup/environment.yml b/downstream/ProxyCLIP_TPAMI/env_setup/environment.yml new file mode 100644 index 0000000000000000000000000000000000000000..429925c388e914c460b593649899fabf13a88956 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/env_setup/environment.yml @@ -0,0 +1,70 @@ +# ===================================================== +# ProxyCLIP TPAMI - Conda 环境配置 +# ===================================================== +# 使用方法: +# conda env create -f environment.yml +# conda activate proxyclip_tpami +# +# # 然后安装本地包 +# cd .. && pip install -e clipself/ -e segment_anything/ -e imagecorruptions/ +# ===================================================== + +name: proxyclip_tpami +channels: + - pytorch + - nvidia + - conda-forge + - defaults + +dependencies: + - python=3.10 + + # PyTorch (CUDA 11.8) + # 如果需要其他 CUDA 版本,请修改这里 + - pytorch=2.0.0 + - torchvision=0.15.1 + - pytorch-cuda=11.8 + + # 基础科学计算 + - numpy>=1.24.0,<2.0.0 + - scipy>=1.10.0 + - pandas>=2.0.0 + + # 图像处理 + - pillow>=9.4.0 + - scikit-image>=0.18.0 + + # 工具 + - pyyaml>=6.0 + - tqdm>=4.65.0 + - rich>=13.0.0 + + # pip 安装的包 + - pip + - pip: + # MMSeg 生态系统 + - mmcv==2.1.0 + - mmengine==0.10.4 + - mmsegmentation==1.2.2 + + # CLIP & 视觉模型 + - ftfy>=6.1.0 + - regex>=2024.0.0 + - timm>=1.0.0 + - einops>=0.8.0 + - sentencepiece>=0.2.0 + - protobuf>=3.20.0,<4.0.0 + - huggingface-hub>=0.20.0 + + # 图像处理 + - opencv-python>=4.8.0 + + # 数据处理 + - openpyxl>=3.1.0 + - addict>=2.4.0 + - yapf>=0.40.0 + + # 其他 + - termcolor>=2.0.0 + - terminaltables>=3.1.0 + - pycocotools>=2.0.7 diff --git a/downstream/ProxyCLIP_TPAMI/env_setup/extract_annotations.sh b/downstream/ProxyCLIP_TPAMI/env_setup/extract_annotations.sh new file mode 100644 index 0000000000000000000000000000000000000000..fde2411b70ebe08c4a05d07420005eadbe31036c --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/env_setup/extract_annotations.sh @@ -0,0 +1,93 @@ +#!/bin/bash +# ============================================================================= +# 解压从 HuggingFace 下载的标注文件 +# ============================================================================= + +set -e + +# 默认路径 +ANNOTATIONS_DIR="${1:-./datasets/annotations}" +OUTPUT_DIR="${2:-./datasets}" + +RED='\033[0;31m' +GREEN='\033[0;32m' +BLUE='\033[0;34m' +NC='\033[0m' + +echo_info() { echo -e "${BLUE}[INFO]${NC} $1"; } +echo_success() { echo -e "${GREEN}[SUCCESS]${NC} $1"; } +echo_error() { echo -e "${RED}[ERROR]${NC} $1"; } + +echo "============================================================" +echo "📦 解压标注文件" +echo "============================================================" +echo "源目录: $ANNOTATIONS_DIR" +echo "输出目录: $OUTPUT_DIR" +echo "" + +if [ ! -d "$ANNOTATIONS_DIR" ]; then + echo_error "标注目录不存在: $ANNOTATIONS_DIR" + echo "请先运行: python download_from_hf.py --download-datasets" + exit 1 +fi + +mkdir -p "$OUTPUT_DIR" + +# ADE20K +if [ -f "$ANNOTATIONS_DIR/ade20k_annotations.tar.gz" ]; then + echo_info "解压 ADE20K 标注..." + mkdir -p "$OUTPUT_DIR/ADEChallengeData2016" + tar -xzf "$ANNOTATIONS_DIR/ade20k_annotations.tar.gz" -C "$OUTPUT_DIR/ADEChallengeData2016" + echo_success "ADE20K 完成" +fi + +# Cityscapes +if [ -f "$ANNOTATIONS_DIR/cityscapes_gtfine.tar.gz" ]; then + echo_info "解压 Cityscapes 标注..." + mkdir -p "$OUTPUT_DIR/cityscapes" + tar -xzf "$ANNOTATIONS_DIR/cityscapes_gtfine.tar.gz" -C "$OUTPUT_DIR/cityscapes" + echo_success "Cityscapes 完成" +fi + +# COCO-Stuff +if [ -f "$ANNOTATIONS_DIR/coco_stuff_annotations.tar.gz" ]; then + echo_info "解压 COCO-Stuff 标注 (较大,请等待)..." + mkdir -p "$OUTPUT_DIR/standard_coco" + tar -xzf "$ANNOTATIONS_DIR/coco_stuff_annotations.tar.gz" -C "$OUTPUT_DIR/standard_coco" + echo_success "COCO-Stuff 完成" +fi + +# COCO-Object +if [ -f "$ANNOTATIONS_DIR/coco_object_annotations.tar.gz" ]; then + echo_info "解压 COCO-Object 标注..." + mkdir -p "$OUTPUT_DIR/coco_obj" + tar -xzf "$ANNOTATIONS_DIR/coco_object_annotations.tar.gz" -C "$OUTPUT_DIR/coco_obj" + echo_success "COCO-Object 完成" +fi + +# VOC2012 +if [ -f "$ANNOTATIONS_DIR/voc2012_annotations.tar.gz" ]; then + echo_info "解压 VOC2012 标注..." + mkdir -p "$OUTPUT_DIR/VOCdevkit/VOC2012" + tar -xzf "$ANNOTATIONS_DIR/voc2012_annotations.tar.gz" -C "$OUTPUT_DIR/VOCdevkit/VOC2012" + echo_success "VOC2012 完成" +fi + +# VOC2010 (PASCAL Context) +if [ -f "$ANNOTATIONS_DIR/voc2010_context_annotations.tar.gz" ]; then + echo_info "解压 PASCAL Context 标注..." + mkdir -p "$OUTPUT_DIR/VOCdevkit/VOC2010" + tar -xzf "$ANNOTATIONS_DIR/voc2010_context_annotations.tar.gz" -C "$OUTPUT_DIR/VOCdevkit/VOC2010" + echo_success "PASCAL Context 完成" +fi + +echo "" +echo "============================================================" +echo_success "所有标注解压完成!" +echo "============================================================" +echo "" +echo "目录结构:" +ls -la "$OUTPUT_DIR" +echo "" +echo "⚠️ 提示: 还需要下载原始图片,运行:" +echo " ./download_datasets.sh" diff --git a/downstream/ProxyCLIP_TPAMI/env_setup/install_local_packages.sh b/downstream/ProxyCLIP_TPAMI/env_setup/install_local_packages.sh new file mode 100644 index 0000000000000000000000000000000000000000..4ee77c2d2204549217e93044262b1fbd6f3610cd --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/env_setup/install_local_packages.sh @@ -0,0 +1,73 @@ +#!/bin/bash +# ===================================================== +# 安装本地包脚本 +# ===================================================== +# 在激活环境后运行此脚本安装本地依赖包 +# ===================================================== + +set -e + +SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" +PROJECT_ROOT="$( cd "$SCRIPT_DIR/.." && pwd )" + +echo "安装本地包..." +echo "项目根目录: $PROJECT_ROOT" + +# 检查是否在虚拟环境中 +if [ -z "$VIRTUAL_ENV" ] && [ -z "$CONDA_PREFIX" ]; then + echo "警告: 未检测到激活的虚拟环境" + echo "请先激活环境后再运行此脚本" + read -p "是否继续? (y/n) " -n 1 -r + echo + if [[ ! $REPLY =~ ^[Yy]$ ]]; then + exit 1 + fi +fi + +# 安装 clipself +if [ -d "$PROJECT_ROOT/clipself" ]; then + echo "[1/3] 安装 clipself..." + pip install -e "$PROJECT_ROOT/clipself" +else + echo "[1/3] 跳过 clipself (目录不存在)" +fi + +# 安装 segment_anything +if [ -d "$PROJECT_ROOT/segment_anything" ]; then + echo "[2/3] 安装 segment_anything..." + pip install -e "$PROJECT_ROOT/segment_anything" +else + echo "[2/3] 跳过 segment_anything (目录不存在)" +fi + +# 安装 imagecorruptions +if [ -d "$PROJECT_ROOT/imagecorruptions" ]; then + echo "[3/3] 安装 imagecorruptions..." + pip install -e "$PROJECT_ROOT/imagecorruptions" +else + echo "[3/3] 跳过 imagecorruptions (目录不存在)" +fi + +echo "" +echo "本地包安装完成!" +echo "" +echo "验证安装:" +python -c " +try: + import open_clip + print(' ✓ open_clip (clipself)') +except ImportError: + print(' ✗ open_clip (clipself)') + +try: + from segment_anything import sam_model_registry + print(' ✓ segment_anything') +except ImportError: + print(' ✗ segment_anything') + +try: + import imagecorruptions + print(' ✓ imagecorruptions') +except ImportError: + print(' ✗ imagecorruptions') +" diff --git a/downstream/ProxyCLIP_TPAMI/env_setup/push_to_github.sh b/downstream/ProxyCLIP_TPAMI/env_setup/push_to_github.sh new file mode 100644 index 0000000000000000000000000000000000000000..4080b752ad7313fcaf9d34b37693a8cce08d9a3b --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/env_setup/push_to_github.sh @@ -0,0 +1,67 @@ +#!/bin/bash +# ===================================================== +# 推送到 GitHub 脚本 +# ===================================================== +# 使用方法: +# 1. 确保代理已启动 (http://127.0.0.1:7897) +# 2. 确保已在 GitHub 创建私有仓库: xiaomoguhz/ProxyCLIP_TPAMI +# 3. 运行: ./push_to_github.sh +# ===================================================== + +set -e + +PROJECT_ROOT="$( cd "$( dirname "${BASH_SOURCE[0]}" )/.." && pwd )" +cd "$PROJECT_ROOT" + +# 代理配置 +PROXY="http://127.0.0.1:7897" + +# GitHub 仓库 +REPO_URL="https://github.com/xiaomoguhz/ProxyCLIP_TPAMI.git" + +echo "==============================================" +echo "📤 推送到 GitHub" +echo "==============================================" +echo "项目目录: $PROJECT_ROOT" +echo "远程仓库: $REPO_URL" +echo "代理: $PROXY" +echo "" + +# 检查代理 +echo "🔍 检查代理..." +if curl -s --connect-timeout 5 -x "$PROXY" https://github.com > /dev/null 2>&1; then + echo "✅ 代理可用" +else + echo "⚠️ 代理可能不可用,尝试直接连接..." + PROXY="" +fi + +# 配置 git 代理 +if [ -n "$PROXY" ]; then + git config http.proxy "$PROXY" + git config https.proxy "$PROXY" + echo "✅ 已配置 git 代理" +else + git config --unset http.proxy 2>/dev/null || true + git config --unset https.proxy 2>/dev/null || true + echo "⚠️ 未使用代理" +fi + +# 检查远程仓库 +if ! git remote | grep -q origin; then + git remote add origin "$REPO_URL" + echo "✅ 已添加远程仓库" +else + echo "✅ 远程仓库已配置" +fi + +# 推送 +echo "" +echo "📤 推送中..." +git push -u origin main + +echo "" +echo "==============================================" +echo "✅ 推送完成!" +echo "==============================================" +echo "仓库地址: $REPO_URL" diff --git a/downstream/ProxyCLIP_TPAMI/env_setup/pyproject.toml b/downstream/ProxyCLIP_TPAMI/env_setup/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..bf5c7af0588d9cfc74101d622674ea86c36dfacf --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/env_setup/pyproject.toml @@ -0,0 +1,76 @@ +[project] +name = "proxyclip-tpami" +version = "1.0.0" +description = "ProxyCLIP TPAMI - Open-Vocabulary Semantic Segmentation with CLIP" +readme = "../README.md" +requires-python = ">=3.9,<3.12" + +dependencies = [ + # ============== PyTorch 核心 ============== + # 注意: PyTorch 需要根据目标机器的 CUDA 版本单独安装 + # 这里不包含 torch/torchvision/torchaudio,需要在 setup 脚本中单独处理 + + # ============== MMSeg 生态系统 ============== + "mmcv==2.1.0", + "mmengine==0.10.4", + "mmsegmentation==1.2.2", + + # ============== CLIP & 视觉模型核心 ============== + "ftfy>=6.1.0", + "regex>=2024.0.0", + "timm>=1.0.0", + "einops>=0.8.0", + "sentencepiece>=0.2.0", + "protobuf>=3.20.0,<4.0.0", + "huggingface-hub>=0.20.0", + + # ============== 图像处理 ============== + "Pillow>=9.4.0", + "opencv-python>=4.8.0", + "numpy>=1.24.0,<2.0.0", + "scipy>=1.10.0", + "scikit-image>=0.18.0", + + # ============== 数据处理与工具 ============== + "tqdm>=4.65.0", + "PyYAML>=6.0", + "openpyxl>=3.1.0", + "pandas>=2.0.0", + "addict>=2.4.0", + "yapf>=0.40.0", + + # ============== 鲁棒性评估 ============== + # imagecorruptions 本地安装 + + # ============== 其他工具 ============== + "termcolor>=2.0.0", + "terminaltables>=3.1.0", + "rich>=13.0.0", +] + +[project.optional-dependencies] +dev = [ + "pytest>=7.0.0", + "black>=24.0.0", + "ruff>=0.1.0", +] + +training = [ + "tensorboard>=2.15.0", + "tensorboardX>=2.6.0", + "pytorch-lightning>=2.0.0", + "accelerate>=1.0.0", +] + +[build-system] +requires = ["hatchling"] +build-backend = "hatchling.build" + +[tool.uv] +# UV 特定配置 +dev-dependencies = [ + "pytest>=7.0.0", +] + +[tool.uv.sources] +# 如果需要从特定源安装包,可以在这里配置 diff --git a/downstream/ProxyCLIP_TPAMI/env_setup/requirements.txt b/downstream/ProxyCLIP_TPAMI/env_setup/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..0b7b4dec125c7de028981bf41c6b23381a5929a4 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/env_setup/requirements.txt @@ -0,0 +1,43 @@ +# ===================================================== +# ProxyCLIP TPAMI - 核心依赖 +# ===================================================== +# 使用方法: +# 1. 先安装 PyTorch (根据 CUDA 版本) +# 2. pip install -r requirements.txt +# 3. 安装本地包 (clipself, segment_anything, imagecorruptions) +# ===================================================== + +# ============== MMSeg 生态系统 ============== +mmcv==2.1.0 +mmengine==0.10.4 +mmsegmentation==1.2.2 + +# ============== CLIP & 视觉模型核心 ============== +ftfy>=6.1.0 +regex>=2024.0.0 +timm>=1.0.0 +einops>=0.8.0 +sentencepiece>=0.2.0 +protobuf>=3.20.0,<4.0.0 +huggingface-hub>=0.20.0 + +# ============== 图像处理 ============== +Pillow>=9.4.0 +opencv-python>=4.8.0 +numpy>=1.24.0,<2.0.0 +scipy>=1.10.0 +scikit-image>=0.18.0 + +# ============== 数据处理与工具 ============== +tqdm>=4.65.0 +PyYAML>=6.0 +openpyxl>=3.1.0 +pandas>=2.0.0 +addict>=2.4.0 +yapf>=0.40.0 + +# ============== 其他工具 ============== +termcolor>=2.0.0 +terminaltables>=3.1.0 +rich>=13.0.0 +pycocotools>=2.0.7 diff --git a/downstream/ProxyCLIP_TPAMI/env_setup/setup_env.sh b/downstream/ProxyCLIP_TPAMI/env_setup/setup_env.sh new file mode 100644 index 0000000000000000000000000000000000000000..8e7d2e89bee9998d8133ab97615edfce57c9210e --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/env_setup/setup_env.sh @@ -0,0 +1,209 @@ +#!/bin/bash +# ===================================================== +# ProxyCLIP TPAMI - 一键环境配置脚本 +# ===================================================== +# 使用方法: +# chmod +x setup_env.sh +# ./setup_env.sh [--cuda-version 11.8|12.1|12.4] [--env-name proxyclip_tpami] +# ===================================================== + +set -e # 遇到错误立即退出 + +# 默认参数 +CUDA_VERSION="11.8" +ENV_NAME="proxyclip_tpami" +PYTHON_VERSION="3.10" +USE_UV=true + +# 解析命令行参数 +while [[ $# -gt 0 ]]; do + case $1 in + --cuda-version) + CUDA_VERSION="$2" + shift 2 + ;; + --env-name) + ENV_NAME="$2" + shift 2 + ;; + --python-version) + PYTHON_VERSION="$2" + shift 2 + ;; + --no-uv) + USE_UV=false + shift + ;; + -h|--help) + echo "Usage: ./setup_env.sh [OPTIONS]" + echo "" + echo "Options:" + echo " --cuda-version CUDA version (11.8, 12.1, 12.4). Default: 11.8" + echo " --env-name Environment name. Default: proxyclip_tpami" + echo " --python-version Python version. Default: 3.10" + echo " --no-uv Use pip instead of uv" + echo " -h, --help Show this help message" + exit 0 + ;; + *) + echo "Unknown option: $1" + exit 1 + ;; + esac +done + +# 获取脚本所在目录和项目根目录 +SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" +PROJECT_ROOT="$( cd "$SCRIPT_DIR/.." && pwd )" + +echo "==============================================" +echo "ProxyCLIP TPAMI 环境配置" +echo "==============================================" +echo "CUDA 版本: $CUDA_VERSION" +echo "环境名称: $ENV_NAME" +echo "Python 版本: $PYTHON_VERSION" +echo "项目根目录: $PROJECT_ROOT" +echo "==============================================" + +# Step 1: 检查并安装 uv (如果选择使用 uv) +if $USE_UV; then + if ! command -v uv &> /dev/null; then + echo "[Step 1] 安装 uv..." + curl -LsSf https://astral.sh/uv/install.sh | sh + export PATH="$HOME/.cargo/bin:$PATH" + else + echo "[Step 1] uv 已安装" + fi +fi + +# Step 2: 创建虚拟环境 +echo "[Step 2] 创建虚拟环境 $ENV_NAME..." +cd "$PROJECT_ROOT" + +if $USE_UV; then + # 使用 uv 创建虚拟环境 + uv venv ".venv_$ENV_NAME" --python "$PYTHON_VERSION" + source ".venv_$ENV_NAME/bin/activate" +else + # 使用 conda 创建环境 + if command -v conda &> /dev/null; then + conda create -n "$ENV_NAME" python="$PYTHON_VERSION" -y + source "$(conda info --base)/etc/profile.d/conda.sh" + conda activate "$ENV_NAME" + else + echo "错误: 未安装 conda,请先安装 conda 或使用 uv" + exit 1 + fi +fi + +# Step 3: 安装 PyTorch +echo "[Step 3] 安装 PyTorch (CUDA $CUDA_VERSION)..." +case $CUDA_VERSION in + "11.8") + if $USE_UV; then + uv pip install torch==2.0.0 torchvision==0.15.1 --index-url https://download.pytorch.org/whl/cu118 + else + pip install torch==2.0.0 torchvision==0.15.1 --index-url https://download.pytorch.org/whl/cu118 + fi + ;; + "12.1") + if $USE_UV; then + uv pip install torch==2.1.0 torchvision==0.16.0 --index-url https://download.pytorch.org/whl/cu121 + else + pip install torch==2.1.0 torchvision==0.16.0 --index-url https://download.pytorch.org/whl/cu121 + fi + ;; + "12.4") + if $USE_UV; then + uv pip install torch==2.4.0 torchvision==0.19.0 --index-url https://download.pytorch.org/whl/cu124 + else + pip install torch==2.4.0 torchvision==0.19.0 --index-url https://download.pytorch.org/whl/cu124 + fi + ;; + *) + echo "不支持的 CUDA 版本: $CUDA_VERSION" + echo "支持的版本: 11.8, 12.1, 12.4" + exit 1 + ;; +esac + +# Step 4: 安装核心依赖 +echo "[Step 4] 安装核心依赖..." +if $USE_UV; then + uv pip install -r "$SCRIPT_DIR/requirements.txt" +else + pip install -r "$SCRIPT_DIR/requirements.txt" +fi + +# Step 5: 安装本地包 +echo "[Step 5] 安装本地包..." + +# 安装 clipself (open_clip 修改版) +if [ -d "$PROJECT_ROOT/clipself" ]; then + echo " - 安装 clipself..." + cd "$PROJECT_ROOT/clipself" + if $USE_UV; then + uv pip install -e . + else + pip install -e . + fi +fi + +# 安装 segment_anything +if [ -d "$PROJECT_ROOT/segment_anything" ]; then + echo " - 安装 segment_anything..." + cd "$PROJECT_ROOT/segment_anything" + if $USE_UV; then + uv pip install -e . + else + pip install -e . + fi +fi + +# 安装 imagecorruptions (鲁棒性测试) +if [ -d "$PROJECT_ROOT/imagecorruptions" ]; then + echo " - 安装 imagecorruptions..." + cd "$PROJECT_ROOT/imagecorruptions" + if $USE_UV; then + uv pip install -e . + else + pip install -e . + fi +fi + +cd "$PROJECT_ROOT" + +# Step 6: 验证安装 +echo "[Step 6] 验证安装..." +python -c " +import torch +import torchvision +import mmcv +import mmseg +import open_clip +print('=' * 50) +print('环境验证成功!') +print('=' * 50) +print(f'PyTorch: {torch.__version__}') +print(f'TorchVision: {torchvision.__version__}') +print(f'CUDA available: {torch.cuda.is_available()}') +if torch.cuda.is_available(): + print(f'CUDA version: {torch.version.cuda}') + print(f'GPU: {torch.cuda.get_device_name(0)}') +print(f'MMCV: {mmcv.__version__}') +print(f'MMSeg: {mmseg.__version__}') +print('=' * 50) +" + +echo "" +echo "==============================================" +echo "环境配置完成!" +echo "==============================================" +if $USE_UV; then + echo "激活环境: source .venv_$ENV_NAME/bin/activate" +else + echo "激活环境: conda activate $ENV_NAME" +fi +echo "" +echo "运行测试: python eval.py --config configs/proxyclip/cfg_ade20k.py" +echo "==============================================" diff --git a/downstream/ProxyCLIP_TPAMI/env_setup/update_paths.py b/downstream/ProxyCLIP_TPAMI/env_setup/update_paths.py new file mode 100644 index 0000000000000000000000000000000000000000..0e9aabe856d5fe5542cfdaf563c45058ec3518b4 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/env_setup/update_paths.py @@ -0,0 +1,155 @@ +#!/usr/bin/env python3 +""" +批量更新配置文件中的路径 +===================================================== +使用方法: + python update_paths.py --dataset-root /new/dataset/path --checkpoint-root /new/checkpoint/path +===================================================== +""" + +import os +import re +import argparse +from pathlib import Path + + +# 旧路径模式 +OLD_PATTERNS = { + "dataset": [ + r"/mnt/SSD8T/home/wjj/dataset", + ], + "checkpoint": [ + r"/mnt/SSD8T/home/wjj/code/DeCLIP_private/checkpoints", + r"/mnt/SSD8T/home/wjj/code/DeCLIP_private/logs", + r"/mnt/SSD8T/home/wjj/code/DeCLIP/logs", + r"/mnt/SSD8T/home/wjj/code/DeCLIP/backup_bin/logs", + r"/mnt/SSD8T/home/wjj/code/my_CLIPSelf/logs", + r"/mnt/SSD8T/home/wjj/code/my_CLIPSelf/checkpoints", + ], + "sam": [ + r"/mnt/SSD8T/home/wjj/code/ProxyCLIP/sam_ckpts", + ], + "hub": [ + r"/mnt/SSD8T/home/wjj/.cache/torch/hub", + ], +} + + +def update_file(filepath: Path, replacements: dict, dry_run: bool = False): + """更新单个文件中的路径""" + try: + content = filepath.read_text(encoding='utf-8') + except Exception as e: + print(f" ⚠️ 无法读取文件: {e}") + return False + + original_content = content + changes = [] + + for old_path, new_path in replacements.items(): + if old_path in content: + content = content.replace(old_path, new_path) + changes.append((old_path, new_path)) + + if changes: + print(f"\n📝 {filepath}") + for old, new in changes: + print(f" {old}") + print(f" -> {new}") + + if not dry_run and content != original_content: + try: + filepath.write_text(content, encoding='utf-8') + print(f" ✅ 已更新") + except Exception as e: + print(f" ❌ 写入失败: {e}") + return False + + return True + + +def main(): + parser = argparse.ArgumentParser(description="批量更新配置文件中的路径") + parser.add_argument("--dataset-root", type=str, required=True, help="新的数据集根路径") + parser.add_argument("--checkpoint-root", type=str, required=True, help="新的权重根路径") + parser.add_argument("--sam-root", type=str, help="SAM 权重路径 (默认: checkpoint-root/sam)") + parser.add_argument("--hub-root", type=str, help="torch.hub 缓存路径 (默认: ~/.cache/torch/hub)") + parser.add_argument("--config-dir", type=str, default="../configs", help="配置文件目录") + parser.add_argument("--dry-run", action="store_true", help="仅显示将要修改的内容,不实际修改") + args = parser.parse_args() + + # 处理相对路径 + script_dir = Path(__file__).parent + config_dir = (script_dir / args.config_dir).resolve() + + if not config_dir.exists(): + print(f"❌ 配置目录不存在: {config_dir}") + return + + # 构建替换规则 + dataset_root = Path(args.dataset_root).resolve() + checkpoint_root = Path(args.checkpoint_root).resolve() + sam_root = Path(args.sam_root).resolve() if args.sam_root else checkpoint_root / "sam" + hub_root = Path(args.hub_root).resolve() if args.hub_root else Path.home() / ".cache/torch/hub" + + replacements = {} + + # 数据集路径 + for pattern in OLD_PATTERNS["dataset"]: + replacements[pattern] = str(dataset_root) + + # 权重路径 + for pattern in OLD_PATTERNS["checkpoint"]: + replacements[pattern] = str(checkpoint_root) + + # SAM 路径 + for pattern in OLD_PATTERNS["sam"]: + replacements[pattern] = str(sam_root) + + # torch.hub 路径 + for pattern in OLD_PATTERNS["hub"]: + replacements[pattern] = str(hub_root) + + print("=" * 60) + print("🔧 批量更新配置文件路径") + print("=" * 60) + print(f"\n配置目录: {config_dir}") + print(f"数据集路径: {dataset_root}") + print(f"权重路径: {checkpoint_root}") + print(f"SAM 路径: {sam_root}") + print(f"Hub 缓存: {hub_root}") + + if args.dry_run: + print("\n🔍 [DRY RUN] 仅显示将要修改的内容\n") + + # 查找所有配置文件 + config_files = list(config_dir.rglob("*.py")) + print(f"\n找到 {len(config_files)} 个配置文件") + + # 更新每个文件 + updated_count = 0 + for filepath in config_files: + if update_file(filepath, replacements, dry_run=args.dry_run): + updated_count += 1 + + # 同时更新代码文件中的硬编码路径 + code_files = [ + script_dir.parent / "proxyclip_segmentor.py", + script_dir.parent / "tinyclip_proxy_segmentor.py", + ] + + print(f"\n检查代码文件中的硬编码路径...") + for filepath in code_files: + if filepath.exists(): + update_file(filepath, replacements, dry_run=args.dry_run) + + print("\n" + "=" * 60) + if args.dry_run: + print("🔍 [DRY RUN] 完成预览,未实际修改文件") + else: + print(f"✅ 路径更新完成!") + print("=" * 60) + + +if __name__ == "__main__": + main() diff --git a/downstream/ProxyCLIP_TPAMI/env_setup/upload_to_hf.py b/downstream/ProxyCLIP_TPAMI/env_setup/upload_to_hf.py new file mode 100644 index 0000000000000000000000000000000000000000..78aafca7c6351081c20cc51c70236a8001dff92b --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/env_setup/upload_to_hf.py @@ -0,0 +1,220 @@ +#!/usr/bin/env python3 +""" +上传预训练权重和数据集到 HuggingFace +===================================================== +使用方法: + python upload_to_hf.py --upload-weights # 仅上传权重 + python upload_to_hf.py --upload-datasets # 仅上传数据集 + python upload_to_hf.py --all # 上传全部 +===================================================== +""" + +import os +import argparse +from pathlib import Path + +try: + from huggingface_hub import login, upload_folder, upload_file, HfApi +except ImportError: + print("请先安装 huggingface_hub: pip install huggingface_hub") + exit(1) + +# HuggingFace 仓库配置 +WEIGHTS_REPO = "xiaomoguhzz/xiaomogu_pami" +DATASET_REPO = "xiaomoguhzz/xiaomogu_pami_dataset" + +# 权重文件路径配置 +WEIGHTS_CONFIG = { + # SAM 权重 + "sam": { + "source": "/mnt/SSD8T/home/wjj/code/ProxyCLIP_TPAMI/sam_ckpts", + "files": [ + "sam_vit_b_01ec64.pth", + "sam_vit_l_0b3195.pth", + ], + "target_dir": "sam" + }, + # TinyCLIP 原始权重 + "tinyclip_pretrained": { + "source": "/mnt/SSD8T/home/wjj/code/DeCLIP_private/checkpoints", + "files": [ + "TinyCLIP-ViT-39M-16-Text-19M-YFCC15M.pt", + ], + "target_dir": "tinyclip" + }, + # EVA-CLIP DeCLIP 训练权重 + "eva_declip": { + "source": "/mnt/SSD8T/home/wjj/code/DeCLIP/logs/EVA-B_DINOv2-B_csa_560_declip2_0.25_1.0_0.05/checkpoints", + "files": [ + "epoch_6.pt", + ], + "target_dir": "eva_declip" + }, + # TinyCLIP DeCLIP 训练权重 + "tinyclip_declip": { + "source": "/mnt/SSD8T/home/wjj/code/DeCLIP_private/logs/TinyCLIP_39M_DeCLIP+_dinov2B_csa_560_0.25_1.0_0.05_alpha0.4/checkpoints", + "files": [ + "epoch_6.pt", + ], + "target_dir": "tinyclip_declip" + }, +} + +# 数据集路径配置 +DATASETS_CONFIG = { + "ade20k": { + "source": "/mnt/SSD8T/home/wjj/dataset/ADEChallengeData2016", + "target_dir": "ADEChallengeData2016", + "description": "ADE20K Dataset" + }, + "cityscapes": { + "source": "/mnt/SSD8T/home/wjj/dataset/cityscapes", + "target_dir": "cityscapes", + "description": "Cityscapes Dataset" + }, + "coco_stuff": { + "source": "/mnt/SSD8T/home/wjj/dataset/standard_coco", + "target_dir": "standard_coco", + "description": "COCO-Stuff 164K Dataset" + }, + "coco_obj": { + "source": "/mnt/SSD8T/home/wjj/dataset/coco_obj", + "target_dir": "coco_obj", + "description": "COCO-Object Dataset" + }, + "voc2012": { + "source": "/mnt/SSD8T/home/wjj/dataset/VOCdevkit/VOC2012", + "target_dir": "VOCdevkit/VOC2012", + "description": "PASCAL VOC 2012" + }, + "voc2010": { + "source": "/mnt/SSD8T/home/wjj/dataset/VOCdevkit/VOC2010", + "target_dir": "VOCdevkit/VOC2010", + "description": "PASCAL Context (VOC2010)" + }, +} + + +def upload_weights(api: HfApi, dry_run: bool = False): + """上传预训练权重到 HuggingFace""" + print("\n" + "=" * 60) + print("📦 上传预训练权重到:", WEIGHTS_REPO) + print("=" * 60) + + for name, config in WEIGHTS_CONFIG.items(): + source_dir = Path(config["source"]) + target_dir = config["target_dir"] + + print(f"\n[{name}]") + print(f" 源路径: {source_dir}") + print(f" 目标目录: {target_dir}") + + if not source_dir.exists(): + print(f" ⚠️ 源路径不存在,跳过") + continue + + for filename in config["files"]: + source_file = source_dir / filename + if source_file.exists(): + target_path = f"{target_dir}/{filename}" + print(f" 📤 上传: {filename} -> {target_path}") + + if not dry_run: + try: + api.upload_file( + path_or_fileobj=str(source_file), + path_in_repo=target_path, + repo_id=WEIGHTS_REPO, + repo_type="model", + ) + print(f" ✅ 完成: {filename}") + except Exception as e: + print(f" ❌ 失败: {e}") + else: + print(f" ⚠️ 文件不存在: {filename}") + + +def upload_datasets(api: HfApi, dry_run: bool = False): + """上传数据集到 HuggingFace""" + print("\n" + "=" * 60) + print("📊 上传数据集到:", DATASET_REPO) + print("=" * 60) + print("\n⚠️ 注意: 数据集通常很大,上传可能需要很长时间") + print("⚠️ 建议: 仅上传验证集,或使用官方下载链接\n") + + for name, config in DATASETS_CONFIG.items(): + source_dir = Path(config["source"]) + target_dir = config["target_dir"] + + print(f"\n[{name}] - {config['description']}") + print(f" 源路径: {source_dir}") + print(f" 目标目录: {target_dir}") + + if not source_dir.exists(): + print(f" ⚠️ 源路径不存在,跳过") + continue + + # 计算目录大小 + total_size = sum(f.stat().st_size for f in source_dir.rglob('*') if f.is_file()) + size_gb = total_size / (1024**3) + print(f" 📊 总大小: {size_gb:.2f} GB") + + if not dry_run: + confirm = input(f" 是否上传 {name}? (y/n): ").strip().lower() + if confirm != 'y': + print(f" 跳过 {name}") + continue + + try: + print(f" 📤 开始上传...") + api.upload_folder( + folder_path=str(source_dir), + path_in_repo=target_dir, + repo_id=DATASET_REPO, + repo_type="dataset", + ) + print(f" ✅ 完成: {name}") + except Exception as e: + print(f" ❌ 失败: {e}") + + +def main(): + parser = argparse.ArgumentParser(description="上传权重和数据集到 HuggingFace") + parser.add_argument("--upload-weights", action="store_true", help="上传预训练权重") + parser.add_argument("--upload-datasets", action="store_true", help="上传数据集") + parser.add_argument("--all", action="store_true", help="上传全部") + parser.add_argument("--dry-run", action="store_true", help="仅显示将要上传的内容,不实际上传") + parser.add_argument("--token", type=str, help="HuggingFace token (可选)") + args = parser.parse_args() + + if not (args.upload_weights or args.upload_datasets or args.all): + parser.print_help() + print("\n请指定要上传的内容: --upload-weights, --upload-datasets, 或 --all") + return + + api = None + + if args.dry_run: + print("\n🔍 [DRY RUN] 仅显示将要上传的内容\n") + else: + # 登录 HuggingFace + print("🔐 登录 HuggingFace...") + if args.token: + login(token=args.token) + else: + login() + api = HfApi() + + if args.upload_weights or args.all: + upload_weights(api, dry_run=args.dry_run) + + if args.upload_datasets or args.all: + upload_datasets(api, dry_run=args.dry_run) + + print("\n" + "=" * 60) + print("✅ 操作完成!") + print("=" * 60) + + +if __name__ == "__main__": + main() diff --git a/downstream/ProxyCLIP_TPAMI/imagecorruptions/.gitignore b/downstream/ProxyCLIP_TPAMI/imagecorruptions/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..0e43c8540409df244607a87a31fd6925c18e47bf --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/imagecorruptions/.gitignore @@ -0,0 +1,9 @@ +build/* +*egg-info/ +*.egg-info/* +dist/* +*__pycache__* +*.ipynb_checkpoints* +*.pyc +.vscode +.venv diff --git a/downstream/ProxyCLIP_TPAMI/imagecorruptions/CHANGELOG b/downstream/ProxyCLIP_TPAMI/imagecorruptions/CHANGELOG new file mode 100644 index 0000000000000000000000000000000000000000..2222a06141aa683c401f47602e63434745854c1e --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/imagecorruptions/CHANGELOG @@ -0,0 +1,9 @@ +# Changes in Version 1.1.0: +- docstring updated +- validation of arguments that are passed to corrupt() +- bugfix: motion_blur now works on small images + +# Changes in Version 1.0.0: +- all corruption functions accept images with arbitrary dimensions and aspect ratios +- corruption functions that convert the image to a byte-object will now also work for grayscale images +- reimplemented motion_blur and snow corruptions to remove the libmagickwand dependency diff --git a/downstream/ProxyCLIP_TPAMI/imagecorruptions/LICENSE b/downstream/ProxyCLIP_TPAMI/imagecorruptions/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..29f81d812f3e768fa89638d1f72920dbfd1413a8 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/imagecorruptions/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/downstream/ProxyCLIP_TPAMI/imagecorruptions/MANIFEST.in b/downstream/ProxyCLIP_TPAMI/imagecorruptions/MANIFEST.in new file mode 100644 index 0000000000000000000000000000000000000000..68942ee3f1cf4cbf2db8cec8feb362cdf536cefc --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/imagecorruptions/MANIFEST.in @@ -0,0 +1,2 @@ +include imagecorruptions/frost/*.png +include imagecorruptions/frost/*.jpg diff --git a/downstream/ProxyCLIP_TPAMI/imagecorruptions/README.md b/downstream/ProxyCLIP_TPAMI/imagecorruptions/README.md new file mode 100644 index 0000000000000000000000000000000000000000..a66df9e3fd75792f93fd8f51b5b0d6a71df67d0a --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/imagecorruptions/README.md @@ -0,0 +1,85 @@ +# imagecorruptions +This package provides a set of corruptions that can be applied to images in order to benchmark the robustness of neural networks. These corruptions are not meant to be used as training data augmentation but rather to test the networks against unseen perturbations. For more information have a look at the paper on the original corruption package by Hendrycks and Dietterich: [Benchmarking Neural Network Robustness to Common Corruptions and Surface Variations](https://arxiv.org/abs/1807.01697). + +![image corruptions](https://raw.githubusercontent.com/bethgelab/imagecorruptions/master/assets/corruptions_sev_3.png) + +## Installation and Usage +This package is pip installable via `pip3 install imagecorruptions`. An example of how to use the corruption function is given below: +```python +from imagecorruptions import corrupt +... +corrupted_image = corrupt(image, corruption_name='gaussian_blur', severity=1) +... +``` +Looping over all available corruptions can be done either by name or by index: +```python +# via name +from imagecorruptions import get_corruption_names +for corruption in get_corruption_names(): + for severity in range(5): + corrupted = corrupt(image, corruption_name=corruption, severity=severity+1) + ... + +# via number: +for i in range(15): + for severity in range(5): + corrupted = corrupt(image, corruption_number=i, severity=severity+1) + ... +``` + +Note that the first 15 image corruptions are the common corruptions (the ones you get via `get_corruption_names()`). If you really wish to use these as data augmentation, there exist four additional validation corruptions which can be accessed via `get_corruption_names('validation')` which should then be used to test the corruption robustness of the trained model. + +## Apply Image Corruption to a Batch of Images +A script `corrupt_images.py` helps to apply any kind of corruption to a given folder of images. The original folder structure is maintained. +Here is how you can use the script: +``` +usage: corrupt_images.py [-h] [-su {common,validation,all,noise,blur,weather,digital}] + [-c {gaussian_noise,shot_noise,impulse_noise,defocus_blur,glass_blur,motion_blur,zoom_blur,snow,frost,fog,brightness,contrast,elastic_transform,pixelate,jpeg_compression,speckle_noise,gaussian_blur,spatter,saturate} [{gaussian_noise,shot_noise,impulse_noise,defocus_blur,glass_blur,motion_blur,zoom_blur,snow,frost,fog,brightness,contrast,elastic_transform,pixelate,jpeg_compression,speckle_noise,gaussian_blur,spatter,saturate} ...]] + [-se [{1,2,3,4} ...]] [-j J] [-n N] + in_path out_path {subdirs,filename} + +positional arguments: + in_path Directory which has to be processed + out_path Output folder + {subdirs,filename} How should the output be organized + +optional arguments: + -h, --help show this help message and exit + -su {common,validation,all,noise,blur,weather,digital}, --subset {common,validation,all,noise,blur,weather,digital} + Which subsets of corruptions should be applied + -c {gaussian_noise,shot_noise,impulse_noise,defocus_blur,glass_blur,motion_blur,zoom_blur,snow,frost,fog,brightness,contrast,elastic_transform,pixelate,jpeg_compression,speckle_noise,gaussian_blur,spatter,saturate} [{gaussian_noise,shot_noise,impulse_noise,defocus_blur,glass_blur,motion_blur,zoom_blur,snow,frost,fog,brightness,contrast,elastic_transform,pixelate,jpeg_compression,speckle_noise,gaussian_blur,spatter,saturate} ...], --corruptions {gaussian_noise,shot_noise,impulse_noise,defocus_blur,glass_blur,motion_blur,zoom_blur,snow,frost,fog,brightness,contrast,elastic_transform,pixelate,jpeg_compression,speckle_noise,gaussian_blur,spatter,saturate} [{gaussian_noise,shot_noise,impulse_noise,defocus_blur,glass_blur,motion_blur,zoom_blur,snow,frost,fog,brightness,contrast,elastic_transform,pixelate,jpeg_compression,speckle_noise,gaussian_blur,spatter,saturate} ...] + Kind of corruptions to be applied, can be mixed with subset + -se [{1,2,3,4} ...], --severity [{1,2,3,4} ...] + Severity level of corruption, if not provided all 5 levels will be applied + -j J Multiprocessing, default is 1 core + -n N Limit the number of input images to be corrupted + +``` +Positional arguments are input and output folder, along with either `subdirs` or `filename` to tell the script how to organize the output files. Either each corrupted file is placed in subfolders (e.g. `$INPUT_DIR/dir1/image1.png` becomes `$OUTPUT_DIR/dir1/brightness/1/image1.png`) or the filename is altered (e.g. `$INPUT_DIR/dir1/image1.png` becomes `$OUTPUT_DIR/dir1/image1_brightness_1.png`) + +Optimal arguments: +- `-su` Which subsets of corruptions should be applied. One of: common,validation,all,noise,blur,weather,digital +- `-c` Which corruptions should be applied, can be list and can be mixed with subset +- `-se` Severity level of corruption (1-5), if not provided all 5 levels will be applied +- `-j` Number of cores for multiprocessing, default is 1 core +- `-n` Limit the number of input images to be corrupted + + +## Citation + +If you use our code or the imagecorruptions package, please consider citing: +``` +@article{michaelis2019dragon, + title={Benchmarking Robustness in Object Detection: + Autonomous Driving when Winter is Coming}, + author={Michaelis, Claudio and Mitzkus, Benjamin and + Geirhos, Robert and Rusak, Evgenia and + Bringmann, Oliver and Ecker, Alexander S. and + Bethge, Matthias and Brendel, Wieland}, + journal={arXiv preprint arXiv:1907.07484}, + year={2019} +} +``` + +## Credit and Changelog +This package is an extension of the image corruption functions provided by Dan Hendrycks in the repository [corruptions](https://github.com/hendrycks/robustness); please consider citing it. The image corruptions implemented by Hendrycks are generalized to work on images with arbitrary image dimensions and aspect ratios aswell as on grayscale images. We furthermore removed the dependency to `libmagickwand` and the python api `Wand` and reimplemented `motion_blur` in python. diff --git a/downstream/ProxyCLIP_TPAMI/imagecorruptions/corrupt_images.py b/downstream/ProxyCLIP_TPAMI/imagecorruptions/corrupt_images.py new file mode 100644 index 0000000000000000000000000000000000000000..34cc6a623d53db955e2eb40477af7b2160f3d5fe --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/imagecorruptions/corrupt_images.py @@ -0,0 +1,152 @@ +import os +import glob +import argparse +import filetype +import matplotlib.pyplot as plt +import numpy as np + +from imagecorruptions import corrupt +from imagecorruptions import get_corruption_names +from imagecorruptions import corruption_dict +from tqdm import tqdm +from multiprocessing import Pool +from enum import Enum + +# Example call: +# python corrupt_images.py test_images out_images filename -j 10 -c fog snow -su digital -se 1 2 -n 20 +# corrupts all images in test_images and puts the results in out_images +# corruption type will be added to the filename +# corruption happens on 10 cores in parallel +# fog, snow and all digital corruptions are applied +# with severity level 1 and 2 +# and on a total of 20 images + + +class OutputType(Enum): + """How should the generated files be arranged + """ + SUBDIRS = 'subdirs' + FILENAME = 'filename' + + def __str__(self) -> str: + return self.value + + +# https://github.com/scikit-image/scikit-image/issues/4294 +def corrupt_image(image_path: str, image_path_base: str, + output_directory: str, output_type: OutputType, + corruptions: list, severity_levels: list) -> bool: + """Apply image corruption to all images in a given folder + + Args: + image_path (str): Path to an image + input_path_base (str): Base path of input folder, needed to keep directory structure + output_directory (str): Output folder + output_type (OutputType): How should the files be arranged, in + subfolders for each corruption and severity level or should + the corruption type be added to the filename + corruptions (list): which corruptions should be applied + severity_levels (list): List of severity levels + + Returns: + bool: If succeeded or failed + """ + kind = filetype.guess(image_path) + if not kind.mime.startswith('image'): + # Skip inputs that are not images... + return False + + if kind.extension == 'png': + # matplotlib reads png in float format -> convert to uint8 + img_array = plt.imread(image_path) * 255 + img_array = img_array.astype(dtype=np.uint8) + else: + # other image formats are already read as uint8 + img_array = plt.imread(image_path) + + output_path_stub = os.path.relpath(os.path.dirname(image_path), image_path_base) + + for corruption in corruptions: # get_corruption_names(subset=subset): + for severity in severity_levels: + if output_type == OutputType.SUBDIRS: + # Build output_path with subdirectories for each corruption type + # and severity, e.g., $OUT_DIR/$ORIGINAL_STRUCTURE/snow/1/image.jpg + output_path = os.path.join(output_directory, output_path_stub, corruption, + str(severity), os.path.basename(image_path)) + + elif output_type == OutputType.FILENAME: + # Put corruption type and severity into filename, e.g., $OUT_DIR/$ORIGINAL_STRUCTURE/image_snow_1.jpg + fname, ext = os.path.splitext(os.path.basename(image_path)) + fn = "{}_{}_{}{}".format(fname, corruption, str(severity), ext) + output_path = os.path.join(output_directory, output_path_stub, fn) + + else: + raise ValueError("output_type unsupported") + + out_dir = os.path.dirname(output_path) + if not os.path.exists(out_dir): + os.makedirs(out_dir) + + # Apply corruptions + corrupted = corrupt(img_array, corruption_name=corruption, severity=severity) + + plt.imsave(output_path, corrupted) + + return True + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + + parser.add_argument("in_path", help="Directory which has to be processed") + parser.add_argument("out_path", help="Output folder") + parser.add_argument("output_type", choices=list(OutputType), type=OutputType, + help="How should the output be organized") + parser.add_argument("-su", "--subset", choices=['common', 'validation', 'all', 'noise', 'blur', + 'weather', 'digital'], help="Which subsets of corruptions should be applied") + parser.add_argument("-c", "--corruptions", type=str, choices=corruption_dict.keys(), nargs="+", + help="Kind of corruptions to be applied, can be mixed with subset") + parser.add_argument("-se", "--severity", type=int, choices=range(1, 5), nargs="*", + help="Severity level of corruption, if not provided all 5 levels will be applied") + parser.add_argument("-j", type=int, default=1, + help="Multiprocessing, default is 1 core") + parser.add_argument("-n", type=int, help="Limit the number of input images to be corrupted") + + opt = parser.parse_args() + + # make severity a list + severity_levels = list(range(1, 6)) if opt.severity is None else opt.severity + + # Get the total number of images to be corrupted, mainly for progress bar + total = opt.n if opt.n is not None else sum([len(files) for r, d, files in os.walk(opt.in_path)]) + + corruptions = opt.corruptions if opt.corruptions else [] + if opt.subset: + corruptions.extend(get_corruption_names(opt.subset)) + corruptions = list(set(corruptions)) # remove duplicates + assert len(corruptions) > 1, ValueError("No corruption types were provided") + + # Spawn multiprocessing pool + pool = Pool(opt.j) + progress_bar = tqdm(total=total, ascii=True) + + def update_bar(*args): + progress_bar.update() + + i = 0 + for filename in glob.glob(os.path.join(opt.in_path, "**"), recursive=True): + i += 1 + # skip directories + if os.path.isdir(filename): + continue + + pool.apply_async(corrupt_image, + args=[filename, opt.in_path, opt.out_path, opt.output_type, opt.corruptions, severity_levels], + callback=update_bar) + + # break when n is reached + if opt.n and i > opt.n: + break + + pool.close() + pool.join() diff --git a/downstream/ProxyCLIP_TPAMI/imagecorruptions/imagecorruptions/__init__.py b/downstream/ProxyCLIP_TPAMI/imagecorruptions/imagecorruptions/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7c9ac1f55f6e9d07add16143eade48a6f6718bb1 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/imagecorruptions/imagecorruptions/__init__.py @@ -0,0 +1,88 @@ +import numpy as np +from PIL import Image +from .corruptions import * + +corruption_tuple = (gaussian_noise, shot_noise, impulse_noise, defocus_blur, + glass_blur, motion_blur, zoom_blur, snow, frost, fog, + brightness, contrast, elastic_transform, pixelate, + jpeg_compression, speckle_noise, gaussian_blur, spatter, + saturate) + +corruption_dict = {corr_func.__name__: corr_func for corr_func in + corruption_tuple} + + +def corrupt(image, severity=1, corruption_name=None, corruption_number=-1): + """This function returns a corrupted version of the given image. + + Args: + image (numpy.ndarray): image to corrupt; a numpy array in [0, 255], expected datatype is np.uint8 + expected shape is either (height x width x channels) or (height x width); + width and height must be at least 32 pixels; + channels must be 1 or 3; + severity (int): strength with which to corrupt the image; an integer in [1, 5] + corruption_name (str): specifies which corruption function to call, must be one of + 'gaussian_noise', 'shot_noise', 'impulse_noise', 'defocus_blur', + 'glass_blur', 'motion_blur', 'zoom_blur', 'snow', 'frost', 'fog', + 'brightness', 'contrast', 'elastic_transform', 'pixelate', 'jpeg_compression', + 'speckle_noise', 'gaussian_blur', 'spatter', 'saturate'; + the last four are validation corruptions + corruption_number (int): the position of the corruption_name in the above list; an integer in [0, 18]; + useful for easy looping; 15, 16, 17, 18 are validation corruption numbers + Returns: + numpy.ndarray: the image corrupted by a corruption function at the given severity; same shape as input + """ + + if not isinstance(image, np.ndarray): + raise AttributeError('Expecting type(image) to be numpy.ndarray') + if not (image.dtype.type is np.uint8): + raise AttributeError('Expecting image.dtype.type to be numpy.uint8') + + if not (image.ndim in [2,3]): + raise AttributeError('Expecting image.shape to be either (height x width) or (height x width x channels)') + if image.ndim == 2: + image = np.stack((image,)*3, axis=-1) + + height, width, channels = image.shape + + if (height < 32 or width < 32): + raise AttributeError('Image width and height must be at least 32 pixels') + + if not (channels in [1, 3]): + raise AttributeError('Expecting image to have either 1 or 3 channels (last dimension)') + + if channels == 1: + image = np.stack((np.squeeze(image),)*3, axis=-1) + + if severity not in [1, 2, 3, 4, 5]: + raise AttributeError('Severity must be an integer in [1, 5]') + + if not (corruption_name is None): + image_corrupted = corruption_dict[corruption_name](Image.fromarray(image), + severity) + elif corruption_number != -1: + image_corrupted = corruption_tuple[corruption_number](Image.fromarray(image), + severity) + else: + raise ValueError("Either corruption_name or corruption_number must be passed") + + return np.uint8(image_corrupted) + + +def get_corruption_names(subset='common'): + if subset == 'common': + return [f.__name__ for f in corruption_tuple[:15]] + elif subset == 'validation': + return [f.__name__ for f in corruption_tuple[15:]] + elif subset == 'all': + return [f.__name__ for f in corruption_tuple] + elif subset == 'noise': + return [f.__name__ for f in corruption_tuple[0:3]] + elif subset == 'blur': + return [f.__name__ for f in corruption_tuple[3:7]] + elif subset == 'weather': + return [f.__name__ for f in corruption_tuple[7:11]] + elif subset == 'digital': + return [f.__name__ for f in corruption_tuple[11:15]] + else: + raise ValueError("subset must be one of ['common', 'validation', 'noise', 'blur', 'weather', 'digital', 'all']") diff --git a/downstream/ProxyCLIP_TPAMI/imagecorruptions/imagecorruptions/corruptions.py b/downstream/ProxyCLIP_TPAMI/imagecorruptions/imagecorruptions/corruptions.py new file mode 100644 index 0000000000000000000000000000000000000000..c9e8d382eaf4c71eebfc2f80096f21d991a6c46c --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/imagecorruptions/imagecorruptions/corruptions.py @@ -0,0 +1,583 @@ +# -*- coding: utf-8 -*- + +import numpy as np +import math +from PIL import Image + +# /////////////// Corruption Helpers /////////////// + +import skimage as sk +from skimage.filters import gaussian +from io import BytesIO +import cv2 +from scipy.ndimage import zoom as scizoom +from scipy.ndimage.interpolation import map_coordinates +from pkg_resources import resource_filename +from numba import njit + + +def disk(radius, alias_blur=0.1, dtype=np.float32): + if radius <= 8: + L = np.arange(-8, 8 + 1) + ksize = (3, 3) + else: + L = np.arange(-radius, radius + 1) + ksize = (5, 5) + X, Y = np.meshgrid(L, L) + aliased_disk = np.array((X ** 2 + Y ** 2) <= radius ** 2, dtype=dtype) + aliased_disk /= np.sum(aliased_disk) + + # supersample disk to antialias + return cv2.GaussianBlur(aliased_disk, ksize=ksize, sigmaX=alias_blur) + + +# modification of https://github.com/FLHerne/mapgen/blob/master/diamondsquare.py +def plasma_fractal(mapsize=256, wibbledecay=3): + """ + Generate a heightmap using diamond-square algorithm. + Return square 2d array, side length 'mapsize', of floats in range 0-255. + 'mapsize' must be a power of two. + """ + assert (mapsize & (mapsize - 1) == 0) + maparray = np.empty((mapsize, mapsize), dtype=np.float32) + maparray[0, 0] = 0 + stepsize = mapsize + wibble = 100 + + def wibbledmean(array): + return array / 4 + wibble * np.random.uniform(-wibble, wibble, + array.shape) + + def fillsquares(): + """For each square of points stepsize apart, + calculate middle value as mean of points + wibble""" + cornerref = maparray[0:mapsize:stepsize, 0:mapsize:stepsize] + squareaccum = cornerref + np.roll(cornerref, shift=-1, axis=0) + squareaccum += np.roll(squareaccum, shift=-1, axis=1) + maparray[stepsize // 2:mapsize:stepsize, + stepsize // 2:mapsize:stepsize] = wibbledmean(squareaccum) + + def filldiamonds(): + """For each diamond of points stepsize apart, + calculate middle value as mean of points + wibble""" + mapsize = maparray.shape[0] + drgrid = maparray[stepsize // 2:mapsize:stepsize, + stepsize // 2:mapsize:stepsize] + ulgrid = maparray[0:mapsize:stepsize, 0:mapsize:stepsize] + ldrsum = drgrid + np.roll(drgrid, 1, axis=0) + lulsum = ulgrid + np.roll(ulgrid, -1, axis=1) + ltsum = ldrsum + lulsum + maparray[0:mapsize:stepsize, + stepsize // 2:mapsize:stepsize] = wibbledmean(ltsum) + tdrsum = drgrid + np.roll(drgrid, 1, axis=1) + tulsum = ulgrid + np.roll(ulgrid, -1, axis=0) + ttsum = tdrsum + tulsum + maparray[stepsize // 2:mapsize:stepsize, + 0:mapsize:stepsize] = wibbledmean(ttsum) + + while stepsize >= 2: + fillsquares() + filldiamonds() + stepsize //= 2 + wibble /= wibbledecay + + maparray -= maparray.min() + return maparray / maparray.max() + + +def clipped_zoom(img, zoom_factor): + # clipping along the width dimension: + ch0 = int(np.ceil(img.shape[0] / float(zoom_factor))) + top0 = (img.shape[0] - ch0) // 2 + + # clipping along the height dimension: + ch1 = int(np.ceil(img.shape[1] / float(zoom_factor))) + top1 = (img.shape[1] - ch1) // 2 + + img = scizoom(img[top0:top0 + ch0, top1:top1 + ch1], + (zoom_factor, zoom_factor, 1), order=1) + + return img + + +def getOptimalKernelWidth1D(radius, sigma): + return radius * 2 + 1 + + +def gauss_function(x, mean, sigma): + return (np.exp(- (x - mean)**2 / (2 * (sigma**2)))) / (np.sqrt(2 * np.pi) * sigma) + + +def getMotionBlurKernel(width, sigma): + k = gauss_function(np.arange(width), 0, sigma) + Z = np.sum(k) + return k/Z + + +def shift(image, dx, dy): + if (dx < 0): + shifted = np.roll(image, shift=image.shape[1]+dx, axis=1) + shifted[:, dx:] = shifted[:, dx-1:dx] + elif (dx > 0): + shifted = np.roll(image, shift=dx, axis=1) + shifted[:, :dx] = shifted[:, dx:dx+1] + else: + shifted = image + + if (dy < 0): + shifted = np.roll(shifted, shift=image.shape[0]+dy, axis=0) + shifted[dy:, :] = shifted[dy-1:dy, :] + elif (dy > 0): + shifted = np.roll(shifted, shift=dy, axis=0) + shifted[:dy, :] = shifted[dy:dy+1, :] + return shifted + + +def _motion_blur(x, radius, sigma, angle): + width = getOptimalKernelWidth1D(radius, sigma) + kernel = getMotionBlurKernel(width, sigma) + point = (width * np.sin(np.deg2rad(angle)), width * np.cos(np.deg2rad(angle))) + hypot = math.hypot(point[0], point[1]) + + blurred = np.zeros_like(x, dtype=np.float32) + for i in range(width): + dy = -math.ceil(((i*point[0]) / hypot) - 0.5) + dx = -math.ceil(((i*point[1]) / hypot) - 0.5) + if (np.abs(dy) >= x.shape[0] or np.abs(dx) >= x.shape[1]): + # simulated motion exceeded image borders + break + shifted = shift(x, dx, dy) + blurred = blurred + kernel[i] * shifted + return blurred + +# Numba nopython compilation to shuffle_pixles + + +@njit() +def _shuffle_pixels_njit_glass_blur(d0, d1, x, c): + + # locally shuffle pixels + for i in range(c[2]): + for h in range(d0 - c[1], c[1], -1): + for w in range(d1 - c[1], c[1], -1): + dx, dy = np.random.randint(-c[1], c[1], size=(2,)) + h_prime, w_prime = h + dy, w + dx + # swap + x[h, w], x[h_prime, w_prime] = x[h_prime, w_prime], x[h, w] + return x + +# /////////////// End Corruption Helpers /////////////// + + +# /////////////// Corruptions /////////////// + +def gaussian_noise(x, severity=1): + c = [.08, .12, 0.18, 0.26, 0.38][severity - 1] + + x = np.array(x) / 255. + return np.clip(x + np.random.normal(size=x.shape, scale=c), 0, 1) * 255 + + +def shot_noise(x, severity=1): + c = [60, 25, 12, 5, 3][severity - 1] + + x = np.array(x) / 255. + return np.clip(np.random.poisson(x * c) / float(c), 0, 1) * 255 + + +def impulse_noise(x, severity=1): + c = [.03, .06, .09, 0.17, 0.27][severity - 1] + + x = sk.util.random_noise(np.array(x) / 255., mode='s&p', amount=c) + return np.clip(x, 0, 1) * 255 + + +def speckle_noise(x, severity=1): + c = [.15, .2, 0.35, 0.45, 0.6][severity - 1] + + x = np.array(x) / 255. + return np.clip(x + x * np.random.normal(size=x.shape, scale=c), 0, 1) * 255 + + +def gaussian_blur(x, severity=1): + c = [1, 2, 3, 4, 6][severity - 1] + + x = gaussian(np.array(x) / 255., sigma=c, channel_axis=-1) + return np.clip(x, 0, 1) * 255 + + +def glass_blur(x, severity=1): + # sigma, max_delta, iterations + c = [(0.7, 1, 2), (0.9, 2, 1), (1, 2, 3), (1.1, 3, 2), (1.5, 4, 2)][ + severity - 1] + + x = np.uint8( + gaussian(np.array(x) / 255., sigma=c[0], channel_axis=-1) * 255) + + x = _shuffle_pixels_njit_glass_blur(np.array(x).shape[0], np.array(x).shape[1], x, c) + + return np.clip(gaussian(x / 255., sigma=c[0], channel_axis=-1), 0, + 1) * 255 + + +def defocus_blur(x, severity=1): + c = [(3, 0.1), (4, 0.5), (6, 0.5), (8, 0.5), (10, 0.5)][severity - 1] + + x = np.array(x) / 255. + kernel = disk(radius=c[0], alias_blur=c[1]) + + channels = [] + if len(x.shape) < 3 or x.shape[2] < 3: + channels = np.array(cv2.filter2D(x, -1, kernel)) + else: + for d in range(3): + channels.append(cv2.filter2D(x[:, :, d], -1, kernel)) + channels = np.array(channels).transpose((1, 2, 0)) + + return np.clip(channels, 0, 1) * 255 + + +def motion_blur(x, severity=1): + shape = np.array(x).shape + c = [(10, 3), (15, 5), (15, 8), (15, 12), (20, 15)][severity - 1] + x = np.array(x) + + angle = np.random.uniform(-45, 45) + x = _motion_blur(x, radius=c[0], sigma=c[1], angle=angle) + + if len(x.shape) < 3 or x.shape[2] < 3: + gray = np.clip(np.array(x).transpose((0, 1)), 0, 255) + if len(shape) >= 3 or shape[2] >= 3: + return np.stack([gray, gray, gray], axis=2) + else: + return gray + else: + return np.clip(x, 0, 255) + + +def zoom_blur(x, severity=1): + c = [np.arange(1, 1.11, 0.01), + np.arange(1, 1.16, 0.01), + np.arange(1, 1.21, 0.02), + np.arange(1, 1.26, 0.02), + np.arange(1, 1.31, 0.03)][severity - 1] + + x = (np.array(x) / 255.).astype(np.float32) + out = np.zeros_like(x) + + set_exception = False + for zoom_factor in c: + if len(x.shape) < 3 or x.shape[2] < 3: + x_channels = np.array([x, x, x]).transpose((1, 2, 0)) + zoom_layer = clipped_zoom(x_channels, zoom_factor) + zoom_layer = zoom_layer[:x.shape[0], :x.shape[1], 0] + else: + zoom_layer = clipped_zoom(x, zoom_factor) + zoom_layer = zoom_layer[:x.shape[0], :x.shape[1], :] + + try: + out += zoom_layer + except ValueError: + set_exception = True + out[:zoom_layer.shape[0], :zoom_layer.shape[1]] += zoom_layer + + if set_exception: + print('ValueError for zoom blur, Exception handling') + x = (x + out) / (len(c) + 1) + return np.clip(x, 0, 1) * 255 + + +def next_power_of_2(x): + return 1 if x == 0 else 2 ** (x - 1).bit_length() + + +def fog(x, severity=1): + c = [(1.5, 2), (2., 2), (2.5, 1.7), (2.5, 1.5), (3., 1.4)][severity - 1] + + shape = np.array(x).shape + max_side = np.max(shape) + map_size = next_power_of_2(int(max_side)) + + x = np.array(x) / 255. + max_val = x.max() + + x_shape = np.array(x).shape + if len(x_shape) < 3 or x_shape[2] < 3: + x += c[0] * plasma_fractal(mapsize=map_size, wibbledecay=c[1])[ + :shape[0], :shape[1]] + else: + x += c[0] * \ + plasma_fractal(mapsize=map_size, wibbledecay=c[1])[:shape[0], + :shape[1]][..., np.newaxis] + return np.clip(x * max_val / (max_val + c[0]), 0, 1) * 255 + + +def frost(x, severity=1): + c = [(1, 0.4), + (0.8, 0.6), + (0.7, 0.7), + (0.65, 0.7), + (0.6, 0.75)][severity - 1] + + idx = np.random.randint(5) + filename = [resource_filename(__name__, './frost/frost1.png'), + resource_filename(__name__, './frost/frost2.png'), + resource_filename(__name__, './frost/frost3.png'), + resource_filename(__name__, './frost/frost4.jpg'), + resource_filename(__name__, './frost/frost5.jpg'), + resource_filename(__name__, './frost/frost6.jpg')][idx] + frost = cv2.imread(filename) + frost_shape = frost.shape + x_shape = np.array(x).shape + + # resize the frost image so it fits to the image dimensions + scaling_factor = 1 + if frost_shape[0] >= x_shape[0] and frost_shape[1] >= x_shape[1]: + scaling_factor = 1 + elif frost_shape[0] < x_shape[0] and frost_shape[1] >= x_shape[1]: + scaling_factor = x_shape[0] / frost_shape[0] + elif frost_shape[0] >= x_shape[0] and frost_shape[1] < x_shape[1]: + scaling_factor = x_shape[1] / frost_shape[1] + elif frost_shape[0] < x_shape[0] and frost_shape[1] < x_shape[ + 1]: # If both dims are too small, pick the bigger scaling factor + scaling_factor_0 = x_shape[0] / frost_shape[0] + scaling_factor_1 = x_shape[1] / frost_shape[1] + scaling_factor = np.maximum(scaling_factor_0, scaling_factor_1) + + scaling_factor *= 1.1 + new_shape = (int(np.ceil(frost_shape[1] * scaling_factor)), + int(np.ceil(frost_shape[0] * scaling_factor))) + frost_rescaled = cv2.resize(frost, dsize=new_shape, + interpolation=cv2.INTER_CUBIC) + + # randomly crop + x_start, y_start = np.random.randint(0, frost_rescaled.shape[0] - x_shape[ + 0]), np.random.randint(0, frost_rescaled.shape[1] - x_shape[1]) + + if len(x_shape) < 3 or x_shape[2] < 3: + frost_rescaled = frost_rescaled[x_start:x_start + x_shape[0], + y_start:y_start + x_shape[1]] + frost_rescaled = rgb2gray(frost_rescaled) + else: + frost_rescaled = frost_rescaled[x_start:x_start + x_shape[0], + y_start:y_start + x_shape[1]][..., [2, 1, 0]] + return np.clip(c[0] * np.array(x) + c[1] * frost_rescaled, 0, 255) + + +def rgb2gray(rgb): + return np.dot(rgb[..., :3], [0.2989, 0.5870, 0.1140]) + + +def snow(x, severity=1): + c = [(0.1, 0.3, 3, 0.5, 10, 4, 0.8), + (0.2, 0.3, 2, 0.5, 12, 4, 0.7), + (0.55, 0.3, 4, 0.9, 12, 8, 0.7), + (0.55, 0.3, 4.5, 0.85, 12, 8, 0.65), + (0.55, 0.3, 2.5, 0.85, 12, 12, 0.55)][severity - 1] + + x = np.array(x, dtype=np.float32) / 255. + snow_layer = np.random.normal(size=x.shape[:2], loc=c[0], + scale=c[1]) # [:2] for monochrome + + snow_layer = clipped_zoom(snow_layer[..., np.newaxis], c[2]) + snow_layer[snow_layer < c[3]] = 0 + + snow_layer = np.clip(snow_layer.squeeze(), 0, 1) + + snow_layer = _motion_blur(snow_layer, radius=c[4], sigma=c[5], angle=np.random.uniform(-135, -45)) + + # The snow layer is rounded and cropped to the img dims + snow_layer = np.round(snow_layer * 255).astype(np.uint8) / 255. + snow_layer = snow_layer[..., np.newaxis] + snow_layer = snow_layer[:x.shape[0], :x.shape[1], :] + + if len(x.shape) < 3 or x.shape[2] < 3: + x = c[6] * x + (1 - c[6]) * np.maximum(x, x.reshape(x.shape[0], + x.shape[ + 1]) * 1.5 + 0.5) + snow_layer = snow_layer.squeeze(-1) + else: + x = c[6] * x + (1 - c[6]) * np.maximum(x, cv2.cvtColor(x, + cv2.COLOR_RGB2GRAY).reshape( + x.shape[0], x.shape[1], 1) * 1.5 + 0.5) + try: + return np.clip(x + snow_layer + np.rot90(snow_layer, k=2), 0, 1) * 255 + except ValueError: + print('ValueError for Snow, Exception handling') + x[:snow_layer.shape[0], :snow_layer.shape[1]] += snow_layer + np.rot90( + snow_layer, k=2) + return np.clip(x, 0, 1) * 255 + + +def spatter(x, severity=1): + c = [(0.65, 0.3, 4, 0.69, 0.6, 0), + (0.65, 0.3, 3, 0.68, 0.6, 0), + (0.65, 0.3, 2, 0.68, 0.5, 0), + (0.65, 0.3, 1, 0.65, 1.5, 1), + (0.67, 0.4, 1, 0.65, 1.5, 1)][severity - 1] + x_PIL = x + x = np.array(x, dtype=np.float32) / 255. + + liquid_layer = np.random.normal(size=x.shape[:2], loc=c[0], scale=c[1]) + + liquid_layer = gaussian(liquid_layer, sigma=c[2]) + liquid_layer[liquid_layer < c[3]] = 0 + if c[5] == 0: + liquid_layer = (liquid_layer * 255).astype(np.uint8) + dist = 255 - cv2.Canny(liquid_layer, 50, 150) + dist = cv2.distanceTransform(dist, cv2.DIST_L2, 5) + _, dist = cv2.threshold(dist, 20, 20, cv2.THRESH_TRUNC) + dist = cv2.blur(dist, (3, 3)).astype(np.uint8) + dist = cv2.equalizeHist(dist) + ker = np.array([[-2, -1, 0], [-1, 1, 1], [0, 1, 2]]) + dist = cv2.filter2D(dist, cv2.CV_8U, ker) + dist = cv2.blur(dist, (3, 3)).astype(np.float32) + + m = cv2.cvtColor(liquid_layer * dist, cv2.COLOR_GRAY2BGRA) + m /= np.max(m, axis=(0, 1)) + m *= c[4] + # water is pale turqouise + color = np.concatenate((175 / 255. * np.ones_like(m[..., :1]), + 238 / 255. * np.ones_like(m[..., :1]), + 238 / 255. * np.ones_like(m[..., :1])), axis=2) + + color = cv2.cvtColor(color, cv2.COLOR_BGR2BGRA) + + if len(x.shape) < 3 or x.shape[2] < 3: + add_spatter_color = cv2.cvtColor(np.clip(m * color, 0, 1), + cv2.COLOR_BGRA2BGR) + add_spatter_gray = rgb2gray(add_spatter_color) + + return np.clip(x + add_spatter_gray, 0, 1) * 255 + + else: + + x = cv2.cvtColor(x, cv2.COLOR_BGR2BGRA) + + return cv2.cvtColor(np.clip(x + m * color, 0, 1), + cv2.COLOR_BGRA2BGR) * 255 + else: + m = np.where(liquid_layer > c[3], 1, 0) + m = gaussian(m.astype(np.float32), sigma=c[4]) + m[m < 0.8] = 0 + + x_rgb = np.array(x_PIL.convert('RGB')) + + # mud brown + color = np.concatenate((63 / 255. * np.ones_like(x_rgb[..., :1]), + 42 / 255. * np.ones_like(x_rgb[..., :1]), + 20 / 255. * np.ones_like(x_rgb[..., :1])), + axis=2) + color *= m[..., np.newaxis] + if len(x.shape) < 3 or x.shape[2] < 3: + x *= (1 - m) + return np.clip(x + rgb2gray(color), 0, 1) * 255 + + else: + x *= (1 - m[..., np.newaxis]) + return np.clip(x + color, 0, 1) * 255 + + +def contrast(x, severity=1): + c = [0.4, .3, .2, .1, .05][severity - 1] + + x = np.array(x) / 255. + means = np.mean(x, axis=(0, 1), keepdims=True) + return np.clip((x - means) * c + means, 0, 1) * 255 + + +def brightness(x, severity=1): + c = [.1, .2, .3, .4, .5][severity - 1] + + x = np.array(x) / 255. + + if len(x.shape) < 3 or x.shape[2] < 3: + x = np.clip(x + c, 0, 1) + else: + x = sk.color.rgb2hsv(x) + x[:, :, 2] = np.clip(x[:, :, 2] + c, 0, 1) + x = sk.color.hsv2rgb(x) + + return np.clip(x, 0, 1) * 255 + + +def saturate(x, severity=1): + c = [(0.3, 0), (0.1, 0), (2, 0), (5, 0.1), (20, 0.2)][severity - 1] + + x = np.array(x) / 255. + + gray_scale = False + if len(x.shape) < 3 or x.shape[2] < 3: + x = np.array([x, x, x]).transpose((1, 2, 0)) + gray_scale = True + x = sk.color.rgb2hsv(x) + x[:, :, 1] = np.clip(x[:, :, 1] * c[0] + c[1], 0, 1) + x = sk.color.hsv2rgb(x) + if gray_scale: + x = x[:, :, 0] + + return np.clip(x, 0, 1) * 255 + + +def jpeg_compression(x, severity=1): + c = [25, 18, 15, 10, 7][severity - 1] + + output = BytesIO() + gray_scale = False + if x.mode != 'RGB': + gray_scale = True + x = x.convert('RGB') + x.save(output, 'JPEG', quality=c) + x = Image.open(output) + if gray_scale: + x = x.convert('L') + + return x + + +def pixelate(x, severity=1): + c = [0.6, 0.5, 0.4, 0.3, 0.25][severity - 1] + + x_shape = np.array(x).shape + + x = x.resize((int(x_shape[1] * c), int(x_shape[0] * c)), Image.BOX) + + x = x.resize((x_shape[1], x_shape[0]), Image.NEAREST) + + return x + + +# mod of https://gist.github.com/erniejunior/601cdf56d2b424757de5 +def elastic_transform(image, severity=1): + image = np.array(image, dtype=np.float32) / 255. + shape = image.shape + shape_size = shape[:2] + + sigma = np.array(shape_size) * 0.01 + alpha = [250 * 0.05, 250 * 0.065, 250 * 0.085, 250 * 0.1, 250 * 0.12][ + severity - 1] + max_dx = shape[0] * 0.005 + max_dy = shape[0] * 0.005 + + dx = (gaussian(np.random.uniform(-max_dx, max_dx, size=shape[:2]), + sigma, mode='reflect', truncate=3) * alpha).astype( + np.float32) + dy = (gaussian(np.random.uniform(-max_dy, max_dy, size=shape[:2]), + sigma, mode='reflect', truncate=3) * alpha).astype( + np.float32) + + if len(image.shape) < 3 or image.shape[2] < 3: + x, y = np.meshgrid(np.arange(shape[1]), np.arange(shape[0])) + indices = np.reshape(y + dy, (-1, 1)), np.reshape(x + dx, (-1, 1)) + else: + dx, dy = dx[..., np.newaxis], dy[..., np.newaxis] + x, y, z = np.meshgrid(np.arange(shape[1]), np.arange(shape[0]), + np.arange(shape[2])) + indices = np.reshape(y + dy, (-1, 1)), np.reshape(x + dx, + (-1, 1)), np.reshape( + z, (-1, 1)) + return np.clip( + map_coordinates(image, indices, order=1, mode='reflect').reshape( + shape), 0, 1) * 255 + +# /////////////// End Corruptions /////////////// diff --git a/downstream/ProxyCLIP_TPAMI/imagecorruptions/requirements.txt b/downstream/ProxyCLIP_TPAMI/imagecorruptions/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..0a00384ffc093771833f9549d211af79abb19dd8 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/imagecorruptions/requirements.txt @@ -0,0 +1,9 @@ +numpy >= 1.16 +Pillow >= 5.4.1 +scikit-image >= 0.15 +opencv-python >= 3.4.5 +scipy >= 1.2.1 +numba >= 0.53.0 +tqdm >= 4.0.0 +matplotlib >= 3.6.0 +filetype >= 1.1.0 \ No newline at end of file diff --git a/downstream/ProxyCLIP_TPAMI/imagecorruptions/setup.py b/downstream/ProxyCLIP_TPAMI/imagecorruptions/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..9fe273033e5e29c4977e6a6095e6fa28334dbf4f --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/imagecorruptions/setup.py @@ -0,0 +1,35 @@ +import setuptools + +with open("README.md", "r") as fh: + long_description = fh.read() + +# Can be used to load install_require +# with open('requirements.txt', 'r') as freq: +# required = freq.read().splitlines() + + +setuptools.setup( + name="imagecorruptions", + version="1.1.2", + author="Evgenia Rusak, Benjamin Mitzkus", + author_email="evgenia.rusak@bethgelab.org, benjamin.mitzkus@bethgelab.org", + description="This package provides a set of image corruptions.", + long_description=long_description, + long_description_content_type="text/markdown", + url="https://github.com/bethgelab/imagecorruptions", + packages=setuptools.find_packages(), + install_requires=[ + 'numpy >= 1.16', + 'Pillow >= 5.4.1', + 'scikit-image >= 0.15', + 'opencv-python >= 3.4.5', + 'scipy >= 1.2.1', + 'numba >= 0.53.0' + ], + include_package_data=True, + classifiers=[ + "Programming Language :: Python :: 3", + "License :: OSI Approved :: Apache Software License", + "Operating System :: OS Independent", + ], +) diff --git a/downstream/ProxyCLIP_TPAMI/imagecorruptions/test_demo.py b/downstream/ProxyCLIP_TPAMI/imagecorruptions/test_demo.py new file mode 100644 index 0000000000000000000000000000000000000000..df342591166cffa671347b2e7a43ef43d967f2b2 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/imagecorruptions/test_demo.py @@ -0,0 +1,17 @@ +from imagecorruptions import corrupt, get_corruption_names +from PIL import Image +import numpy as np +import matplotlib.pyplot as plt +import time +image = np.asarray(Image.open('test_image.jpg')) +#image = np.ones((427, 640, 3), dtype=np.uint8) + +# corrupted_image = corrupt(img, corruption_name='gaussian_blur', severity=1) + +for corruption in get_corruption_names('blur'): + tic = time.time() + for severity in range(5): + corrupted = corrupt(image, corruption_name=corruption, severity=severity+1) + plt.imshow(corrupted) + plt.show() + print(corruption, time.time() - tic) \ No newline at end of file diff --git a/downstream/ProxyCLIP_TPAMI/prompts/imagenet_template.py b/downstream/ProxyCLIP_TPAMI/prompts/imagenet_template.py new file mode 100644 index 0000000000000000000000000000000000000000..cb7802df3f0bcc0cdf5b5ef9c6aa826bc049f238 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/prompts/imagenet_template.py @@ -0,0 +1,260 @@ + +imagenet_classnames = ["tench", "goldfish", "great white shark", "tiger shark", "hammerhead shark", "electric ray", + "stingray", "rooster", "hen", "ostrich", "brambling", "goldfinch", "house finch", "junco", + "indigo bunting", "American robin", "bulbul", "jay", "magpie", "chickadee", "American dipper", + "kite (bird of prey)", "bald eagle", "vulture", "great grey owl", "fire salamander", + "smooth newt", "newt", "spotted salamander", "axolotl", "American bullfrog", "tree frog", + "tailed frog", "loggerhead sea turtle", "leatherback sea turtle", "mud turtle", "terrapin", + "box turtle", "banded gecko", "green iguana", "Carolina anole", + "desert grassland whiptail lizard", "agama", "frilled-necked lizard", "alligator lizard", + "Gila monster", "European green lizard", "chameleon", "Komodo dragon", "Nile crocodile", + "American alligator", "triceratops", "worm snake", "ring-necked snake", + "eastern hog-nosed snake", "smooth green snake", "kingsnake", "garter snake", "water snake", + "vine snake", "night snake", "boa constrictor", "African rock python", "Indian cobra", + "green mamba", "sea snake", "Saharan horned viper", "eastern diamondback rattlesnake", + "sidewinder rattlesnake", "trilobite", "harvestman", "scorpion", "yellow garden spider", + "barn spider", "European garden spider", "southern black widow", "tarantula", "wolf spider", + "tick", "centipede", "black grouse", "ptarmigan", "ruffed grouse", "prairie grouse", "peafowl", + "quail", "partridge", "african grey parrot", "macaw", "sulphur-crested cockatoo", "lorikeet", + "coucal", "bee eater", "hornbill", "hummingbird", "jacamar", "toucan", "duck", + "red-breasted merganser", "goose", "black swan", "tusker", "echidna", "platypus", "wallaby", + "koala", "wombat", "jellyfish", "sea anemone", "brain coral", "flatworm", "nematode", "conch", + "snail", "slug", "sea slug", "chiton", "chambered nautilus", "Dungeness crab", "rock crab", + "fiddler crab", "red king crab", "American lobster", "spiny lobster", "crayfish", "hermit crab", + "isopod", "white stork", "black stork", "spoonbill", "flamingo", "little blue heron", + "great egret", "bittern bird", "crane bird", "limpkin", "common gallinule", "American coot", + "bustard", "ruddy turnstone", "dunlin", "common redshank", "dowitcher", "oystercatcher", + "pelican", "king penguin", "albatross", "grey whale", "killer whale", "dugong", "sea lion", + "Chihuahua", "Japanese Chin", "Maltese", "Pekingese", "Shih Tzu", "King Charles Spaniel", + "Papillon", "toy terrier", "Rhodesian Ridgeback", "Afghan Hound", "Basset Hound", "Beagle", + "Bloodhound", "Bluetick Coonhound", "Black and Tan Coonhound", "Treeing Walker Coonhound", + "English foxhound", "Redbone Coonhound", "borzoi", "Irish Wolfhound", "Italian Greyhound", + "Whippet", "Ibizan Hound", "Norwegian Elkhound", "Otterhound", "Saluki", "Scottish Deerhound", + "Weimaraner", "Staffordshire Bull Terrier", "American Staffordshire Terrier", + "Bedlington Terrier", "Border Terrier", "Kerry Blue Terrier", "Irish Terrier", + "Norfolk Terrier", "Norwich Terrier", "Yorkshire Terrier", "Wire Fox Terrier", + "Lakeland Terrier", "Sealyham Terrier", "Airedale Terrier", "Cairn Terrier", + "Australian Terrier", "Dandie Dinmont Terrier", "Boston Terrier", "Miniature Schnauzer", + "Giant Schnauzer", "Standard Schnauzer", "Scottish Terrier", "Tibetan Terrier", + "Australian Silky Terrier", "Soft-coated Wheaten Terrier", "West Highland White Terrier", + "Lhasa Apso", "Flat-Coated Retriever", "Curly-coated Retriever", "Golden Retriever", + "Labrador Retriever", "Chesapeake Bay Retriever", "German Shorthaired Pointer", "Vizsla", + "English Setter", "Irish Setter", "Gordon Setter", "Brittany dog", "Clumber Spaniel", + "English Springer Spaniel", "Welsh Springer Spaniel", "Cocker Spaniel", "Sussex Spaniel", + "Irish Water Spaniel", "Kuvasz", "Schipperke", "Groenendael dog", "Malinois", "Briard", + "Australian Kelpie", "Komondor", "Old English Sheepdog", "Shetland Sheepdog", "collie", + "Border Collie", "Bouvier des Flandres dog", "Rottweiler", "German Shepherd Dog", "Dobermann", + "Miniature Pinscher", "Greater Swiss Mountain Dog", "Bernese Mountain Dog", + "Appenzeller Sennenhund", "Entlebucher Sennenhund", "Boxer", "Bullmastiff", "Tibetan Mastiff", + "French Bulldog", "Great Dane", "St. Bernard", "husky", "Alaskan Malamute", "Siberian Husky", + "Dalmatian", "Affenpinscher", "Basenji", "pug", "Leonberger", "Newfoundland dog", + "Great Pyrenees dog", "Samoyed", "Pomeranian", "Chow Chow", "Keeshond", "brussels griffon", + "Pembroke Welsh Corgi", "Cardigan Welsh Corgi", "Toy Poodle", "Miniature Poodle", + "Standard Poodle", "Mexican hairless dog (xoloitzcuintli)", "grey wolf", "Alaskan tundra wolf", + "red wolf or maned wolf", "coyote", "dingo", "dhole", "African wild dog", "hyena", "red fox", + "kit fox", "Arctic fox", "grey fox", "tabby cat", "tiger cat", "Persian cat", "Siamese cat", + "Egyptian Mau", "cougar", "lynx", "leopard", "snow leopard", "jaguar", "lion", "tiger", + "cheetah", "brown bear", "American black bear", "polar bear", "sloth bear", "mongoose", + "meerkat", "tiger beetle", "ladybug", "ground beetle", "longhorn beetle", "leaf beetle", + "dung beetle", "rhinoceros beetle", "weevil", "fly", "bee", "ant", "grasshopper", + "cricket insect", "stick insect", "cockroach", "praying mantis", "cicada", "leafhopper", + "lacewing", "dragonfly", "damselfly", "red admiral butterfly", "ringlet butterfly", + "monarch butterfly", "small white butterfly", "sulphur butterfly", "gossamer-winged butterfly", + "starfish", "sea urchin", "sea cucumber", "cottontail rabbit", "hare", "Angora rabbit", + "hamster", "porcupine", "fox squirrel", "marmot", "beaver", "guinea pig", "common sorrel horse", + "zebra", "pig", "wild boar", "warthog", "hippopotamus", "ox", "water buffalo", "bison", + "ram (adult male sheep)", "bighorn sheep", "Alpine ibex", "hartebeest", "impala (antelope)", + "gazelle", "arabian camel", "llama", "weasel", "mink", "European polecat", + "black-footed ferret", "otter", "skunk", "badger", "armadillo", "three-toed sloth", "orangutan", + "gorilla", "chimpanzee", "gibbon", "siamang", "guenon", "patas monkey", "baboon", "macaque", + "langur", "black-and-white colobus", "proboscis monkey", "marmoset", "white-headed capuchin", + "howler monkey", "titi monkey", "Geoffroy's spider monkey", "common squirrel monkey", + "ring-tailed lemur", "indri", "Asian elephant", "African bush elephant", "red panda", + "giant panda", "snoek fish", "eel", "silver salmon", "rock beauty fish", "clownfish", + "sturgeon", "gar fish", "lionfish", "pufferfish", "abacus", "abaya", "academic gown", + "accordion", "acoustic guitar", "aircraft carrier", "airliner", "airship", "altar", "ambulance", + "amphibious vehicle", "analog clock", "apiary", "apron", "trash can", "assault rifle", + "backpack", "bakery", "balance beam", "balloon", "ballpoint pen", "Band-Aid", "banjo", + "baluster / handrail", "barbell", "barber chair", "barbershop", "barn", "barometer", "barrel", + "wheelbarrow", "baseball", "basketball", "bassinet", "bassoon", "swimming cap", "bath towel", + "bathtub", "station wagon", "lighthouse", "beaker", "military hat (bearskin or shako)", + "beer bottle", "beer glass", "bell tower", "baby bib", "tandem bicycle", "bikini", + "ring binder", "binoculars", "birdhouse", "boathouse", "bobsleigh", "bolo tie", "poke bonnet", + "bookcase", "bookstore", "bottle cap", "hunting bow", "bow tie", "brass memorial plaque", "bra", + "breakwater", "breastplate", "broom", "bucket", "buckle", "bulletproof vest", + "high-speed train", "butcher shop", "taxicab", "cauldron", "candle", "cannon", "canoe", + "can opener", "cardigan", "car mirror", "carousel", "tool kit", "cardboard box / carton", + "car wheel", "automated teller machine", "cassette", "cassette player", "castle", "catamaran", + "CD player", "cello", "mobile phone", "chain", "chain-link fence", "chain mail", "chainsaw", + "storage chest", "chiffonier", "bell or wind chime", "china cabinet", "Christmas stocking", + "church", "movie theater", "cleaver", "cliff dwelling", "cloak", "clogs", "cocktail shaker", + "coffee mug", "coffeemaker", "spiral or coil", "combination lock", "computer keyboard", + "candy store", "container ship", "convertible", "corkscrew", "cornet", "cowboy boot", + "cowboy hat", "cradle", "construction crane", "crash helmet", "crate", "infant bed", + "Crock Pot", "croquet ball", "crutch", "cuirass", "dam", "desk", "desktop computer", + "rotary dial telephone", "diaper", "digital clock", "digital watch", "dining table", + "dishcloth", "dishwasher", "disc brake", "dock", "dog sled", "dome", "doormat", "drilling rig", + "drum", "drumstick", "dumbbell", "Dutch oven", "electric fan", "electric guitar", + "electric locomotive", "entertainment center", "envelope", "espresso machine", "face powder", + "feather boa", "filing cabinet", "fireboat", "fire truck", "fire screen", "flagpole", "flute", + "folding chair", "football helmet", "forklift", "fountain", "fountain pen", "four-poster bed", + "freight car", "French horn", "frying pan", "fur coat", "garbage truck", + "gas mask or respirator", "gas pump", "goblet", "go-kart", "golf ball", "golf cart", "gondola", + "gong", "gown", "grand piano", "greenhouse", "radiator grille", "grocery store", "guillotine", + "hair clip", "hair spray", "half-track", "hammer", "hamper", "hair dryer", "hand-held computer", + "handkerchief", "hard disk drive", "harmonica", "harp", "combine harvester", "hatchet", + "holster", "home theater", "honeycomb", "hook", "hoop skirt", "gymnastic horizontal bar", + "horse-drawn vehicle", "hourglass", "iPod", "clothes iron", "carved pumpkin", "jeans", "jeep", + "T-shirt", "jigsaw puzzle", "rickshaw", "joystick", "kimono", "knee pad", "knot", "lab coat", + "ladle", "lampshade", "laptop computer", "lawn mower", "lens cap", "letter opener", "library", + "lifeboat", "lighter", "limousine", "ocean liner", "lipstick", "slip-on shoe", "lotion", + "music speaker", "loupe magnifying glass", "sawmill", "magnetic compass", "messenger bag", + "mailbox", "tights", "one-piece bathing suit", "manhole cover", "maraca", "marimba", "mask", + "matchstick", "maypole", "maze", "measuring cup", "medicine cabinet", "megalith", "microphone", + "microwave oven", "military uniform", "milk can", "minibus", "miniskirt", "minivan", "missile", + "mitten", "mixing bowl", "mobile home", "ford model t", "modem", "monastery", "monitor", + "moped", "mortar and pestle", "graduation cap", "mosque", "mosquito net", "vespa", + "mountain bike", "tent", "computer mouse", "mousetrap", "moving van", "muzzle", "metal nail", + "neck brace", "necklace", "baby pacifier", "notebook computer", "obelisk", "oboe", "ocarina", + "odometer", "oil filter", "pipe organ", "oscilloscope", "overskirt", "bullock cart", + "oxygen mask", "product packet / packaging", "paddle", "paddle wheel", "padlock", "paintbrush", + "pajamas", "palace", "pan flute", "paper towel", "parachute", "parallel bars", "park bench", + "parking meter", "railroad car", "patio", "payphone", "pedestal", "pencil case", + "pencil sharpener", "perfume", "Petri dish", "photocopier", "plectrum", "Pickelhaube", + "picket fence", "pickup truck", "pier", "piggy bank", "pill bottle", "pillow", "ping-pong ball", + "pinwheel", "pirate ship", "drink pitcher", "block plane", "planetarium", "plastic bag", + "plate rack", "farm plow", "plunger", "Polaroid camera", "pole", "police van", "poncho", + "pool table", "soda bottle", "plant pot", "potter's wheel", "power drill", "prayer rug", + "printer", "prison", "missile", "projector", "hockey puck", "punching bag", "purse", "quill", + "quilt", "race car", "racket", "radiator", "radio", "radio telescope", "rain barrel", + "recreational vehicle", "fishing casting reel", "reflex camera", "refrigerator", + "remote control", "restaurant", "revolver", "rifle", "rocking chair", "rotisserie", "eraser", + "rugby ball", "ruler measuring stick", "sneaker", "safe", "safety pin", "salt shaker", "sandal", + "sarong", "saxophone", "scabbard", "weighing scale", "school bus", "schooner", "scoreboard", + "CRT monitor", "screw", "screwdriver", "seat belt", "sewing machine", "shield", "shoe store", + "shoji screen / room divider", "shopping basket", "shopping cart", "shovel", "shower cap", + "shower curtain", "ski", "balaclava ski mask", "sleeping bag", "slide rule", "sliding door", + "slot machine", "snorkel", "snowmobile", "snowplow", "soap dispenser", "soccer ball", "sock", + "solar thermal collector", "sombrero", "soup bowl", "keyboard space bar", "space heater", + "space shuttle", "spatula", "motorboat", "spider web", "spindle", "sports car", "spotlight", + "stage", "steam locomotive", "through arch bridge", "steel drum", "stethoscope", "scarf", + "stone wall", "stopwatch", "stove", "strainer", "tram", "stretcher", "couch", "stupa", + "submarine", "suit", "sundial", "sunglasses", "sunglasses", "sunscreen", "suspension bridge", + "mop", "sweatshirt", "swim trunks / shorts", "swing", "electrical switch", "syringe", + "table lamp", "tank", "tape player", "teapot", "teddy bear", "television", "tennis ball", + "thatched roof", "front curtain", "thimble", "threshing machine", "throne", "tile roof", + "toaster", "tobacco shop", "toilet seat", "torch", "totem pole", "tow truck", "toy store", + "tractor", "semi-trailer truck", "tray", "trench coat", "tricycle", "trimaran", "tripod", + "triumphal arch", "trolleybus", "trombone", "hot tub", "turnstile", "typewriter keyboard", + "umbrella", "unicycle", "upright piano", "vacuum cleaner", "vase", "vaulted or arched ceiling", + "velvet fabric", "vending machine", "vestment", "viaduct", "violin", "volleyball", + "waffle iron", "wall clock", "wallet", "wardrobe", "military aircraft", "sink", + "washing machine", "water bottle", "water jug", "water tower", "whiskey jug", "whistle", + "hair wig", "window screen", "window shade", "Windsor tie", "wine bottle", "airplane wing", + "wok", "wooden spoon", "wool", "split-rail fence", "shipwreck", "sailboat", "yurt", "website", + "comic book", "crossword", "traffic or street sign", "traffic light", "dust jacket", "menu", + "plate", "guacamole", "consomme", "hot pot", "trifle", "ice cream", "popsicle", "baguette", + "bagel", "pretzel", "cheeseburger", "hot dog", "mashed potatoes", "cabbage", "broccoli", + "cauliflower", "zucchini", "spaghetti squash", "acorn squash", "butternut squash", "cucumber", + "artichoke", "bell pepper", "cardoon", "mushroom", "Granny Smith apple", "strawberry", "orange", + "lemon", "fig", "pineapple", "banana", "jackfruit", "cherimoya (custard apple)", "pomegranate", + "hay", "carbonara", "chocolate syrup", "dough", "meatloaf", "pizza", "pot pie", "burrito", + "red wine", "espresso", "tea cup", "eggnog", "mountain", "bubble", "cliff", "coral reef", + "geyser", "lakeshore", "promontory", "sandbar", "beach", "valley", "volcano", "baseball player", + "bridegroom", "scuba diver", "rapeseed", "daisy", "yellow lady's slipper", "corn", "acorn", + "rose hip", "horse chestnut seed", "coral fungus", "agaric", "gyromitra", "stinkhorn mushroom", + "earth star fungus", "hen of the woods mushroom", "bolete", "corn cob", "toilet paper"] + + +openai_imagenet_template = [ + lambda c: f'a bad photo of a {c}.', + lambda c: f'a photo of many {c}.', + lambda c: f'a sculpture of a {c}.', + lambda c: f'a photo of the hard to see {c}.', + lambda c: f'a low resolution photo of the {c}.', + lambda c: f'a rendering of a {c}.', + lambda c: f'graffiti of a {c}.', + lambda c: f'a bad photo of the {c}.', + lambda c: f'a cropped photo of the {c}.', + lambda c: f'a tattoo of a {c}.', + lambda c: f'the embroidered {c}.', + lambda c: f'a photo of a hard to see {c}.', + lambda c: f'a bright photo of a {c}.', + lambda c: f'a photo of a clean {c}.', + lambda c: f'a photo of a dirty {c}.', + lambda c: f'a dark photo of the {c}.', + lambda c: f'a drawing of a {c}.', + lambda c: f'a photo of my {c}.', + lambda c: f'the plastic {c}.', + lambda c: f'a photo of the cool {c}.', + lambda c: f'a close-up photo of a {c}.', + lambda c: f'a black and white photo of the {c}.', + lambda c: f'a painting of the {c}.', + lambda c: f'a painting of a {c}.', + lambda c: f'a pixelated photo of the {c}.', + lambda c: f'a sculpture of the {c}.', + lambda c: f'a bright photo of the {c}.', + lambda c: f'a cropped photo of a {c}.', + lambda c: f'a plastic {c}.', + lambda c: f'a photo of the dirty {c}.', + lambda c: f'a jpeg corrupted photo of a {c}.', + lambda c: f'a blurry photo of the {c}.', + lambda c: f'a photo of the {c}.', + lambda c: f'a good photo of the {c}.', + lambda c: f'a rendering of the {c}.', + lambda c: f'a {c} in a video game.', + lambda c: f'a photo of one {c}.', + lambda c: f'a doodle of a {c}.', + lambda c: f'a close-up photo of the {c}.', + lambda c: f'a photo of a {c}.', + lambda c: f'the origami {c}.', + lambda c: f'the {c} in a video game.', + lambda c: f'a sketch of a {c}.', + lambda c: f'a doodle of the {c}.', + lambda c: f'a origami {c}.', + lambda c: f'a low resolution photo of a {c}.', + lambda c: f'the toy {c}.', + lambda c: f'a rendition of the {c}.', + lambda c: f'a photo of the clean {c}.', + lambda c: f'a photo of a large {c}.', + lambda c: f'a rendition of a {c}.', + lambda c: f'a photo of a nice {c}.', + lambda c: f'a photo of a weird {c}.', + lambda c: f'a blurry photo of a {c}.', + lambda c: f'a cartoon {c}.', + lambda c: f'art of a {c}.', + lambda c: f'a sketch of the {c}.', + lambda c: f'a embroidered {c}.', + lambda c: f'a pixelated photo of a {c}.', + lambda c: f'itap of the {c}.', + lambda c: f'a jpeg corrupted photo of the {c}.', + lambda c: f'a good photo of a {c}.', + lambda c: f'a plushie {c}.', + lambda c: f'a photo of the nice {c}.', + lambda c: f'a photo of the small {c}.', + lambda c: f'a photo of the weird {c}.', + lambda c: f'the cartoon {c}.', + lambda c: f'art of the {c}.', + lambda c: f'a drawing of the {c}.', + lambda c: f'a photo of the large {c}.', + lambda c: f'a black and white photo of a {c}.', + lambda c: f'the plushie {c}.', + lambda c: f'a dark photo of a {c}.', + lambda c: f'itap of a {c}.', + lambda c: f'graffiti of the {c}.', + lambda c: f'a toy {c}.', + lambda c: f'itap of my {c}.', + lambda c: f'a photo of a cool {c}.', + lambda c: f'a photo of a small {c}.', + lambda c: f'a tattoo of the {c}.', +] + +sub_imagenet_template = [ + lambda c: f'itap of a {c}.', + lambda c: f'a bad photo of a {c}.', + lambda c: f'a origami {c}.', + lambda c: f'a photo of the large {c}.', + lambda c: f'a {c} in a video game.', + lambda c: f'art of the {c}.', + lambda c: f'a photo of the small {c}.', +] \ No newline at end of file diff --git a/downstream/ProxyCLIP_TPAMI/quantization_analysis/DESIGN.md b/downstream/ProxyCLIP_TPAMI/quantization_analysis/DESIGN.md new file mode 100644 index 0000000000000000000000000000000000000000..0915e3cd3ed60e110eafccf13e5ad14254a86934 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/quantization_analysis/DESIGN.md @@ -0,0 +1,315 @@ +# DeCLIP 量化实验设计 + +> 最后更新: 2026-01-11 +> 项目位置: `/mnt/SSD8T/home/wjj/code/ProxyCLIP_TPAMI/quantization_analysis/` +> 训练代码位置: `/mnt/SSD8T/home/wjj/code/DeCLIP_private/` + +--- + +## 🔄 快速重启摘要 + +### 背景 +这是 TPAMI 投稿论文 DeCLIP 的补充实验,用于回应审稿人关于计算效率的意见。 + +### 核心论点 +**DeCLIP 与量化策略正交(Orthogonal)**: +- DeCLIP 是**训练时**的改进(解耦蒸馏) +- **推理时**使用的是标准 CLIP backbone,架构完全一致 +- 因此 DeCLIP 不增加任何推理开销 +- 所有效率优化(INT8 量化等)在 DeCLIP 上同样有效 + +### 已确认配置 +| 配置项 | 值 | +|-------|---| +| 量化方案 | PyTorch Native (动态量化) | +| 模型版本 | EVA-CLIP-B (ViT-B/16) | +| 测试硬件 | NVIDIA RTX 4090 | +| 评估范围 | 效率指标 + mIoU | +| 输入分辨率 | 🔄 待定(根据 mIoU 评测代码确定) | + +### 待补充 +- [ ] mIoU 评测代码上下文(用户会提供) +- [ ] 输入分辨率处理方式 +- [ ] 量化模型如何接入评测流程 + +--- + +## 📋 审稿人原始要求 + +> Address computational efficiency and edge deployment feasibility. While DeCLIP enhances accuracy, it lacks analysis of: +> (1) inference latency/memory (e.g., on NVIDIA Jetson AGX for 1080p images); +> (2) parameter count vs. lightweight baselines (e.g., CLIP-Tiny + decoupled learning); +> (3) optimization strategies (e.g., model quantization, layer pruning). +> +> Quantify latency (≤200ms for 1080p) and memory usage, and propose optimizations to reduce latency by ≥40% while retaining ≥90% accuracy. + +### 我们的回复策略 +补充 INT8 量化实验,证明: +1. DeCLIP **不增加任何推理开销**(延迟、内存、FLOPs 与原始 CLIP 完全一致) +2. DeCLIP + INT8 量化 **仍然优于** CLIP + INT8 量化 +3. 量化带来的效率提升在 DeCLIP 上**同样有效** + +--- + +## 🛠️ 技术方案:PyTorch Native Quantization + +### 为什么选择 PyTorch Native? + +对比了三种方案: + +| 方案 | EVA-CLIP 兼容性 | 说明 | +|-----|----------------|------| +| **bitsandbytes** | ⚠️ 需要调整 | 主要针对 LLM,不是 ViT | +| **PyTorch Native** | ✅ 开箱即用 | 标准 PyTorch 模型完美支持 | +| **HuggingFace Optimum** | ❌ 不兼容 | EVA-CLIP 不在 transformers 库中 | + +**结论**:PyTorch Native 最适合,因为: +- EVA-CLIP 是纯 PyTorch 实现 +- 代码最简单(几行代码) +- 无额外依赖 +- 审稿人容易复现 + +### 量化代码示例 + +```python +import torch +import torch.quantization as quant + +# FP16 量化 +model_fp16 = model.half() + +# INT8 动态量化 +model_int8 = quant.quantize_dynamic( + model.visual, # 只量化视觉编码器 + {torch.nn.Linear}, + dtype=torch.qint8 +) +``` + +### 量化原理 + +``` +量化改变的是:权重/激活的数值精度 +量化不改变的:模型架构、层数、参数数量 + +FP32 → FP16: 模型大小减半,精度损失极小 +FP32 → INT8: 模型大小 1/4,精度损失小 +``` + +--- + +## 📊 实验设计 + +### 实验矩阵 + +``` +┌──────────────────┬────────┬────────┬────────┐ +│ Model │ FP32 │ FP16 │ INT8 │ +├──────────────────┼────────┼────────┼────────┤ +│ CLIP (Vanilla) │ ✓ │ ✓ │ ✓ │ +├──────────────────┼────────┼────────┼────────┤ +│ DeCLIP (Ours) │ ✓ │ ✓ │ ✓ │ +└──────────────────┴────────┴────────┴────────┘ +``` + +### 测量指标 + +| 指标 | 说明 | 单位 | +|-----|------|-----| +| Model Size | 模型文件大小 | MB | +| Latency | 单张图像推理时间 | ms | +| Memory | 推理时内存占用 | MB | +| mIoU | 语义分割精度 | % | + +### 预期结果 + +``` +┌──────────────────┬────────┬────────┬────────┬────────┐ +│ Model │ Size │Latency │ Memory │ mIoU │ +├──────────────────┼────────┼────────┼────────┼────────┤ +│ CLIP-B FP32 │ ~350MB │ Xms │ X MB │ A.A │ +│ CLIP-B FP16 │ ~175MB │ Yms │ Y MB │ A.A │ +│ CLIP-B INT8 │ ~88MB │ Zms │ Z MB │ A.A' │ +├──────────────────┼────────┼────────┼────────┼────────┤ +│ DeCLIP-B FP32 │ ~350MB │ Xms │ X MB │ B.B │ +│ DeCLIP-B FP16 │ ~175MB │ Yms │ Y MB │ B.B │ +│ DeCLIP-B INT8 │ ~88MB │ Zms │ Z MB │ B.B' │ +└──────────────────┴────────┴────────┴────────┴────────┘ + +预期观察: +1. 同精度下 Size/Latency/Memory 完全相同 → 证明零开销 +2. 同精度下 DeCLIP mIoU > CLIP mIoU → 证明精度提升 +3. 量化后 DeCLIP 仍优于 CLIP → 证明正交性 +``` + +--- + +## 📁 相关项目结构 + +### DeCLIP 训练项目 +``` +/mnt/SSD8T/home/wjj/code/DeCLIP_private/ +├── src/ +│ ├── open_clip/eva_clip/ # EVA-CLIP 模型代码 +│ │ ├── factory.py # 模型创建 +│ │ ├── model.py # CLIP/CustomCLIP 类 +│ │ └── eva_vit_model.py # EVAVisionTransformer +│ └── training/ +│ ├── declip.py # DeCLIP 基础版 +│ └── declip_plus.py # DeCLIP+ (带 SD attention) +├── scripts/ # 训练脚本 +└── checkpoints/ # 模型权重 +``` + +### ProxyCLIP 评测项目(当前位置) +``` +/mnt/SSD8T/home/wjj/code/ProxyCLIP_TPAMI/ +├── quantization_analysis/ # 本实验文件夹 +│ └── DESIGN.md # 本文档 +├── declip_segmentor.py # DeCLIP 分割器(评测用) +├── eval.py # 评估脚本 +├── configs/eva_declip/ # DeCLIP 配置 +└── logs/ # 评测日志 +``` + +### EVA-CLIP 模型信息 + +| 模型 | 名称 | Patch Size | 分辨率 | +|-----|------|-----------|-------| +| EVA-CLIP-B | EVA02-CLIP-B-16 | 16 | 224/336/560 | +| EVA-CLIP-L | EVA02-CLIP-L-14-336 | 14 | 336/560 | + +--- + +## 🔧 实现计划 + +### 文件结构(规划) + +``` +quantization_analysis/ +├── DESIGN.md # 本设计文档 +├── PROGRESS.md # 进度记录(待创建) +├── quantize_and_benchmark.py # 量化 + 效率测量脚本(待创建) +├── eval_quantized.py # 量化模型 mIoU 评测(待创建) +└── results/ # 实验结果 + └── benchmark_results.csv +``` + +### Benchmark 代码框架(待实现) + +```python +# quantize_and_benchmark.py + +import torch +import torch.quantization as quant +import time +import os + +def load_model(checkpoint_path, model_name="EVA02-CLIP-B-16"): + """加载 EVA-CLIP 模型""" + # 需要参考 DeCLIP_private 中的模型加载代码 + pass + +def quantize_fp16(model): + """FP16 量化""" + return model.half() + +def quantize_int8(model): + """INT8 动态量化""" + return quant.quantize_dynamic( + model.visual, + {torch.nn.Linear}, + dtype=torch.qint8 + ) + +def measure_model_size(model): + """测量模型大小 (MB)""" + torch.save(model.state_dict(), "temp.pt") + size = os.path.getsize("temp.pt") / (1024 * 1024) + os.remove("temp.pt") + return size + +def measure_latency(model, input_tensor, num_runs=100): + """测量推理延迟 (ms)""" + model.eval() + with torch.no_grad(): + # Warmup + for _ in range(10): + _ = model(input_tensor) + + # Measure + torch.cuda.synchronize() + start = time.time() + for _ in range(num_runs): + _ = model(input_tensor) + torch.cuda.synchronize() + + return (time.time() - start) / num_runs * 1000 + +def measure_memory(model, input_tensor): + """测量显存占用 (MB)""" + torch.cuda.reset_peak_memory_stats() + with torch.no_grad(): + _ = model(input_tensor) + return torch.cuda.max_memory_allocated() / (1024 * 1024) +``` + +--- + +## 📝 论文表述建议 + +``` +We demonstrate that DeCLIP's improvements are orthogonal to model +compression techniques. Since DeCLIP only modifies the training +objective while keeping the inference architecture identical to +vanilla CLIP, all efficiency optimizations (e.g., INT8 quantization) +remain fully applicable. + +Table X shows that DeCLIP maintains its performance advantages +across different precision levels (FP32, FP16, INT8), confirming +that our approach introduces zero additional inference overhead. +``` + +--- + +## ⏳ 待用户补充 + +### 1. mIoU 评测代码上下文 +需要了解: +- `declip_segmentor.py` 的使用方式 +- 评测配置文件 +- 输入图像预处理流程 +- 分辨率如何确定 + +### 2. 模型 Checkpoint 路径 +- Vanilla CLIP-B checkpoint 路径 +- DeCLIP-B checkpoint 路径 + +--- + +## 🚀 下一步 + +1. [x] 确定量化方案 → **PyTorch Native (动态量化)** +2. [x] 确定测试配置 → **EVA-CLIP-B, RTX 4090, 效率+mIoU** +3. [ ] 🔄 等待用户提供 mIoU 评测代码上下文 +4. [ ] 实现量化 + benchmark 脚本 +5. [ ] 实现 mIoU 评测集成 +6. [ ] 运行实验,收集数据 + +--- + +## 💬 重启对话提示 + +如果需要在新对话中继续这个任务,可以使用以下提示: + +``` +我正在进行 DeCLIP 的量化实验,请阅读 +/mnt/SSD8T/home/wjj/code/ProxyCLIP_TPAMI/quantization_analysis/DESIGN.md +了解上下文,然后继续帮我完成实验。 + +当前状态: +- 已确定使用 PyTorch Native 动态量化 +- 模型:EVA-CLIP-B,硬件:RTX 4090 +- 需要测效率指标 + mIoU +- 等待我提供 mIoU 评测代码上下文 +``` diff --git a/downstream/ProxyCLIP_TPAMI/robustness_eval/README.md b/downstream/ProxyCLIP_TPAMI/robustness_eval/README.md new file mode 100644 index 0000000000000000000000000000000000000000..49c86ced06dc8bbe953346afe67b414d674ed233 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/robustness_eval/README.md @@ -0,0 +1,93 @@ +# 鲁棒性评估工具 + +用于评估模型在不同图像退化条件下的性能。 + +## 快速开始 + +### 1. 选择数据集 & 编辑脚本 + +编辑 `robustness_eval/run_eval.sh`,修改以下参数: + +```bash +# 数据集名称(与 robust_datasets.py 中的键一致) +DATASET="cityscapes" # 可选: cityscapes, coco_stuff164k, ade20k, voc20, voc21, context59, context60, coco_object + +# 若想手动指定配置,可填 CONFIG;否则保持空,脚本会根据 DATASET 自动解析 +CONFIG="" + +# 退化类型: common/validation/all/noise/blur/weather/digital +CORRUPTIONS="common" + +# 严重程度 +SEVERITIES="1 2 3 4 5" + +# 指定可用的GPU ID(根据实际情况修改) +GPUS=(0 2 3 4 5 6 7) +``` + +### 2. 运行评估 + +```bash +bash robustness_eval/run_eval.sh +``` + +## 参数说明 + +### GPU配置 +- `GPUS`: 指定可用的GPU ID数组,例如 `(0 2 3 4 5 6 7)` + +### 退化类型 +- `CORRUPTIONS`: 退化类型类别(一次只能选择一个) + - `common`: 常见退化类型(推荐,包含15种) + - `all`: 所有退化类型(75种) + - `validation`: 验证集退化类型 + - `noise`: 噪声类(gaussian_noise, shot_noise, impulse_noise, speckle_noise) + - `blur`: 模糊类(defocus_blur, glass_blur, motion_blur, zoom_blur) + - `weather`: 天气类(snow, frost, fog, brightness) + - `digital`: 数字类(contrast, elastic_transform, pixelate, jpeg_compression) + +### 其他参数 +- `CONFIG`: 配置文件路径 +- `WORK_DIR`: 工作目录(默认: `robustness_eval/results`) +- `SEVERITIES`: 严重程度列表(默认: `1 2 3 4 5`) + +### 数据集预置配置(8个) +- `robustness_eval/robust_datasets.py` 预置 8 个鲁棒性配置(均位于 `robustness_eval/configs/`) + 支持: cityscapes, coco_stuff164k, ade20k, voc20, voc21, context59, context60, coco_object +- 查看支持的数据集: + ```bash + python robustness_eval/robust_datasets.py --list + ``` +- 获取某个数据集的鲁棒性配置路径(示例 cityscapes): + ```bash + CONFIG=$(python robustness_eval/robust_datasets.py --name cityscapes) + ``` + 然后将 `CONFIG` 写入 `run_eval.sh` 中的 CONFIG 变量即可。 + +## 评估流程 + +1. **编辑脚本**: 修改 `run_eval.sh` 中的GPU ID和其他参数 +2. **运行评估**: 执行 `bash robustness_eval/run_eval.sh` +3. **收集结果**: 评估完成后,收集所有结果并生成Excel + +```bash +python robustness_eval/collect_all_results.py --results-dir robustness_eval/results +``` + +结果将保存到 `robustness_eval/results.xlsx` + +## 注意事项 + +- **退化类型**: `CORRUPTIONS` 参数一次只能选择一个预定义的类别(如 `common`、`all`、`noise` 等),不能直接指定多个具体的退化类型名称 +- **GPU选择**: 根据实际可用的GPU修改 `GPUS` 数组,避免使用不可用的GPU +- **评估时间**: 使用 `all` 会评估所有75种退化类型,耗时较长,建议先用 `common` 测试 + +## 文件说明 + +- `run_eval.sh`: 评估启动脚本(推荐使用) +- `run_robustness_eval_multi_gpu.py`: 多GPU并行评估主程序 +- `run_robustness_eval.py`: 单GPU评估主程序 +- `collect_all_results.py`: 收集结果并生成Excel +- `save_results_to_excel.py`: 保存结果到Excel +- `prepare_corrupted_images.py`: 准备退化图片 + diff --git a/downstream/ProxyCLIP_TPAMI/robustness_eval/__init__.py b/downstream/ProxyCLIP_TPAMI/robustness_eval/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..72080f3a9d9b2622c4dd8c570ff028b174ec7ba5 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/robustness_eval/__init__.py @@ -0,0 +1,2 @@ +# Robustness evaluation package for Cityscapes + diff --git a/downstream/ProxyCLIP_TPAMI/robustness_eval/calc_metrics.py b/downstream/ProxyCLIP_TPAMI/robustness_eval/calc_metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..f85b6d132483729b571b847f518fcdd5b0ba4bb0 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/robustness_eval/calc_metrics.py @@ -0,0 +1,134 @@ +#!/usr/bin/env python +""" +根据评估结果计算 P / mPC / rPC 指标。 + +使用方法(在项目根目录执行): + python robustness_eval/calc_metrics.py \ + --results-json robustness_eval/results/results_summary.json \ + --metrics mIoU aAcc mAcc \ + --output robustness_eval/results/metrics.csv + +说明: + - P : clean 基线指标(severity=0) + - mPC : 所有退化 (corruptions) 的平均指标(包含所有严重程度) + - rPC : mPC / P +""" + +import argparse +import csv +import json +from pathlib import Path +from typing import Dict, Any, List, Tuple + +project_root = Path(__file__).parent.parent + + +def load_results_summary(path: Path) -> Dict[str, Any]: + """读取 results_summary.json.""" + if not path.is_absolute(): + path = project_root / path + if not path.exists(): + raise FileNotFoundError(f"未找到结果文件: {path}") + with path.open("r") as f: + return json.load(f) + + +def compute_metrics( + summary: Dict[str, Any], + metric_keys: List[str], +) -> List[Tuple[str, float, float, float]]: + """ + 计算每个指标的 P / mPC / rPC。 + + Args: + summary: results_summary.json 内容 + metric_keys: 需要计算的指标名列表,如 ["mIoU", "aAcc", "mAcc"] + + Returns: + 列表,元素为 (metric, P, mPC, rPC) + """ + results = [] + + # clean 结果 + clean = summary.get("clean", {}) + clean_val = None + if clean: + # clean 的 severity 键可能是 0 或 "0" + clean_key = next(iter(clean)) + if str(clean_key) in clean: + clean_val = clean[str(clean_key)] + else: + clean_val = clean[clean_key] + + for metric in metric_keys: + # P + P = clean_val.get(metric) if clean_val else None + + # 收集所有退化的该指标 + vals = [] + for corr, sev_dict in summary.items(): + if corr == "clean": + continue + for _, res in sev_dict.items(): + if metric in res: + vals.append(res[metric]) + + mPC = sum(vals) / len(vals) if vals else None + rPC = (mPC / P) if (P not in (None, 0) and mPC is not None) else None + results.append((metric, P, mPC, rPC)) + + return results + + +def save_csv(rows: List[Tuple[str, float, float, float]], path: Path): + if not path.is_absolute(): + path = project_root / path + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("w", newline="") as f: + writer = csv.writer(f) + writer.writerow(["Metric", "P(clean)", "mPC(mean corrupt)", "rPC(mPC/P)"]) + for row in rows: + writer.writerow(row) + print(f"指标已保存到: {path}") + + +def parse_args(): + parser = argparse.ArgumentParser(description="计算 P / mPC / rPC 指标") + parser.add_argument( + "--results-json", + type=str, + default="robustness_eval/results/results_summary.json", + help="results_summary.json 路径", + ) + parser.add_argument( + "--metrics", + type=str, + nargs="+", + default=["mIoU", "aAcc", "mAcc"], + help="需要计算的指标列表", + ) + parser.add_argument( + "--output", + type=str, + default="robustness_eval/results/metrics.csv", + help="输出 CSV 路径(默认: robustness_eval/results/metrics.csv)", + ) + return parser.parse_args() + + +def main(): + args = parse_args() + summary = load_results_summary(Path(args.results_json)) + rows = compute_metrics(summary, args.metrics) + + print("指标汇总:") + for metric, P, mPC, rPC in rows: + print(f" {metric}: P={P}, mPC={mPC}, rPC={rPC}") + + if args.output: + save_csv(rows, Path(args.output)) + + +if __name__ == "__main__": + main() + diff --git a/downstream/ProxyCLIP_TPAMI/robustness_eval/collect_all_results.py b/downstream/ProxyCLIP_TPAMI/robustness_eval/collect_all_results.py new file mode 100644 index 0000000000000000000000000000000000000000..33268552cfd3b72b6443dc34136ba20cbec2212b --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/robustness_eval/collect_all_results.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python +""" +从结果目录重新收集所有评估结果 + +当评估被中断时,可以使用此脚本重新收集所有已完成的结果。 +""" + +import os +import sys +import json +from pathlib import Path + +# 添加项目根目录到路径 +project_root = Path(__file__).parent.parent +sys.path.insert(0, str(project_root)) + +from robustness_eval.run_robustness_eval_multi_gpu import load_results +from imagecorruptions import get_corruption_names + + +def collect_all_results(results_dir): + """从目录中收集所有评估结果""" + results_dir = Path(results_dir) + if not results_dir.is_absolute(): + results_dir = project_root / results_dir + + results_summary = {} + + # 收集clean结果 + clean_dir = results_dir / 'clean' + if clean_dir.exists(): + result = load_results(clean_dir) + if result: + results_summary['clean'] = {0: result} + print(f"✓ 收集到 clean 结果") + + # 收集各退化类型的结果 + corruption_names = get_corruption_names('all') + for corruption in corruption_names: + corruption_dir = results_dir / corruption + if not corruption_dir.exists(): + continue + + corruption_results = {} + # 遍历所有严重程度 + for severity_dir in sorted(corruption_dir.iterdir()): + if not severity_dir.is_dir() or not severity_dir.name.startswith('severity_'): + continue + + severity = int(severity_dir.name.split('_')[1]) + result = load_results(severity_dir) + if result: + corruption_results[severity] = result + print(f"✓ 收集到 {corruption}, severity={severity}") + + if corruption_results: + results_summary[corruption] = corruption_results + + return results_summary + + +def main(): + import argparse + parser = argparse.ArgumentParser(description='重新收集所有评估结果') + parser.add_argument( + '--results-dir', + type=str, + default='robustness_eval/results', + help='结果目录路径') + parser.add_argument( + '--output', + type=str, + default=None, + help='输出JSON文件路径(默认:results_dir/results_summary.json)') + args = parser.parse_args() + + # 收集结果 + print("开始收集所有评估结果...") + results_summary = collect_all_results(args.results_dir) + + if not results_summary: + print("警告: 未找到任何评估结果") + return + + # 保存结果 + results_dir = Path(args.results_dir) + if not results_dir.is_absolute(): + results_dir = project_root / results_dir + + if args.output: + output_file = Path(args.output) + if not output_file.is_absolute(): + output_file = project_root / output_file + else: + output_file = results_dir / 'results_summary.json' + + output_file.parent.mkdir(parents=True, exist_ok=True) + with open(output_file, 'w') as f: + json.dump(results_summary, f, indent=2) + + # 统计信息 + total_results = sum(len(results) for results in results_summary.values()) + print(f"\n{'='*80}") + print(f"收集完成") + print(f"{'='*80}") + print(f"退化类型数: {len(results_summary)}") + print(f"总评估数: {total_results}") + print(f"结果已保存到: {output_file}") + print(f"{'='*80}\n") + + # 生成Excel(默认保存到robustness_eval文件夹) + excel_script = project_root / 'robustness_eval' / 'save_results_to_excel.py' + if excel_script.exists(): + excel_output = project_root / 'robustness_eval' / 'results.xlsx' + import subprocess + subprocess.run([ + sys.executable, + str(excel_script), + '--results-json', str(output_file), + '--output', str(excel_output), + ]) + print(f"Excel结果已保存到: {excel_output}") + + +if __name__ == '__main__': + main() + diff --git a/downstream/ProxyCLIP_TPAMI/robustness_eval/configs/cfg_ade20k_robust.py b/downstream/ProxyCLIP_TPAMI/robustness_eval/configs/cfg_ade20k_robust.py new file mode 100644 index 0000000000000000000000000000000000000000..06e3689694e92330024ff76b1c5c3b2aea7e2ca9 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/robustness_eval/configs/cfg_ade20k_robust.py @@ -0,0 +1,71 @@ +import os + +# 模型设置(直接展开,不再继承) +model = dict( + name_path='/mnt/SSD8T/home/wjj/code/ProxyCLIP_TPAMI/configs/proxyclip/cls_ade20k.txt', + vfm=None, + type='DeCLIPSegmentation', + clip_type='EVA02-CLIP-B-16', + pretrained='eva', + checkpoint="/mnt/SSD8T/home/wjj/code/DeCLIP/backup_bin/logs/EVAB_dinov2B_csa_560_plus_exp90/checkpoints/epoch_6.pt", + mode="csa", +) + +# 评测与基础配置(来自 base_config.py) +test_evaluator = dict(type='IoUMetric', iou_metrics=['mIoU']) +default_scope = 'mmseg' +env_cfg = dict( + cudnn_benchmark=True, + mp_cfg=dict(mp_start_method='fork', opencv_num_threads=0), + dist_cfg=dict(backend='nccl'), +) +vis_backends = [dict(type='LocalVisBackend')] +visualizer = dict( + type='SegLocalVisualizer', vis_backends=vis_backends, alpha=1.0, name='visualizer') +log_processor = dict(by_epoch=False) +log_level = 'INFO' +load_from = None +resume = False +test_cfg = dict(type='TestLoop') +default_hooks = dict( + timer=dict(type='IterTimerHook'), + logger=dict(type='LoggerHook', interval=50, log_metric_by_epoch=False), + param_scheduler=dict(type='ParamSchedulerHook'), + checkpoint=dict(type='CheckpointHook', by_epoch=False, interval=2000), + sampler_seed=dict(type='DistSamplerSeedHook'), + visualization=dict(type='SegVisualizationHook', draw=False, interval=100), +) + +# 数据集设置(仅图片可被 CORRUPTED_DATA_ROOT 替换,标注保持原路径) +dataset_type = 'ADE20KDataset' +_orig_data_root = '/mnt/SSD8T/home/wjj/dataset/ADEChallengeData2016' +_corrupted_root = os.environ.get('CORRUPTED_DATA_ROOT', None) +_img_path = (os.path.join(_corrupted_root, 'images/validation') + if _corrupted_root else 'images/validation') +_seg_map_path = 'annotations/validation' +data_root = _orig_data_root + +test_pipeline = [ + dict(type='LoadImageFromFile'), + dict(type='Resize', scale=(4096, 448), keep_ratio=True), + dict(type='LoadAnnotations', reduce_zero_label=True), + dict(type='PackSegInputs', meta_keys=( + 'img_path', 'seg_map_path', 'ori_shape', 'img_shape', 'pad_shape', + 'scale_factor', 'flip', 'flip_direction', 'reduce_zero_label', + 'resize_shape')), +] + +test_dataloader = dict( + batch_size=1, + num_workers=4, + persistent_workers=True, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + data_prefix=dict( + img_path=_img_path, + seg_map_path=_seg_map_path), + pipeline=test_pipeline, + ), +) diff --git a/downstream/ProxyCLIP_TPAMI/robustness_eval/configs/cfg_coco_object_robust.py b/downstream/ProxyCLIP_TPAMI/robustness_eval/configs/cfg_coco_object_robust.py new file mode 100644 index 0000000000000000000000000000000000000000..e0f6e3a0b0559b71843c390ba3e013ce5fa979a3 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/robustness_eval/configs/cfg_coco_object_robust.py @@ -0,0 +1,73 @@ +import os + +# 模型设置(直接展开,不再继承) +model = dict( + name_path='/mnt/SSD8T/home/wjj/code/ProxyCLIP_TPAMI/configs/proxyclip/cls_coco_object.txt', + vfm=None, + type='DeCLIPSegmentation', + clip_type='EVA02-CLIP-B-16', + pretrained='eva', + checkpoint="/mnt/SSD8T/home/wjj/code/DeCLIP/backup_bin/logs/EVAB_dinov2B_csa_560_plus_exp90/checkpoints/epoch_6.pt", + mode="csa", + prob_thd=0.3, +) + +# 评测与基础配置(来自 base_config.py) +test_evaluator = dict(type='IoUMetric', iou_metrics=['mIoU']) +default_scope = 'mmseg' +env_cfg = dict( + cudnn_benchmark=True, + mp_cfg=dict(mp_start_method='fork', opencv_num_threads=0), + dist_cfg=dict(backend='nccl'), +) +vis_backends = [dict(type='LocalVisBackend')] +visualizer = dict( + type='SegLocalVisualizer', vis_backends=vis_backends, alpha=1.0, name='visualizer') +log_processor = dict(by_epoch=False) +log_level = 'INFO' +load_from = None +resume = False +test_cfg = dict(type='TestLoop') +default_hooks = dict( + timer=dict(type='IterTimerHook'), + logger=dict(type='LoggerHook', interval=50, log_metric_by_epoch=False), + param_scheduler=dict(type='ParamSchedulerHook'), + checkpoint=dict(type='CheckpointHook', by_epoch=False, interval=2000), + sampler_seed=dict(type='DistSamplerSeedHook'), + visualization=dict(type='SegVisualizationHook', draw=False, interval=100), +) + +# 数据集设置(仅图片可被 CORRUPTED_DATA_ROOT 替换,标注保持原路径) +dataset_type = 'COCOObjectDataset' +_orig_data_root = '/mnt/SSD8T/home/wjj/dataset/coco_obj' +_corrupted_root = os.environ.get('CORRUPTED_DATA_ROOT', None) +_img_path = (os.path.join(_corrupted_root, 'images/val2017') + if _corrupted_root else 'images/val2017') +_seg_map_path = 'annotations/val2017' +data_root = _orig_data_root + +test_pipeline = [ + dict(type='LoadImageFromFile'), + dict(type='Resize', scale=(2048, 448), keep_ratio=True), + dict(type='LoadAnnotations'), + dict(type='PackSegInputs', meta_keys=( + 'img_path', 'seg_map_path', 'ori_shape', 'img_shape', 'pad_shape', + 'scale_factor', 'flip', 'flip_direction', 'reduce_zero_label', + 'resize_shape')), +] + +test_dataloader = dict( + batch_size=1, + num_workers=4, + persistent_workers=True, + sampler=dict(type='DefaultSampler', shuffle=False), + dataset=dict( + type=dataset_type, + data_root=data_root, + reduce_zero_label=False, + data_prefix=dict( + img_path=_img_path, + seg_map_path=_seg_map_path), + pipeline=test_pipeline, + ), +) diff --git a/downstream/ProxyCLIP_TPAMI/robustness_eval/prepare_corrupted_images.py b/downstream/ProxyCLIP_TPAMI/robustness_eval/prepare_corrupted_images.py new file mode 100644 index 0000000000000000000000000000000000000000..69b2bdcbc3687e4be9805d4f5fecb423b75b3e51 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/robustness_eval/prepare_corrupted_images.py @@ -0,0 +1,173 @@ +#!/usr/bin/env python +""" +图片预处理模块:根据corruption类型和severity对图片进行corrupt并保存到tmp目录 + +该模块用于在评估前预处理图片,将corrupt后的图片保存到临时目录, +然后通过修改配置文件中的data_root来使用这些corrupt图片进行评估。 +""" + +import os +import sys +import shutil +from pathlib import Path +from tqdm import tqdm +import numpy as np +from PIL import Image +import cv2 + +# 添加项目根目录到路径 +project_root = Path(__file__).parent.parent +sys.path.insert(0, str(project_root)) + +try: + from imagecorruptions import corrupt +except ImportError: + raise ImportError( + 'imagecorruptions is not installed. ' + 'Please install it with: pip install imagecorruptions' + ) + + +def corrupt_and_save_images( + source_data_root: str, + source_img_prefix: str, + target_tmp_root: str, + corruption_name: str, + severity: int, + keep_structure: bool = True +): + """ + 对源目录中的所有图片应用corruption,并保存到目标临时目录 + + Args: + source_data_root: 源数据集根目录(如 '/mnt/SSD8T/home/wjj/dataset/cityscapes') + source_img_prefix: 源图片相对路径前缀(如 'leftImg8bit/val') + target_tmp_root: 目标临时目录根路径 + corruption_name: corruption类型名称(如 'gaussian_noise','clean'表示不应用corruption) + severity: 严重程度 (1-5),clean时忽略 + keep_structure: 是否保持原始目录结构 + + Returns: + str: 目标临时目录的绝对路径 + """ + source_data_root = Path(source_data_root) + target_tmp_root = Path(target_tmp_root) + + # 构建源图片目录 + source_img_dir = source_data_root / source_img_prefix + + if not source_img_dir.exists(): + raise ValueError(f"源图片目录不存在: {source_img_dir}") + + # 构建目标图片目录(保持相同的相对路径结构) + if keep_structure: + target_img_dir = target_tmp_root / source_img_prefix + else: + target_img_dir = target_tmp_root + + # 创建目标目录 + target_img_dir.mkdir(parents=True, exist_ok=True) + + # 如果是clean,直接使用原数据根目录,不再复制 + if corruption_name.lower() == 'clean': + return str(source_data_root.absolute()) + + # 应用corruption + print(f"应用corruption: {corruption_name}, severity={severity}") + print(f"源目录: {source_img_dir}") + print(f"目标目录: {target_img_dir}") + + # 获取所有图片文件 + image_files = list(source_img_dir.rglob('*.png')) + if not image_files: + # 尝试jpg格式 + image_files = list(source_img_dir.rglob('*.jpg')) + + if not image_files: + raise ValueError(f"在 {source_img_dir} 中未找到图片文件") + + # 处理每张图片 + for img_path in tqdm(image_files, desc=f'处理图片 ({corruption_name}, severity={severity})'): + # 读取图片 + img = cv2.imread(str(img_path)) + if img is None: + print(f"警告: 无法读取图片 {img_path},跳过") + continue + + # imagecorruptions期望RGB格式的uint8 numpy数组 + # cv2读取的是BGR,需要转换为RGB + img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) + + # 确保是uint8格式 + if img_rgb.dtype != np.uint8: + img_rgb = np.clip(img_rgb, 0, 255).astype(np.uint8) + + # 应用corruption + try: + corrupted_img = corrupt( + img_rgb, + corruption_name=corruption_name, + severity=severity + ) + except Exception as e: + # 遇到错误直接抛出异常,不静默处理 + error_msg = ( + f"处理图片 {img_path} 时出错: {e}\n" + f"Corruption类型: {corruption_name}, Severity: {severity}\n" + f"这可能是imagecorruptions库版本兼容性问题(如scikit-image版本不兼容)\n" + f"请检查并修复环境依赖问题" + ) + raise RuntimeError(error_msg) from e + + # 转换回BGR(因为cv2.imwrite期望BGR) + corrupted_img_bgr = cv2.cvtColor(corrupted_img, cv2.COLOR_RGB2BGR) + + # 保存到目标目录(保持相对路径结构) + rel_path = img_path.relative_to(source_img_dir) + target_path = target_img_dir / rel_path + target_path.parent.mkdir(parents=True, exist_ok=True) + + # 保存图片 + cv2.imwrite(str(target_path), corrupted_img_bgr) + + return str(target_tmp_root.absolute()) + + +def cleanup_tmp_directory(tmp_root: str): + """ + 清理临时目录 + + Args: + tmp_root: 临时目录路径 + """ + tmp_path = Path(tmp_root) + if tmp_path.exists(): + print(f"清理临时目录: {tmp_path}") + shutil.rmtree(tmp_path) + print("临时目录已清理") + + +if __name__ == '__main__': + # 测试代码 + import argparse + + parser = argparse.ArgumentParser(description='测试图片预处理') + parser.add_argument('--source-root', type=str, required=True, help='源数据集根目录') + parser.add_argument('--source-prefix', type=str, default='leftImg8bit/val', help='源图片相对路径前缀') + parser.add_argument('--target-root', type=str, required=True, help='目标临时目录') + parser.add_argument('--corruption', type=str, default='gaussian_noise', help='corruption类型') + parser.add_argument('--severity', type=int, default=1, help='严重程度') + + args = parser.parse_args() + + corrupt_and_save_images( + args.source_root, + args.source_prefix, + args.target_root, + args.corruption, + args.severity + ) + + print(f"\n处理完成!临时目录: {args.target_root}") + print("测试完成后可以手动删除临时目录,或使用cleanup_tmp_directory函数") + diff --git a/downstream/ProxyCLIP_TPAMI/robustness_eval/robust_datasets.py b/downstream/ProxyCLIP_TPAMI/robustness_eval/robust_datasets.py new file mode 100644 index 0000000000000000000000000000000000000000..19fa8514e37fa4f00b0e2aa04a84da98e74dcf7c --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/robustness_eval/robust_datasets.py @@ -0,0 +1,67 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +""" +预置 8 个数据集的鲁棒性评估配置路径,统一管理。 + +使用示例(在项目根目录): + # 查看支持的数据集 + python robustness_eval/robust_datasets.py --list + + # 获取某个数据集对应的配置路径 + python robustness_eval/robust_datasets.py --name cityscapes + +然后可在 run_eval.sh 中设置: + CONFIG=$(python robustness_eval/robust_datasets.py --name cityscapes) +""" + +import argparse +from pathlib import Path + +project_root = Path(__file__).parent.parent + +# 预置 8 个数据集对应的鲁棒性配置文件(相对路径,位于 robustness_eval/configs/) +DATASET_CONFIGS = { + "cityscapes": "robustness_eval/configs/cfg_cityscapes_robust.py", + "coco_stuff164k": "robustness_eval/configs/cfg_coco_stuff164k_robust.py", + "ade20k": "robustness_eval/configs/cfg_ade20k_robust.py", + "voc20": "robustness_eval/configs/cfg_voc20_robust.py", + "voc21": "robustness_eval/configs/cfg_voc21_robust.py", + "context59": "robustness_eval/configs/cfg_context59_robust.py", + "context60": "robustness_eval/configs/cfg_context60_robust.py", + "coco_object": "robustness_eval/configs/cfg_coco_object_robust.py", +} + + +def resolve_config(name: str) -> Path: + if name not in DATASET_CONFIGS: + raise KeyError(f"未找到数据集 '{name}',可用项: {list(DATASET_CONFIGS.keys())}") + rel = DATASET_CONFIGS[name] + return project_root / rel + + +def parse_args(): + parser = argparse.ArgumentParser(description="获取预置数据集的鲁棒性评估配置路径") + parser.add_argument("--list", action="store_true", help="列出所有支持的数据集名称") + parser.add_argument("--name", type=str, help="数据集名称,返回对应配置路径") + return parser.parse_args() + + +def main(): + args = parse_args() + if args.list: + print("支持的数据集:") + for k in DATASET_CONFIGS.keys(): + print(f" {k}") + return + + if args.name: + path = resolve_config(args.name) + print(path) + return + + print("未指定参数。使用 --list 查看支持的数据集,或 --name ") + + +if __name__ == "__main__": + main() + diff --git a/downstream/ProxyCLIP_TPAMI/robustness_eval/run_eval.sh b/downstream/ProxyCLIP_TPAMI/robustness_eval/run_eval.sh new file mode 100644 index 0000000000000000000000000000000000000000..0a46194702e9ca9c32b6f9312baf5a0a94eb710a --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/robustness_eval/run_eval.sh @@ -0,0 +1,70 @@ +#!/bin/bash +# 鲁棒性评估启动脚本 + +# ========== 配置参数 ========== +# 指定可用的GPU ID(根据实际情况修改) +GPUS=(0 2 3 5 6 7) + +# 数据集名称(与 robust_datasets.py 中的键一致) +# 可选: cityscapes, coco_stuff164k, ade20k, voc20, voc21, context59, context60, coco_object +DATASET="coco_stuff164k" + +# 配置文件路径(优先使用 DATASET 自动解析,若需要可手动覆盖) +CONFIG="" + +# 工作目录 +WORK_DIR="robustness_eval/results" + +# 退化类型: common/validation/all/noise/blur/weather/digital +CORRUPTIONS="common" + +# 严重程度 +SEVERITIES="1 2 3 4 5" + +# 是否使用nohup后台运行 (true/false) +NOHUP=true + +# ========== 执行评估 ========== +# 确保工作目录存在 +mkdir -p $WORK_DIR + +# 如果未显式指定 CONFIG,则通过 DATASET 自动解析 +if [ -z "$CONFIG" ]; then + CONFIG=$(python robustness_eval/robust_datasets.py --name $DATASET) +fi + +# 如果解析失败则退出 +if [ -z "$CONFIG" ]; then + echo "错误: 未能解析配置,DATASET=$DATASET" + exit 1 +fi + +LOG_FILE="${WORK_DIR}/eval_$(date +%Y%m%d_%H%M%S).log" + +if [ "$NOHUP" = true ]; then + echo "使用nohup后台运行,日志文件: $LOG_FILE" + nohup python robustness_eval/run_robustness_eval_multi_gpu.py \ + --config $CONFIG \ + --work-dir $WORK_DIR \ + --gpus ${GPUS[@]} \ + --corruptions $CORRUPTIONS \ + --severities $SEVERITIES \ + > $LOG_FILE 2>&1 & + + echo "评估任务已在后台启动,PID: $!" + echo "查看日志: tail -f $LOG_FILE" + echo "" + echo "评估完成后,收集结果请运行:" + echo "python robustness_eval/collect_all_results.py --results-dir $WORK_DIR" +else + python robustness_eval/run_robustness_eval_multi_gpu.py \ + --config $CONFIG \ + --work-dir $WORK_DIR \ + --gpus ${GPUS[@]} \ + --corruptions $CORRUPTIONS \ + --severities $SEVERITIES + + echo "" + echo "评估完成!收集结果请运行:" + echo "python robustness_eval/collect_all_results.py --results-dir $WORK_DIR" +fi diff --git a/downstream/ProxyCLIP_TPAMI/robustness_eval/run_robustness_eval.py b/downstream/ProxyCLIP_TPAMI/robustness_eval/run_robustness_eval.py new file mode 100644 index 0000000000000000000000000000000000000000..be7646780134da6e23d19f9c7c9e71bfb0dd25a9 --- /dev/null +++ b/downstream/ProxyCLIP_TPAMI/robustness_eval/run_robustness_eval.py @@ -0,0 +1,379 @@ +#!/usr/bin/env python +""" +批量运行鲁棒性评估脚本 + +该脚本会遍历所有常见的图像退化类型和严重程度,在Cityscapes数据集上评估模型性能。 + +使用方法: + python robustness_eval/run_robustness_eval.py \ + --config configs/eva_declip/cfg_city_scapes_robust.py \ + --work-dir work_logs/robustness_eval \ + --corruptions common \ + --severities 1 2 3 4 5 +""" + +import os +import sys +import argparse +import subprocess +import json +from pathlib import Path +from imagecorruptions import get_corruption_names + +# 添加项目根目录到路径 +project_root = Path(__file__).parent.parent +sys.path.insert(0, str(project_root)) + +from robustness_eval.prepare_corrupted_images import ( + corrupt_and_save_images, + cleanup_tmp_directory +) + + +def parse_args(): + parser = argparse.ArgumentParser( + description='批量运行鲁棒性评估') + parser.add_argument( + '--config', + type=str, + default='configs/eva_declip/cfg_city_scapes_robust.py', + help='配置文件路径') + parser.add_argument( + '--work-dir', + type=str, + default='robustness_eval/results', + help='工作目录,用于保存结果(默认: robustness_eval/results)') + parser.add_argument( + '--corruptions', + type=str, + choices=['common', 'validation', 'all', 'noise', 'blur', 'weather', 'digital'], + default='common', + help='退化类型子集') + parser.add_argument( + '--severities', + type=int, + nargs='+', + default=[1, 2, 3, 4, 5], + help='严重程度级别列表') + parser.add_argument( + '--clean-only', + action='store_true', + help='只运行干净图像的评估(baseline)') + parser.add_argument( + '--skip-clean', + action='store_true', + help='跳过干净图像的评估') + parser.add_argument( + '--parallel', + type=int, + default=1, + help='并行运行的进程数(1表示串行)') + parser.add_argument( + '--resume', + action='store_true', + help='从上次中断的地方继续(跳过已完成的评估)') + return parser.parse_args() + + +def get_eval_script_path(): + """获取eval.py脚本的路径""" + return project_root / 'eval.py' + + +def get_dataset_info_from_config(config_path): + """从配置文件中读取数据集信息 + + 读取原始数据集的data_root和img_path_prefix,用于图片预处理 + """ + from mmengine.config import Config + + # 临时保存并清除CORRUPTED_DATA_ROOT,以获取原始配置 + original_corrupted_root = os.environ.pop('CORRUPTED_DATA_ROOT', None) + + try: + cfg = Config.fromfile(str(config_path)) + + # 读取data_root(允许为空,保持原配置含义) + data_root = cfg.get('data_root', '') + + # 获取img_path_prefix;若为绝对路径则直接使用 + data_prefix = cfg.test_dataloader.dataset.get('data_prefix', {}) + img_path_prefix = data_prefix.get('img_path', 'leftImg8bit/val') + + return data_root, img_path_prefix + finally: + # 恢复环境变量 + if original_corrupted_root is not None: + os.environ['CORRUPTED_DATA_ROOT'] = original_corrupted_root + + +def run_single_eval(config_path, corruption_name, severity, work_dir_base, + source_data_root=None, source_img_prefix=None): + """运行单次评估 + + Args: + config_path: 配置文件路径 + corruption_name: corruption类型名称 + severity: 严重程度 + work_dir_base: 工作目录基础路径 + source_data_root: 源数据集根目录(如果为None,则从配置文件读取) + source_img_prefix: 源图片相对路径前缀(如果为None,则从配置文件读取) + """ + # 确保工作目录是绝对路径 + work_dir_base = Path(work_dir_base) + if not work_dir_base.is_absolute(): + work_dir_base = project_root / work_dir_base + + # 创建工作目录 + if corruption_name == 'clean': + work_dir = work_dir_base / corruption_name + else: + work_dir = work_dir_base / corruption_name / f'severity_{severity}' + work_dir.mkdir(parents=True, exist_ok=True) + + # 从配置文件读取数据集信息(如果未提供) + if source_data_root is None or source_img_prefix is None: + cfg_data_root, cfg_img_prefix = get_dataset_info_from_config(config_path) + if source_data_root is None: + source_data_root = cfg_data_root + if source_img_prefix is None: + source_img_prefix = cfg_img_prefix + + # 准备corrupt图片到临时目录 + tmp_dir = None + try: + # 创建临时目录 + tmp_base = work_dir_base / 'tmp_corrupted_images' + if corruption_name == 'clean': + tmp_dir = tmp_base / 'clean' + else: + tmp_dir = tmp_base / corruption_name / f'severity_{severity}' + + print(f"\n{'='*80}") + print(f"准备图片: {corruption_name}, severity={severity}") + print(f"源目录: {source_data_root}") + print(f"临时目录: {tmp_dir}") + print(f"{'='*80}\n") + + # 预处理图片(应用corruption并保存到tmp目录) + target_data_root = corrupt_and_save_images( + source_data_root=source_data_root, + source_img_prefix=source_img_prefix, + target_tmp_root=str(tmp_dir), + corruption_name=corruption_name, + severity=severity + ) + + # 设置环境变量,告诉配置文件使用临时目录 + env = os.environ.copy() + env['CORRUPTED_DATA_ROOT'] = target_data_root + env['CORRUPTION_NAME'] = corruption_name + if corruption_name != 'clean': + env['SEVERITY'] = str(severity) + else: + env['SEVERITY'] = '1' # clean时severity不重要,但需要设置 + + # 构建命令 + eval_script = get_eval_script_path() + cmd = [ + sys.executable, + str(eval_script), + '--config', str(config_path), + '--work-dir', str(work_dir) + ] + + # 运行评估 + print(f"\n{'='*80}") + print(f"运行评估: {corruption_name}, severity={severity}") + print(f"工作目录: {work_dir}") + print(f"使用数据目录: {target_data_root}") + print(f"{'='*80}\n") + + result = subprocess.run(cmd, env=env, cwd=project_root) + + if result.returncode == 0: + print(f"✓ 完成: {corruption_name}, severity={severity}") + success = True + else: + print(f"✗ 失败: {corruption_name}, severity={severity}") + success = False + + return success, work_dir + + finally: + # 清理临时目录 + if tmp_dir and tmp_dir.exists(): + print(f"\n清理临时目录: {tmp_dir}") + cleanup_tmp_directory(str(tmp_dir)) + + +def load_results(work_dir): + """从工作目录加载评估结果""" + results_file = Path(work_dir) / 'results.txt' + if not results_file.exists(): + return None + + results = {} + with open(results_file, 'r') as f: + lines = f.readlines() + for line in lines: + if ':' in line: + key, value = line.strip().split(':', 1) + key = key.strip() + value = value.strip() + # 尝试转换为数字 + try: + if '.' in value: + value = float(value) + else: + value = int(value) + except ValueError: + pass + results[key] = value + + return results + + +def check_if_done(work_dir): + """检查评估是否已完成""" + results_file = Path(work_dir) / 'results.txt' + if results_file.exists(): + # 检查是否包含mIoU结果 + with open(results_file, 'r') as f: + content = f.read() + if 'mIoU' in content or 'aAcc' in content: + return True + return False + + +def main(): + args = parse_args() + + # 获取配置文件路径 + config_path = Path(args.config) + if not config_path.is_absolute(): + config_path = project_root / config_path + + if not config_path.exists(): + print(f"错误: 配置文件不存在: {config_path}") + return + + # 获取退化类型列表 + if args.clean_only: + corruption_list = ['clean'] + else: + corruption_list = get_corruption_names(args.corruptions) + if not args.skip_clean: + corruption_list = ['clean'] + corruption_list + + # 准备所有评估任务 + tasks = [] + for corruption in corruption_list: + if corruption == 'clean': + # 干净图像只需要评估一次 + tasks.append(('clean', 1)) # severity设为1,但实际不会被使用 + else: + for severity in args.severities: + tasks.append((corruption, severity)) + + print(f"\n{'='*80}") + print(f"鲁棒性评估计划") + print(f"{'='*80}") + print(f"配置文件: {config_path}") + print(f"工作目录: {args.work_dir}") + print(f"退化类型: {args.corruptions} ({len(corruption_list)} 种)") + print(f"严重程度: {args.severities}") + print(f"总任务数: {len(tasks)}") + print(f"{'='*80}\n") + + # 确保工作目录是绝对路径 + work_dir_base = Path(args.work_dir) + if not work_dir_base.is_absolute(): + work_dir_base = project_root / work_dir_base + + # 先加载已有的结果(如果存在),以便合并 + summary_file = work_dir_base / 'results_summary.json' + results_summary = {} + if summary_file.exists(): + try: + with open(summary_file, 'r') as f: + results_summary = json.load(f) + except: + pass + + # 运行评估 + completed = 0 + failed = 0 + skipped = 0 + + for corruption, severity in tasks: + if corruption == 'clean': + corruption_name = 'clean' + severity_display = 'N/A' + severity_for_result = 0 # 用于结果存储 + else: + corruption_name = corruption + severity_display = severity + severity_for_result = severity + + # 确保工作目录是绝对路径 + work_dir_base = Path(args.work_dir) + if not work_dir_base.is_absolute(): + work_dir_base = project_root / work_dir_base + + work_dir = work_dir_base / corruption_name + if corruption != 'clean': + work_dir = work_dir / f'severity_{severity}' + + # 检查是否需要跳过 + if args.resume and check_if_done(work_dir): + print(f"⊘ 跳过已完成: {corruption_name}, severity={severity_display}") + skipped += 1 + # 加载已有结果 + result = load_results(work_dir) + if result: + if corruption_name not in results_summary: + results_summary[corruption_name] = {} + results_summary[corruption_name][severity_for_result] = result + continue + + # 运行评估 + success, work_dir_actual = run_single_eval( + config_path, corruption_name, severity, args.work_dir, + source_data_root=None, source_img_prefix=None) + + if success: + completed += 1 + # 加载结果 + result = load_results(work_dir_actual) + if result: + if corruption_name not in results_summary: + results_summary[corruption_name] = {} + results_summary[corruption_name][severity_for_result] = result + else: + failed += 1 + + # 保存汇总结果 + summary_file = work_dir_base / 'results_summary.json' + summary_file.parent.mkdir(parents=True, exist_ok=True) + with open(summary_file, 'w') as f: + json.dump(results_summary, f, indent=2) + + # 打印汇总 + print(f"\n{'='*80}") + print(f"评估完成汇总") + print(f"{'='*80}") + print(f"总任务数: {len(tasks)}") + print(f"已完成: {completed}") + print(f"已跳过: {skipped}") + print(f"失败: {failed}") + print(f"结果汇总已保存到: {summary_file}") + print(f"{'='*80}\n") + + # 生成Excel文件(解耦:不在这里生成,由用户单独调用) + # Excel生成已解耦,用户可以在所有任务完成后单独调用save_results_to_excel.py + + +if __name__ == '__main__': + main() +