Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- analysis/model_vis_tools/vis_sd_featsv4.py +207 -0
- analysis/model_vis_tools/vis_sd_featsv5.1.py +150 -0
- analysis/model_vis_tools/vis_sd_featsv5.py +262 -0
- analysis/model_vis_tools/vis_sd_featsv6.py +161 -0
- analysis/prompt_ensemble_ablation/configs/fvit_vitb16_ovcoco_clearclip_single_prompt.py +23 -0
- analysis/prompt_ensemble_ablation/configs/fvit_vitb16_ovcoco_declip_ensemble.py +208 -0
- analysis/prompt_ensemble_ablation/configs/fvit_vitb16_ovcoco_declip_single_prompt.py +209 -0
- analysis/prompt_ensemble_ablation/configs/fvit_vitb16_ovcoco_ensemble.py +27 -0
- analysis/prompt_ensemble_ablation/configs/fvit_vitb16_ovcoco_maskclip_ensemble.py +22 -0
- analysis/prompt_ensemble_ablation/configs/fvit_vitb16_ovcoco_maskclip_single_prompt.py +22 -0
- analysis/prompt_ensemble_ablation/configs/fvit_vitb16_ovcoco_single_prompt.py +27 -0
- analysis/prompt_ensemble_ablation/configs/fvit_vitl14_ovcoco_clearclip_ensemble.py +23 -0
- analysis/prompt_ensemble_ablation/configs/fvit_vitl14_ovcoco_clearclip_single_prompt.py +23 -0
- analysis/prompt_ensemble_ablation/configs/fvit_vitl14_ovcoco_declip_ensemble.py +208 -0
- analysis/prompt_ensemble_ablation/configs/fvit_vitl14_ovcoco_declip_single_prompt.py +208 -0
- analysis/prompt_ensemble_ablation/configs/fvit_vitl14_ovcoco_ensemble.py +26 -0
- analysis/prompt_ensemble_ablation/configs/fvit_vitl14_ovcoco_maskclip_ensemble.py +26 -0
- analysis/prompt_ensemble_ablation/configs/fvit_vitl14_ovcoco_maskclip_single_prompt.py +26 -0
- analysis/prompt_ensemble_ablation/configs/fvit_vitl14_ovcoco_single_prompt.py +26 -0
- analysis/prompt_ensemble_ablation/prompt_ensemble_ablation_results.xlsx +0 -0
- analysis/prompt_ensemble_ablation/results/clearclip_b_results.txt +32 -0
- analysis/prompt_ensemble_ablation/results/clearclip_l_results.txt +32 -0
- analysis/prompt_ensemble_ablation/results/declip_ablation_results.txt +54 -0
- analysis/prompt_ensemble_ablation/results/maskclip_b_clipself_l_results.txt +50 -0
- analysis/prompt_ensemble_ablation/scripts/generate_all_embeddings.sh +95 -0
- analysis/prompt_ensemble_ablation/scripts/generate_single_prompt_embeddings.py +224 -0
- analysis/prompt_ensemble_ablation/scripts/run_all_ablation.sh +211 -0
- analysis/prompt_ensemble_ablation/scripts/run_clearclip_b.sh +125 -0
- analysis/prompt_ensemble_ablation/scripts/run_clearclip_l.sh +125 -0
- analysis/prompt_ensemble_ablation/scripts/run_declip_ablation.sh +163 -0
- analysis/prompt_ensemble_ablation/scripts/run_maskclip_b_clipself_l.sh +140 -0
- analysis/robustness_eval/README.md +131 -0
- analysis/robustness_eval/compare_models.py +225 -0
- analysis/robustness_eval/generate_corruption_table.py +291 -0
- analysis/robustness_eval/merge_robustness_results.py +605 -0
- analysis/robustness_eval/results/clearclip/robustness_report.xlsx +0 -0
- analysis/robustness_eval/results/clearclip/robustness_summary.json +76 -0
- analysis/robustness_eval/results/clearclip/run_gpu0.sh +35 -0
- analysis/robustness_eval/results/clearclip/run_gpu1.sh +35 -0
- analysis/robustness_eval/results/clearclip/run_gpu2.sh +35 -0
- analysis/robustness_eval/results/clearclip/run_gpu3.sh +35 -0
- analysis/robustness_eval/results/clearclip/run_gpu4.sh +35 -0
- analysis/robustness_eval/results/clearclip/run_gpu5.sh +35 -0
- analysis/robustness_eval/results/clearclip/run_gpu6.sh +35 -0
- analysis/robustness_eval/results/clearclip/run_gpu7.sh +35 -0
- analysis/robustness_eval/results/clipself/robustness_report.xlsx +0 -0
- analysis/robustness_eval/results/clipself/robustness_summary.json +76 -0
- analysis/robustness_eval/results/clipself/run_gpu0.sh +35 -0
- analysis/robustness_eval/results/clipself/run_gpu1.sh +35 -0
- analysis/robustness_eval/results/clipself/run_gpu2.sh +35 -0
analysis/model_vis_tools/vis_sd_featsv4.py
ADDED
|
@@ -0,0 +1,207 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import h5py
|
| 3 |
+
import torch
|
| 4 |
+
import os
|
| 5 |
+
import numpy as np
|
| 6 |
+
from PIL import Image,ImageDraw
|
| 7 |
+
import torch.nn.functional as F
|
| 8 |
+
from open_clip.transform import ResizeMaxSize,_convert_to_rgb,det_image_transform,ResizeLongest
|
| 9 |
+
from torchvision.transforms import ToTensor,Normalize
|
| 10 |
+
import matplotlib.pyplot as plt
|
| 11 |
+
from torchvision import transforms
|
| 12 |
+
from pycocotools.coco import COCO
|
| 13 |
+
from src.segment_anything import sam_model_registry
|
| 14 |
+
from math import sqrt
|
| 15 |
+
from vis_sd_featsv2 import build_DINOv2, plot_pca
|
| 16 |
+
|
| 17 |
+
def load_data(coco):
|
| 18 |
+
image_ids=[]
|
| 19 |
+
img_ids = coco.getImgIds()
|
| 20 |
+
cat_ids = coco.getCatIds()
|
| 21 |
+
for img_id in img_ids:
|
| 22 |
+
img = coco.loadImgs(img_id)[0]
|
| 23 |
+
ann_ids = coco.getAnnIds(imgIds=img['id'], catIds=cat_ids, iscrowd=None)
|
| 24 |
+
anns = coco.loadAnns(ann_ids)
|
| 25 |
+
anns = [ann for ann in anns if ann['iscrowd'] == 0]
|
| 26 |
+
if len(anns) == 0:
|
| 27 |
+
continue
|
| 28 |
+
image_ids.append(img_id)
|
| 29 |
+
torch.manual_seed(42)
|
| 30 |
+
image_ids = [image_ids[i] for i in torch.randperm(len(image_ids))]
|
| 31 |
+
return image_ids
|
| 32 |
+
|
| 33 |
+
def build_SAM():
|
| 34 |
+
try:
|
| 35 |
+
vfm = sam_model_registry['vit_l'](checkpoint='/mnt/SSD8T/home/wjj/code/ProxyCLIP/sam_ckpts/sam_vit_l_0b3195.pth').half()
|
| 36 |
+
except Exception as e:
|
| 37 |
+
raise RuntimeError(f"Failed to load SAM model: {e}")
|
| 38 |
+
return vfm
|
| 39 |
+
|
| 40 |
+
mean=[0.485, 0.456, 0.406]
|
| 41 |
+
std=[0.229, 0.224, 0.225]
|
| 42 |
+
normalize = Normalize(mean=mean, std=std)
|
| 43 |
+
SAM_transform=transforms.Compose([
|
| 44 |
+
ResizeLongest(1120, fill=0),
|
| 45 |
+
_convert_to_rgb,
|
| 46 |
+
ToTensor(),
|
| 47 |
+
normalize
|
| 48 |
+
])
|
| 49 |
+
DINO_transform=transforms.Compose([
|
| 50 |
+
ResizeLongest(490, fill=0),
|
| 51 |
+
_convert_to_rgb,
|
| 52 |
+
ToTensor(),
|
| 53 |
+
normalize
|
| 54 |
+
])
|
| 55 |
+
_transform=transforms.Compose([
|
| 56 |
+
ResizeLongest(560, fill=0),
|
| 57 |
+
_convert_to_rgb,])
|
| 58 |
+
|
| 59 |
+
with torch.no_grad():
|
| 60 |
+
device="cuda"
|
| 61 |
+
coco_path='/mnt/SSD8T/home/wjj/dataset/standard_coco/annotations/instances_train2017.json'
|
| 62 |
+
img_path='/mnt/SSD8T/home/wjj/dataset/standard_coco/train2017'
|
| 63 |
+
cache_path = "/mnt/SSD8T/home/wjj/code/distilldift/train/cache/Dift_COCO_dift_merged_fp16.h5"
|
| 64 |
+
cache=h5py.File(cache_path, 'r')[str(0)]
|
| 65 |
+
weights = torch.load("/mnt/SSD8T/home/wjj/code/DeCLIP/EVAB_COCO_117K_topk10.pth", map_location="cpu")
|
| 66 |
+
coco=COCO(coco_path)
|
| 67 |
+
image_ids=load_data(coco)
|
| 68 |
+
sam=build_SAM().to(device)
|
| 69 |
+
dino=build_DINOv2().to(device)
|
| 70 |
+
image_select=100
|
| 71 |
+
img_name = coco.loadImgs(image_ids[image_select])[0]['file_name']
|
| 72 |
+
weight = weights[image_select]
|
| 73 |
+
match_id = weight[np.random.choice(10)]
|
| 74 |
+
matching_sample = image_ids[match_id]
|
| 75 |
+
matching_sample_info = coco.imgs[matching_sample]
|
| 76 |
+
knn_image_name=matching_sample_info['file_name']
|
| 77 |
+
knn_image_path = os.path.join(img_path, knn_image_name)
|
| 78 |
+
knn_image= Image.open(knn_image_path)
|
| 79 |
+
knn_image_tensor = SAM_transform(knn_image).unsqueeze(0).to(torch.float16).to(device)
|
| 80 |
+
|
| 81 |
+
# ------- 1. 特征提取,注意区分raw和norm -------
|
| 82 |
+
# 对KNN图片
|
| 83 |
+
knn_sam_feats_raw = sam.image_encoder(knn_image_tensor).flatten(start_dim=-2).transpose(-2, -1).to(torch.float32).to(device)
|
| 84 |
+
knn_dino_feats_raw = dino.get_intermediate_layers(knn_image_tensor, reshape=True)[0].flatten(start_dim=-2).transpose(-2,-1) # 未归一化
|
| 85 |
+
knn_sd_feats_raw = torch.from_numpy(cache[knn_image_name][()]).unsqueeze(0).flatten(start_dim=-2).transpose(-2, -1).to(torch.float32).to(device)
|
| 86 |
+
|
| 87 |
+
knn_sam_feats = F.normalize(knn_sam_feats_raw, dim=2)
|
| 88 |
+
knn_dino_feats = F.normalize(knn_dino_feats_raw, dim=2)
|
| 89 |
+
knn_sd_feats = F.normalize(knn_sd_feats_raw, dim=2)
|
| 90 |
+
|
| 91 |
+
# 对当前图片
|
| 92 |
+
image_path = os.path.join(img_path, img_name)
|
| 93 |
+
image = Image.open(image_path)
|
| 94 |
+
image_tensor = SAM_transform(image).unsqueeze(0).to(torch.float16).to(device)
|
| 95 |
+
DINO_tensor=DINO_transform(image).unsqueeze(0).to(torch.float16).to(device)
|
| 96 |
+
sd_feats_raw = torch.from_numpy(cache[img_name][()]).unsqueeze(0).flatten(start_dim=-2).transpose(-2, -1).to(torch.float32).to(device)
|
| 97 |
+
sam_feats_raw = sam.image_encoder(image_tensor)
|
| 98 |
+
|
| 99 |
+
dino_feats_raw = dino.get_intermediate_layers(DINO_tensor, reshape=True)[0]
|
| 100 |
+
|
| 101 |
+
_size = dino_feats_raw.shape[-2:]
|
| 102 |
+
sam_feats_raw = sam.image_encoder(image_tensor)
|
| 103 |
+
sam_feats_raw=F.interpolate(sam_feats_raw, size=_size, mode='bilinear', align_corners=False).flatten(start_dim=-2).transpose(-2,-1) # 未归一化
|
| 104 |
+
dino_feats_raw = dino_feats_raw.flatten(start_dim=-2).transpose(-2, -1).to(torch.float32).to(device)
|
| 105 |
+
sd_feats = F.normalize(sd_feats_raw, dim=2)
|
| 106 |
+
sam_feats = F.normalize(sam_feats_raw, dim=2)
|
| 107 |
+
dino_feats = F.normalize(dino_feats_raw, dim=2)
|
| 108 |
+
|
| 109 |
+
# w_sam = 0.3
|
| 110 |
+
# w_dino = 0.7
|
| 111 |
+
# sam_weighted = (w_sam ** 0.5) * sam_feats
|
| 112 |
+
# dino_weighted = (w_dino ** 0.5) * dino_feats
|
| 113 |
+
dino_sam_feats_raw = torch.cat([dino_feats, sam_feats], dim=2)
|
| 114 |
+
dino_sam_feats=F.normalize(dino_sam_feats_raw, dim=2)
|
| 115 |
+
|
| 116 |
+
# ------- 2. 相似度热力图 -------
|
| 117 |
+
sim_dino = torch.einsum('bic,bjc->bij', dino_feats, dino_feats) # [bs, n_sd, n_sd]
|
| 118 |
+
sim_sam = torch.einsum('bic,bjc->bij', sam_feats, sam_feats) # [bs, n_sd, n_sd]
|
| 119 |
+
sim_dino_sam = torch.einsum('bic,bjc->bij', dino_sam_feats, dino_sam_feats)
|
| 120 |
+
|
| 121 |
+
target_size = (560, 560)
|
| 122 |
+
low_res_size = (35, 35)
|
| 123 |
+
low_res_token_choosen = (7, 17)
|
| 124 |
+
token_chosen = int(low_res_token_choosen[0] * low_res_size[1] + low_res_token_choosen[1])
|
| 125 |
+
token_x_low_res = token_chosen % low_res_size[0]
|
| 126 |
+
token_y_low_res = token_chosen // low_res_size[0]
|
| 127 |
+
token_x_img = int(((token_x_low_res+ 0.5) / low_res_size[0]) * target_size[0])
|
| 128 |
+
token_y_img = int(((token_y_low_res+ 0.5) / low_res_size[1]) * target_size[1])
|
| 129 |
+
|
| 130 |
+
output_dir = "sam_vis"
|
| 131 |
+
if not os.path.exists(output_dir):
|
| 132 |
+
os.mkdir(output_dir)
|
| 133 |
+
|
| 134 |
+
sim_dino = sim_dino[:, token_chosen, :] # 1, h*w
|
| 135 |
+
sim_sam = sim_sam[:, token_chosen, :] # 1, h*w
|
| 136 |
+
sim_dino_sam = sim_dino_sam[:, token_chosen, :] # 1, h*w
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
vis_img1=_transform(image)
|
| 140 |
+
|
| 141 |
+
# 2. sim_sd, sim_dino, sim_sd_dino热力图
|
| 142 |
+
sim_maps = [sim_dino, sim_sam, sim_dino_sam]
|
| 143 |
+
sim_np_maps = []
|
| 144 |
+
|
| 145 |
+
for sim in sim_maps:
|
| 146 |
+
sim_map = sim.view(1, 1, low_res_size[0], low_res_size[1])
|
| 147 |
+
sim_map_up = F.interpolate(sim_map, size=target_size, mode="bilinear", align_corners=False)
|
| 148 |
+
sim_map_np = sim_map_up.squeeze().cpu().numpy()
|
| 149 |
+
sim_np_maps.append(sim_map_np)
|
| 150 |
+
|
| 151 |
+
# 3. 可视化
|
| 152 |
+
fig, axes = plt.subplots(1, 4, figsize=(20, 6))
|
| 153 |
+
|
| 154 |
+
# 第一列:原图
|
| 155 |
+
axes[0].imshow(vis_img1)
|
| 156 |
+
axes[0].scatter([token_x_img], [token_y_img], c='red', s=100, marker="o", edgecolors='black', linewidths=2)
|
| 157 |
+
axes[0].set_title('Image')
|
| 158 |
+
axes[0].axis('off')
|
| 159 |
+
|
| 160 |
+
# 后三列:三个相似度热力图
|
| 161 |
+
titles = [
|
| 162 |
+
'Token Similarity (DINOv2)',
|
| 163 |
+
'Token Similarity (SAM)',
|
| 164 |
+
'Token Similarity (DINOv2+SAM)'
|
| 165 |
+
]
|
| 166 |
+
for i in range(3):
|
| 167 |
+
axes[i+1].imshow(sim_np_maps[i], cmap='jet')
|
| 168 |
+
axes[i+1].set_title(titles[i])
|
| 169 |
+
axes[i+1].axis('off')
|
| 170 |
+
|
| 171 |
+
plt.tight_layout()
|
| 172 |
+
plt.savefig(os.path.join(output_dir, "token_similarity_vis.png"))
|
| 173 |
+
plt.close(fig)
|
| 174 |
+
|
| 175 |
+
# ===== PCA 部分 =====
|
| 176 |
+
# 用未归一化特征
|
| 177 |
+
# 注意:sam_feats, sd_feats, sd_sam_feats 需要未归一化版本
|
| 178 |
+
# 你第二段代码里对 sd_feats 和 sam_feats 直接 normalize 了
|
| 179 |
+
# 所以需要提前保存一份未归一化的特征
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
feats_to_pca = [sam_feats_raw, dino_feats_raw, dino_sam_feats_raw]
|
| 183 |
+
pca_titles = ["SAM PCA", "DINOv2 PCA", "DINOv2+SAM PCA"]
|
| 184 |
+
pca_paths = []
|
| 185 |
+
for i, feats in enumerate(feats_to_pca):
|
| 186 |
+
feats_np = feats[0].cpu().numpy()
|
| 187 |
+
pca_path = os.path.join(output_dir, f"pca_vis_{i}.png")
|
| 188 |
+
plot_pca(feats_np, pca_path, target_size)
|
| 189 |
+
pca_paths.append(pca_path)
|
| 190 |
+
|
| 191 |
+
pca_imgs = [
|
| 192 |
+
transforms.Resize(target_size, interpolation=transforms.InterpolationMode.NEAREST)(Image.open(p))
|
| 193 |
+
for p in pca_paths
|
| 194 |
+
]
|
| 195 |
+
|
| 196 |
+
fig, axes = plt.subplots(1, 4, figsize=(20, 6))
|
| 197 |
+
axes[0].imshow(vis_img1)
|
| 198 |
+
axes[0].set_title('Image')
|
| 199 |
+
axes[0].axis('off')
|
| 200 |
+
for i in range(3):
|
| 201 |
+
axes[i+1].imshow(pca_imgs[i])
|
| 202 |
+
axes[i+1].set_title(pca_titles[i])
|
| 203 |
+
axes[i+1].axis('off')
|
| 204 |
+
|
| 205 |
+
plt.tight_layout()
|
| 206 |
+
plt.savefig(os.path.join(output_dir, "pca_vis.png"))
|
| 207 |
+
plt.close(fig)
|
analysis/model_vis_tools/vis_sd_featsv5.1.py
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
from diffusion_model.stable_diffusion import diffusion
|
| 3 |
+
import torch
|
| 4 |
+
import numpy as np
|
| 5 |
+
import os
|
| 6 |
+
from PIL import Image
|
| 7 |
+
from pycocotools.coco import COCO
|
| 8 |
+
from torchvision.transforms import Normalize, Compose, RandomResizedCrop, InterpolationMode, ToTensor, Resize, \
|
| 9 |
+
CenterCrop
|
| 10 |
+
from open_clip.transform import ResizeLongest, _convert_to_rgb
|
| 11 |
+
from torchvision import transforms
|
| 12 |
+
import matplotlib.pyplot as plt
|
| 13 |
+
import cv2
|
| 14 |
+
from functools import reduce
|
| 15 |
+
import torch.nn.functional as F
|
| 16 |
+
from open_clip.factory import create_model
|
| 17 |
+
|
| 18 |
+
# ! 可视化DINO和openai CLIP的余弦相似度
|
| 19 |
+
def build_DINOv2():
|
| 20 |
+
model_name='dinov2_vitb14_reg'
|
| 21 |
+
hub_path = '/mnt/SSD8T/home/wjj/.cache/torch/hub/facebookresearch_dinov2_main'
|
| 22 |
+
try:
|
| 23 |
+
vfm = torch.hub.load(hub_path, model_name, source='local').half()
|
| 24 |
+
except Exception as e:
|
| 25 |
+
raise RuntimeError(f"Failed to load DINOv2 model '{model_name}': {e}")
|
| 26 |
+
return vfm
|
| 27 |
+
|
| 28 |
+
def visualize_sd_dino_clip_att(
|
| 29 |
+
ori_img, sim_dino, sim_clip, token_choosen, output_path, attn_map_hw=(35, 35), vis_hw=(560, 560)
|
| 30 |
+
):
|
| 31 |
+
"""
|
| 32 |
+
Visualize the original image and the cosine similarity maps for both DINO and CLIP.
|
| 33 |
+
Token chosen is highlighted with a smaller red dot in all visualizations.
|
| 34 |
+
|
| 35 |
+
:param ori_img: Input image (PIL.Image, numpy.ndarray, or torch.Tensor)
|
| 36 |
+
:param sim_dino: Cosine similarity matrix from DINO (shape [H*W, H*W])
|
| 37 |
+
:param sim_clip: Cosine similarity matrix from CLIP (shape [H*W, H*W])
|
| 38 |
+
:param token_choosen: Token coordinate (row, col)
|
| 39 |
+
:param output_path: Path to save the visualization
|
| 40 |
+
:param attn_map_hw: Attention map resolution (H, W)
|
| 41 |
+
:param vis_hw: Visualization resolution (H, W)
|
| 42 |
+
"""
|
| 43 |
+
# 1. Preprocess the original image
|
| 44 |
+
if isinstance(ori_img, torch.Tensor):
|
| 45 |
+
img = ori_img
|
| 46 |
+
if img.ndim == 4: # [1,3,H,W] -> [3,H,W]
|
| 47 |
+
img = img[0]
|
| 48 |
+
img = img.cpu().numpy()
|
| 49 |
+
img = np.transpose(img, (1, 2, 0)) # [H, W, 3]
|
| 50 |
+
img = (img * 255).clip(0, 255).astype(np.uint8)
|
| 51 |
+
elif isinstance(ori_img, Image.Image):
|
| 52 |
+
img = np.array(ori_img)
|
| 53 |
+
if img.dtype != np.uint8:
|
| 54 |
+
img = (img * 255).clip(0, 255).astype(np.uint8)
|
| 55 |
+
elif isinstance(ori_img, np.ndarray):
|
| 56 |
+
img = ori_img
|
| 57 |
+
if img.dtype != np.uint8:
|
| 58 |
+
img = (img * 255).clip(0, 255).astype(np.uint8)
|
| 59 |
+
else:
|
| 60 |
+
raise ValueError("ori_img should be torch.Tensor, PIL.Image, or np.ndarray")
|
| 61 |
+
if img.shape[2] == 4: # RGBA to RGB
|
| 62 |
+
img = img[:, :, :3]
|
| 63 |
+
img_resized = cv2.resize(img, vis_hw, interpolation=cv2.INTER_LINEAR)
|
| 64 |
+
|
| 65 |
+
# 2. Token coordinates
|
| 66 |
+
h_attn, w_attn = attn_map_hw
|
| 67 |
+
row, col = token_choosen
|
| 68 |
+
y_vis = int((row + 0.5) * vis_hw[0] / h_attn)
|
| 69 |
+
x_vis = int((col + 0.5) * vis_hw[1] / w_attn)
|
| 70 |
+
|
| 71 |
+
img_with_dot = img_resized.copy()
|
| 72 |
+
cv2.circle(img_with_dot, (x_vis, y_vis), radius=8, color=(0, 0, 0), thickness=-1) # Smaller black circle
|
| 73 |
+
cv2.circle(img_with_dot, (x_vis, y_vis), radius=6, color=(255, 0, 0), thickness=-1) # Smaller red circle
|
| 74 |
+
|
| 75 |
+
# 3. Process DINO similarity map
|
| 76 |
+
dino_att_map = sim_dino[row * w_attn + col].to(torch.float32).detach().cpu().numpy().reshape(h_attn, w_attn)
|
| 77 |
+
dino_att_map = (dino_att_map - dino_att_map.min()) / (dino_att_map.max() - dino_att_map.min() + 1e-8)
|
| 78 |
+
dino_att_map_up = cv2.resize(dino_att_map, vis_hw, interpolation=cv2.INTER_LINEAR)
|
| 79 |
+
|
| 80 |
+
# Enhance contrast for DINO similarity map
|
| 81 |
+
dino_att_map_up = (dino_att_map_up ** 0.5) # Apply gamma correction for better contrast
|
| 82 |
+
dino_overlay = (img_resized * 0.3 + (plt.cm.jet(dino_att_map_up)[:, :, :3] * 255).astype(np.uint8) * 0.7).astype(np.uint8)
|
| 83 |
+
cv2.circle(dino_overlay, (x_vis, y_vis), radius=8, color=(0, 0, 0), thickness=-1) # Smaller black circle
|
| 84 |
+
cv2.circle(dino_overlay, (x_vis, y_vis), radius=6, color=(255, 0, 0), thickness=-1) # Smaller red circle
|
| 85 |
+
|
| 86 |
+
# 4. Process CLIP similarity map
|
| 87 |
+
clip_att_map = sim_clip[row * w_attn + col].to(torch.float32).detach().cpu().numpy().reshape(h_attn, w_attn)
|
| 88 |
+
clip_att_map = (clip_att_map - clip_att_map.min()) / (clip_att_map.max() - clip_att_map.min() + 1e-8)
|
| 89 |
+
clip_att_map_up = cv2.resize(clip_att_map, vis_hw, interpolation=cv2.INTER_LINEAR)
|
| 90 |
+
|
| 91 |
+
# Enhance contrast for CLIP similarity map
|
| 92 |
+
clip_att_map_up = (clip_att_map_up ** 0.5) # Apply gamma correction for better contrast
|
| 93 |
+
clip_overlay = (img_resized * 0.3 + (plt.cm.jet(clip_att_map_up)[:, :, :3] * 255).astype(np.uint8) * 0.7).astype(np.uint8)
|
| 94 |
+
cv2.circle(clip_overlay, (x_vis, y_vis), radius=8, color=(0, 0, 0), thickness=-1) # Smaller black circle
|
| 95 |
+
cv2.circle(clip_overlay, (x_vis, y_vis), radius=6, color=(255, 0, 0), thickness=-1) # Smaller red circle
|
| 96 |
+
|
| 97 |
+
# 5. Combine all images into a single row
|
| 98 |
+
combined_img = np.concatenate([img_with_dot, dino_overlay, clip_overlay], axis=1)
|
| 99 |
+
|
| 100 |
+
# 6. Save the visualization
|
| 101 |
+
plt.figure(figsize=(18, 6))
|
| 102 |
+
plt.imshow(combined_img)
|
| 103 |
+
plt.axis('off')
|
| 104 |
+
plt.title("Original | DINO Cosine Similarity | CLIP Cosine Similarity")
|
| 105 |
+
plt.tight_layout()
|
| 106 |
+
plt.savefig(output_path, dpi=200, bbox_inches='tight')
|
| 107 |
+
plt.close()
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
with torch.no_grad():
|
| 111 |
+
device="cuda:0"
|
| 112 |
+
dino=build_DINOv2().to(device)
|
| 113 |
+
clip = create_model('ViT-B-16', 'openai', device=device, precision="amp").eval().to(device).half()
|
| 114 |
+
image = Image.open("demo_images/bird.jpg")
|
| 115 |
+
dino_mean=[0.485, 0.456, 0.406]
|
| 116 |
+
dino_std=[0.229, 0.224, 0.225]
|
| 117 |
+
clip_mean = [0.48145466, 0.4578275, 0.40821073]
|
| 118 |
+
clip_std = [0.26862954, 0.26130258, 0.27577711]
|
| 119 |
+
DINO_transform = Compose([Resize((196, 196)),_convert_to_rgb,ToTensor(),Normalize(mean=dino_mean, std=dino_std)])
|
| 120 |
+
clip_transform=Compose([Resize((224, 224)),_convert_to_rgb,ToTensor(),Normalize(mean=clip_mean, std=clip_std)])
|
| 121 |
+
img_transform=Compose([Resize((224, 224)),_convert_to_rgb,])
|
| 122 |
+
dino_img = DINO_transform(image).unsqueeze(0).to(torch.float16).to(device)
|
| 123 |
+
clip_img = clip_transform(image).unsqueeze(0).to(torch.float16).to(device)
|
| 124 |
+
vis_img=img_transform(image)
|
| 125 |
+
# dino_feats_raw=dino.get_intermediate_layers(dino_img, reshape=True)[0].flatten(start_dim=-2).transpose(-2,-1)
|
| 126 |
+
dino_feats_raw=dino.get_intermediate_layers(dino_img, reshape=True)[0].flatten(start_dim=-2).transpose(-2,-1)
|
| 127 |
+
dino_feats = F.normalize(dino_feats_raw, dim=2)
|
| 128 |
+
sim_dino = torch.einsum('bic,bjc->bij', dino_feats, dino_feats).squeeze(0)
|
| 129 |
+
del dino
|
| 130 |
+
del dino_feats_raw
|
| 131 |
+
del dino_feats
|
| 132 |
+
clip_feats=clip.encode_dense(clip_img,mode="vanilla",normalize=True)
|
| 133 |
+
del clip
|
| 134 |
+
sim_clip = torch.einsum('bic,bjc->bij', clip_feats, clip_feats).squeeze(0)
|
| 135 |
+
del clip_feats
|
| 136 |
+
output_dir = "clip_dino_vis"
|
| 137 |
+
if not os.path.exists(output_dir):
|
| 138 |
+
os.mkdir(output_dir)
|
| 139 |
+
|
| 140 |
+
token_choosen=(7, 7)
|
| 141 |
+
|
| 142 |
+
visualize_sd_dino_clip_att(
|
| 143 |
+
ori_img=vis_img, # Original image
|
| 144 |
+
sim_dino=sim_dino, # DINO cosine similarity
|
| 145 |
+
sim_clip=sim_clip, # CLIP cosine similarity
|
| 146 |
+
token_choosen=token_choosen, # Token of interest
|
| 147 |
+
output_path=os.path.join(output_dir, "vis_combined.png"), # Output file
|
| 148 |
+
attn_map_hw=(14, 14), # Attention map resolution
|
| 149 |
+
vis_hw=(224, 224) # Visualization resolution
|
| 150 |
+
)
|
analysis/model_vis_tools/vis_sd_featsv5.py
ADDED
|
@@ -0,0 +1,262 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
from diffusion_model.stable_diffusion import diffusion
|
| 3 |
+
import torch
|
| 4 |
+
import numpy as np
|
| 5 |
+
import os
|
| 6 |
+
from PIL import Image
|
| 7 |
+
from pycocotools.coco import COCO
|
| 8 |
+
from torchvision.transforms import Normalize, Compose, RandomResizedCrop, InterpolationMode, ToTensor, Resize, \
|
| 9 |
+
CenterCrop
|
| 10 |
+
from open_clip.transform import ResizeLongest, _convert_to_rgb
|
| 11 |
+
from torchvision import transforms
|
| 12 |
+
import matplotlib.pyplot as plt
|
| 13 |
+
import cv2
|
| 14 |
+
from functools import reduce
|
| 15 |
+
import torch.nn.functional as F
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class SDNormalize(object):
|
| 19 |
+
def __call__(self, img):
|
| 20 |
+
return 2.0 * img - 1.0
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def build_DINOv2():
|
| 24 |
+
model_name='dinov2_vitb14_reg'
|
| 25 |
+
hub_path = '/mnt/SSD8T/home/wjj/.cache/torch/hub/facebookresearch_dinov2_main'
|
| 26 |
+
try:
|
| 27 |
+
vfm = torch.hub.load(hub_path, model_name, source='local').half()
|
| 28 |
+
except Exception as e:
|
| 29 |
+
raise RuntimeError(f"Failed to load DINOv2 model '{model_name}': {e}")
|
| 30 |
+
return vfm
|
| 31 |
+
|
| 32 |
+
def visualize_self_att_raw(
|
| 33 |
+
ori_img, self_att_raw, token_choosen, output_dir, attn_map_hw=(35, 35), vis_hw=(560, 560)
|
| 34 |
+
):
|
| 35 |
+
"""
|
| 36 |
+
可视化self_att_raw中所有注意力图的token choosen位置的结果。
|
| 37 |
+
每幅图单独保存。
|
| 38 |
+
:param ori_img: 输入图像
|
| 39 |
+
:param self_att_raw: 原始注意力图,形状[10, 1225, 1225]
|
| 40 |
+
:param token_choosen: 选择的token坐标 (row, col)
|
| 41 |
+
:param output_dir: 输出文件名前缀
|
| 42 |
+
:param attn_map_hw: 注意力图的分辨率 (H, W)
|
| 43 |
+
:param vis_hw: 可视化图像的分辨率 (H, W)
|
| 44 |
+
"""
|
| 45 |
+
# 1. 原图
|
| 46 |
+
if isinstance(ori_img, torch.Tensor):
|
| 47 |
+
img = ori_img
|
| 48 |
+
if img.ndim == 4: # [1,3,H,W] -> [3,H,W]
|
| 49 |
+
img = img[0]
|
| 50 |
+
img = img.cpu().numpy()
|
| 51 |
+
img = np.transpose(img, (1, 2, 0)) # [H, W, 3]
|
| 52 |
+
img = (img * 255).clip(0, 255).astype(np.uint8)
|
| 53 |
+
elif isinstance(ori_img, Image.Image):
|
| 54 |
+
img = np.array(ori_img)
|
| 55 |
+
if img.dtype != np.uint8:
|
| 56 |
+
img = (img * 255).clip(0, 255).astype(np.uint8)
|
| 57 |
+
elif isinstance(ori_img, np.ndarray):
|
| 58 |
+
img = ori_img
|
| 59 |
+
if img.dtype != np.uint8:
|
| 60 |
+
img = (img * 255).clip(0, 255).astype(np.uint8)
|
| 61 |
+
else:
|
| 62 |
+
raise ValueError("ori_img should be torch.Tensor, PIL.Image, or np.ndarray")
|
| 63 |
+
if img.shape[2] == 4: # RGBA to RGB
|
| 64 |
+
img = img[:, :, :3]
|
| 65 |
+
img_resized = cv2.resize(img, vis_hw, interpolation=cv2.INTER_LINEAR)
|
| 66 |
+
|
| 67 |
+
# 2. token坐标
|
| 68 |
+
h_attn, w_attn = attn_map_hw
|
| 69 |
+
row, col = token_choosen
|
| 70 |
+
y_vis = int((row + 0.5) * vis_hw[0] / h_attn)
|
| 71 |
+
x_vis = int((col + 0.5) * vis_hw[1] / w_attn)
|
| 72 |
+
|
| 73 |
+
img_with_dot = img_resized.copy()
|
| 74 |
+
cv2.circle(img_with_dot, (x_vis, y_vis), radius=13, color=(0, 0, 0), thickness=-1) # 黑色圆
|
| 75 |
+
cv2.circle(img_with_dot, (x_vis, y_vis), radius=11, color=(255, 0, 0), thickness=-1) # 红色圆
|
| 76 |
+
|
| 77 |
+
# 3. 遍历 self_att_raw
|
| 78 |
+
num_layers = self_att_raw.shape[0]
|
| 79 |
+
for i in range(num_layers):
|
| 80 |
+
layer_att_map = self_att_raw[i, row * w_attn + col].to(torch.float32).detach().cpu().numpy().reshape(h_attn, w_attn)
|
| 81 |
+
layer_att_map = (layer_att_map - layer_att_map.min()) / (layer_att_map.max() - layer_att_map.min() + 1e-8)
|
| 82 |
+
layer_att_map_up = cv2.resize(layer_att_map, vis_hw, interpolation=cv2.INTER_LINEAR)
|
| 83 |
+
|
| 84 |
+
# 绘制图像
|
| 85 |
+
fig, axs = plt.subplots(1, 2, figsize=(12, 6))
|
| 86 |
+
axs[0].imshow(img_with_dot)
|
| 87 |
+
axs[0].set_title(f"Original (with token) - Layer {i}")
|
| 88 |
+
axs[0].axis('off')
|
| 89 |
+
|
| 90 |
+
axs[1].imshow(layer_att_map_up, cmap='jet')
|
| 91 |
+
axs[1].set_title(f"Self-Attention (Layer {i})")
|
| 92 |
+
axs[1].axis('off')
|
| 93 |
+
|
| 94 |
+
plt.tight_layout()
|
| 95 |
+
|
| 96 |
+
# 保存每一层的可视化结果
|
| 97 |
+
output_path = os.path.join(output_dir,f"layer_{i}.png")
|
| 98 |
+
plt.savefig(output_path, dpi=200, bbox_inches='tight')
|
| 99 |
+
plt.close()
|
| 100 |
+
|
| 101 |
+
def visualize_sd_dino_att(
|
| 102 |
+
ori_img, self_att, sim_dino_soft, sim_dino_refined,
|
| 103 |
+
token_choosen, filename, attn_map_hw=(64, 64), vis_hw=(512, 512)
|
| 104 |
+
):
|
| 105 |
+
"""
|
| 106 |
+
可视化SD传播对DINO自相关的细化效果, 4列分别为:
|
| 107 |
+
1. 原图带token
|
| 108 |
+
2. SD自注意力传播
|
| 109 |
+
3. DINO自相关
|
| 110 |
+
4. 细化后的DINO自相关
|
| 111 |
+
"""
|
| 112 |
+
# 1. 原图
|
| 113 |
+
# 支持PIL.Image、np.ndarray、tensor三种输入
|
| 114 |
+
if isinstance(ori_img, torch.Tensor):
|
| 115 |
+
img = ori_img
|
| 116 |
+
if img.ndim == 4: # [1,3,H,W] -> [3,H,W]
|
| 117 |
+
img = img[0]
|
| 118 |
+
img = img.cpu().numpy()
|
| 119 |
+
img = np.transpose(img, (1, 2, 0)) # [H, W, 3]
|
| 120 |
+
img = (img * 255).clip(0, 255).astype(np.uint8)
|
| 121 |
+
elif isinstance(ori_img, Image.Image):
|
| 122 |
+
img = np.array(ori_img)
|
| 123 |
+
if img.dtype != np.uint8:
|
| 124 |
+
img = (img * 255).clip(0, 255).astype(np.uint8)
|
| 125 |
+
elif isinstance(ori_img, np.ndarray):
|
| 126 |
+
img = ori_img
|
| 127 |
+
if img.dtype != np.uint8:
|
| 128 |
+
img = (img * 255).clip(0, 255).astype(np.uint8)
|
| 129 |
+
else:
|
| 130 |
+
raise ValueError("ori_img should be torch.Tensor, PIL.Image, or np.ndarray")
|
| 131 |
+
if img.shape[2] == 4: # RGBA to RGB
|
| 132 |
+
img = img[:, :, :3]
|
| 133 |
+
img_resized = cv2.resize(img, vis_hw, interpolation=cv2.INTER_LINEAR)
|
| 134 |
+
|
| 135 |
+
# 2. token坐标
|
| 136 |
+
h_attn, w_attn = attn_map_hw
|
| 137 |
+
row, col = token_choosen
|
| 138 |
+
y_vis = int((row + 0.5) * vis_hw[0] / h_attn)
|
| 139 |
+
x_vis = int((col + 0.5) * vis_hw[1] / w_attn)
|
| 140 |
+
img_with_dot = img_resized.copy()
|
| 141 |
+
# 绘制黑色边缘的圆
|
| 142 |
+
cv2.circle(img_with_dot, (x_vis, y_vis), radius=13, color=(0, 0, 0), thickness=-1) # 黑色圆
|
| 143 |
+
|
| 144 |
+
# 绘制红点
|
| 145 |
+
cv2.circle(img_with_dot, (x_vis, y_vis), radius=11, color=(255, 0, 0), thickness=-1) # 红色圆
|
| 146 |
+
|
| 147 |
+
# 3. SD自注意力传播
|
| 148 |
+
att_map_sd = self_att[row * w_attn + col].to(torch.float32).detach().cpu().numpy().reshape(h_attn, w_attn)
|
| 149 |
+
att_map_sd = (att_map_sd - att_map_sd.min()) / (att_map_sd.max() - att_map_sd.min() + 1e-8)
|
| 150 |
+
att_map_sd_up = cv2.resize(att_map_sd, vis_hw, interpolation=cv2.INTER_LINEAR)
|
| 151 |
+
|
| 152 |
+
# 4. DINO自相关(传播前)
|
| 153 |
+
att_map_dino = sim_dino_soft[row * w_attn + col].detach().cpu().numpy().reshape(h_attn, w_attn)
|
| 154 |
+
att_map_dino = (att_map_dino - att_map_dino.min()) / (att_map_dino.max() - att_map_dino.min() + 1e-8)
|
| 155 |
+
att_map_dino = att_map_dino.astype(np.float32)
|
| 156 |
+
att_map_dino_up = cv2.resize(att_map_dino, vis_hw, interpolation=cv2.INTER_LINEAR)
|
| 157 |
+
|
| 158 |
+
# 5. DINO传播后
|
| 159 |
+
att_map_dino_ref = sim_dino_refined[row * w_attn + col].detach().cpu().numpy().reshape(h_attn, w_attn)
|
| 160 |
+
att_map_dino_ref = (att_map_dino_ref - att_map_dino_ref.min()) / (att_map_dino_ref.max() - att_map_dino_ref.min() + 1e-8)
|
| 161 |
+
att_map_dino_ref = att_map_dino_ref.astype(np.float32)
|
| 162 |
+
att_map_dino_ref_up = cv2.resize(att_map_dino_ref, vis_hw, interpolation=cv2.INTER_LINEAR)
|
| 163 |
+
|
| 164 |
+
# 6. 绘图
|
| 165 |
+
fig, axs = plt.subplots(1, 4, figsize=(18, 5))
|
| 166 |
+
|
| 167 |
+
axs[0].imshow(img_with_dot)
|
| 168 |
+
axs[0].set_title("Original (with token)")
|
| 169 |
+
axs[0].axis('off')
|
| 170 |
+
|
| 171 |
+
axs[1].imshow(att_map_sd_up, cmap='jet')
|
| 172 |
+
axs[1].set_title(f'SD propagation (token {token_choosen})')
|
| 173 |
+
axs[1].axis('off')
|
| 174 |
+
|
| 175 |
+
axs[2].imshow(att_map_dino_up, cmap='jet')
|
| 176 |
+
axs[2].set_title(f'DINO sim (pre-propagate)')
|
| 177 |
+
axs[2].axis('off')
|
| 178 |
+
|
| 179 |
+
axs[3].imshow(att_map_dino_ref_up, cmap='jet')
|
| 180 |
+
axs[3].set_title(f'DINO sim (post-propagate)')
|
| 181 |
+
axs[3].axis('off')
|
| 182 |
+
|
| 183 |
+
plt.tight_layout()
|
| 184 |
+
plt.savefig(filename, dpi=200, bbox_inches='tight')
|
| 185 |
+
plt.close()
|
| 186 |
+
|
| 187 |
+
with torch.no_grad():
|
| 188 |
+
attention_layers_to_use= [-4, -6]
|
| 189 |
+
sd_version='v2.1'
|
| 190 |
+
time_step=45
|
| 191 |
+
device="cuda:6"
|
| 192 |
+
# coco_path='/mnt/SSD8T/home/wjj/dataset/standard_coco/annotations/instances_train2017.json'
|
| 193 |
+
# img_path='/mnt/SSD8T/home/wjj/dataset/standard_coco/train2017'
|
| 194 |
+
|
| 195 |
+
# coco=COCO(coco_path)
|
| 196 |
+
# image_ids=load_data(coco)
|
| 197 |
+
dino=build_DINOv2().to(device)
|
| 198 |
+
sd=diffusion(attention_layers_to_use=attention_layers_to_use,model=sd_version, time_step=time_step, device=device,dtype=torch.float16)
|
| 199 |
+
# image_select=5
|
| 200 |
+
# img_name = coco.loadImgs(image_ids[image_select])[0]['file_name']
|
| 201 |
+
# image_path = os.path.join(img_path, img_name)
|
| 202 |
+
image_root='/mnt/SSD8T/home/wjj/dataset/standard_coco/train2017'
|
| 203 |
+
image_file=os.listdir(image_root)[999]
|
| 204 |
+
image_name=os.path.join(image_root, image_file)
|
| 205 |
+
# image = Image.open('demo_images/horses.jpg')
|
| 206 |
+
image = Image.open("demo_images/bird.jpg")
|
| 207 |
+
mean=[0.485, 0.456, 0.406]
|
| 208 |
+
std=[0.229, 0.224, 0.225]
|
| 209 |
+
|
| 210 |
+
normalize = Normalize(mean=mean, std=std)
|
| 211 |
+
DINO_transform=transforms.Compose([
|
| 212 |
+
ResizeLongest(490, fill=0),
|
| 213 |
+
_convert_to_rgb,
|
| 214 |
+
ToTensor(),
|
| 215 |
+
normalize])
|
| 216 |
+
sd_transform=transforms.Compose([ResizeLongest(560, fill=0), _convert_to_rgb,ToTensor(), SDNormalize()])
|
| 217 |
+
img_transform=transforms.Compose([ResizeLongest(560, fill=0)])
|
| 218 |
+
dino_img=DINO_transform(image).unsqueeze(0).to(torch.float16).to(device)
|
| 219 |
+
sd_img = sd_transform(image).unsqueeze(0).to(torch.float16).to(device)
|
| 220 |
+
|
| 221 |
+
# dino_feats_raw=dino.get_intermediate_layers(dino_img, reshape=True)[0].flatten(start_dim=-2).transpose(-2,-1)
|
| 222 |
+
dino_feats_raw=dino.get_intermediate_layers(dino_img, reshape=True)[0].flatten(start_dim=-2).transpose(-2,-1)
|
| 223 |
+
dino_feats = F.normalize(dino_feats_raw, dim=2)
|
| 224 |
+
sim_dino = torch.einsum('bic,bjc->bij', dino_feats, dino_feats).squeeze(0)
|
| 225 |
+
# sd preprocess
|
| 226 |
+
# 1.
|
| 227 |
+
sd.forward_wo_preprocess(sd_img, "")
|
| 228 |
+
vis_img=img_transform(image)
|
| 229 |
+
self_att_raw = torch.cat([sd.attention_maps[idx] for idx in attention_layers_to_use]).float()
|
| 230 |
+
|
| 231 |
+
self_att = self_att_raw / torch.amax(self_att_raw, dim=-2, keepdim=True) + 1e-5
|
| 232 |
+
self_att = torch.where(self_att < 0.2, 0, self_att)
|
| 233 |
+
self_att /= self_att.sum(dim=-1, keepdim=True) + 1e-5
|
| 234 |
+
self_att = reduce(torch.matmul, self_att, torch.eye(self_att.shape[-1], device=self_att.device)).to(sim_dino.dtype)
|
| 235 |
+
refined_sim_dino = self_att @ sim_dino @ self_att.transpose(0, 1)
|
| 236 |
+
alpha = 0.8
|
| 237 |
+
refined_sim_dino = (1 - alpha) * sim_dino + alpha * refined_sim_dino
|
| 238 |
+
|
| 239 |
+
output_dir = "sd_vis"
|
| 240 |
+
if not os.path.exists(output_dir):
|
| 241 |
+
os.mkdir(output_dir)
|
| 242 |
+
|
| 243 |
+
token_choosen=(12, 20)
|
| 244 |
+
|
| 245 |
+
visualize_sd_dino_att(
|
| 246 |
+
ori_img=vis_img, # [1,3,H,W],归一化 0-1 float
|
| 247 |
+
self_att=self_att, # (4096,4096)
|
| 248 |
+
sim_dino_soft=sim_dino, # (4096,4096)
|
| 249 |
+
sim_dino_refined=refined_sim_dino, # (4096,4096)
|
| 250 |
+
token_choosen=token_choosen,
|
| 251 |
+
filename=os.path.join(output_dir, f"vis.png"),
|
| 252 |
+
attn_map_hw=(35, 35),
|
| 253 |
+
vis_hw=(560, 560)
|
| 254 |
+
)
|
| 255 |
+
visualize_self_att_raw(
|
| 256 |
+
ori_img=vis_img,
|
| 257 |
+
self_att_raw=self_att_raw,
|
| 258 |
+
token_choosen=token_choosen,
|
| 259 |
+
output_dir=output_dir,
|
| 260 |
+
attn_map_hw=(35, 35),
|
| 261 |
+
vis_hw=(560, 560)
|
| 262 |
+
)
|
analysis/model_vis_tools/vis_sd_featsv6.py
ADDED
|
@@ -0,0 +1,161 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
import h5py
|
| 3 |
+
from diffusion_model.stable_diffusion import diffusion
|
| 4 |
+
import torch
|
| 5 |
+
import numpy as np
|
| 6 |
+
import os
|
| 7 |
+
from PIL import Image
|
| 8 |
+
from pycocotools.coco import COCO
|
| 9 |
+
from torchvision.transforms import Normalize, Compose, RandomResizedCrop, InterpolationMode, ToTensor, Resize, \
|
| 10 |
+
CenterCrop
|
| 11 |
+
from open_clip.transform import ResizeLongest, _convert_to_rgb
|
| 12 |
+
from torchvision import transforms
|
| 13 |
+
import matplotlib.pyplot as plt
|
| 14 |
+
import cv2
|
| 15 |
+
from functools import reduce
|
| 16 |
+
import torch.nn.functional as F
|
| 17 |
+
|
| 18 |
+
def build_DINOv2():
|
| 19 |
+
model_name='dinov2_vitb14_reg'
|
| 20 |
+
hub_path = '/mnt/SSD8T/home/wjj/.cache/torch/hub/facebookresearch_dinov2_main'
|
| 21 |
+
try:
|
| 22 |
+
vfm = torch.hub.load(hub_path, model_name, source='local').half()
|
| 23 |
+
except Exception as e:
|
| 24 |
+
raise RuntimeError(f"Failed to load DINOv2 model '{model_name}': {e}")
|
| 25 |
+
return vfm
|
| 26 |
+
|
| 27 |
+
def visualize_sd_dino_att(
|
| 28 |
+
ori_img, self_att, sim_dino_soft, sim_dino_refined,
|
| 29 |
+
token_choosen, filename, attn_map_hw=(64, 64), vis_hw=(512, 512)
|
| 30 |
+
):
|
| 31 |
+
"""
|
| 32 |
+
可视化SD传播对DINO自相关的细化效果, 4列分别为:
|
| 33 |
+
1. 原图带token
|
| 34 |
+
2. SD自注意力传播
|
| 35 |
+
3. DINO自相关
|
| 36 |
+
4. 细化后的DINO自相关
|
| 37 |
+
"""
|
| 38 |
+
# 1. 原图
|
| 39 |
+
# 支持PIL.Image、np.ndarray、tensor三种输入
|
| 40 |
+
if isinstance(ori_img, torch.Tensor):
|
| 41 |
+
img = ori_img
|
| 42 |
+
if img.ndim == 4: # [1,3,H,W] -> [3,H,W]
|
| 43 |
+
img = img[0]
|
| 44 |
+
img = img.cpu().numpy()
|
| 45 |
+
img = np.transpose(img, (1, 2, 0)) # [H, W, 3]
|
| 46 |
+
img = (img * 255).clip(0, 255).astype(np.uint8)
|
| 47 |
+
elif isinstance(ori_img, Image.Image):
|
| 48 |
+
img = np.array(ori_img)
|
| 49 |
+
if img.dtype != np.uint8:
|
| 50 |
+
img = (img * 255).clip(0, 255).astype(np.uint8)
|
| 51 |
+
elif isinstance(ori_img, np.ndarray):
|
| 52 |
+
img = ori_img
|
| 53 |
+
if img.dtype != np.uint8:
|
| 54 |
+
img = (img * 255).clip(0, 255).astype(np.uint8)
|
| 55 |
+
else:
|
| 56 |
+
raise ValueError("ori_img should be torch.Tensor, PIL.Image, or np.ndarray")
|
| 57 |
+
if img.shape[2] == 4: # RGBA to RGB
|
| 58 |
+
img = img[:, :, :3]
|
| 59 |
+
img_resized = cv2.resize(img, vis_hw, interpolation=cv2.INTER_LINEAR)
|
| 60 |
+
|
| 61 |
+
# 2. token坐标
|
| 62 |
+
h_attn, w_attn = attn_map_hw
|
| 63 |
+
row, col = token_choosen
|
| 64 |
+
y_vis = int((row + 0.5) * vis_hw[0] / h_attn)
|
| 65 |
+
x_vis = int((col + 0.5) * vis_hw[1] / w_attn)
|
| 66 |
+
img_with_dot = img_resized.copy()
|
| 67 |
+
cv2.circle(img_with_dot, (x_vis, y_vis), radius=7, color=(255,0,0), thickness=-1) # 红点
|
| 68 |
+
|
| 69 |
+
# 3. SD自注意力传播
|
| 70 |
+
att_map_sd = self_att[row * w_attn + col].to(torch.float32).detach().cpu().numpy().reshape(h_attn, w_attn)
|
| 71 |
+
att_map_sd = (att_map_sd - att_map_sd.min()) / (att_map_sd.max() - att_map_sd.min() + 1e-8)
|
| 72 |
+
att_map_sd_up = cv2.resize(att_map_sd, vis_hw, interpolation=cv2.INTER_LINEAR)
|
| 73 |
+
|
| 74 |
+
# 4. DINO自相关(传播前)
|
| 75 |
+
att_map_dino = sim_dino_soft[row * w_attn + col].detach().cpu().numpy().reshape(h_attn, w_attn)
|
| 76 |
+
att_map_dino = (att_map_dino - att_map_dino.min()) / (att_map_dino.max() - att_map_dino.min() + 1e-8)
|
| 77 |
+
att_map_dino = att_map_dino.astype(np.float32)
|
| 78 |
+
att_map_dino_up = cv2.resize(att_map_dino, vis_hw, interpolation=cv2.INTER_LINEAR)
|
| 79 |
+
|
| 80 |
+
# 5. DINO传播后
|
| 81 |
+
att_map_dino_ref = sim_dino_refined[row * w_attn + col].detach().cpu().numpy().reshape(h_attn, w_attn)
|
| 82 |
+
att_map_dino_ref = (att_map_dino_ref - att_map_dino_ref.min()) / (att_map_dino_ref.max() - att_map_dino_ref.min() + 1e-8)
|
| 83 |
+
att_map_dino_ref = att_map_dino_ref.astype(np.float32)
|
| 84 |
+
att_map_dino_ref_up = cv2.resize(att_map_dino_ref, vis_hw, interpolation=cv2.INTER_LINEAR)
|
| 85 |
+
|
| 86 |
+
# 6. 绘图
|
| 87 |
+
fig, axs = plt.subplots(1, 4, figsize=(18, 5))
|
| 88 |
+
|
| 89 |
+
axs[0].imshow(img_with_dot)
|
| 90 |
+
axs[0].set_title("Original (with token)")
|
| 91 |
+
axs[0].axis('off')
|
| 92 |
+
|
| 93 |
+
axs[1].imshow(att_map_sd_up, cmap='jet')
|
| 94 |
+
axs[1].set_title(f'SD propagation (token {token_choosen})')
|
| 95 |
+
axs[1].axis('off')
|
| 96 |
+
|
| 97 |
+
axs[2].imshow(att_map_dino_up, cmap='jet')
|
| 98 |
+
axs[2].set_title(f'DINO sim (pre-propagate)')
|
| 99 |
+
axs[2].axis('off')
|
| 100 |
+
|
| 101 |
+
axs[3].imshow(att_map_dino_ref_up, cmap='jet')
|
| 102 |
+
axs[3].set_title(f'DINO sim (post-propagate)')
|
| 103 |
+
axs[3].axis('off')
|
| 104 |
+
|
| 105 |
+
plt.tight_layout()
|
| 106 |
+
plt.savefig(filename, dpi=200, bbox_inches='tight')
|
| 107 |
+
plt.close()
|
| 108 |
+
|
| 109 |
+
attention_layers_to_use= [-4, -6]
|
| 110 |
+
sd_version='v2.1'
|
| 111 |
+
time_step=45
|
| 112 |
+
device="cuda:2"
|
| 113 |
+
dino=build_DINOv2().to(device)
|
| 114 |
+
image_root='/mnt/SSD8T/home/wjj/dataset/standard_coco/train2017'
|
| 115 |
+
cache=h5py.File("/mnt/SSD8T/home/wjj/code/DeCLIP/sd_self_attn_cache/sd_self_attn_coco.h5", 'r', swmr=True)
|
| 116 |
+
image_file=os.listdir(image_root)[5]
|
| 117 |
+
cache_attn=torch.from_numpy(cache[image_file][()]).to(device)
|
| 118 |
+
|
| 119 |
+
image_name=os.path.join(image_root, image_file)
|
| 120 |
+
# image = Image.open('demo_images/horses.jpg')
|
| 121 |
+
image = Image.open(image_name)
|
| 122 |
+
mean=[0.485, 0.456, 0.406]
|
| 123 |
+
std=[0.229, 0.224, 0.225]
|
| 124 |
+
|
| 125 |
+
normalize = Normalize(mean=mean, std=std)
|
| 126 |
+
DINO_transform=transforms.Compose([
|
| 127 |
+
ResizeLongest(490, fill=0),
|
| 128 |
+
_convert_to_rgb,
|
| 129 |
+
ToTensor(),
|
| 130 |
+
normalize])
|
| 131 |
+
img_transform=transforms.Compose([ResizeLongest(560, fill=0)])
|
| 132 |
+
dino_img=DINO_transform(image).unsqueeze(0).to(torch.float16).to(device)
|
| 133 |
+
|
| 134 |
+
# dino_feats_raw=dino.get_intermediate_layers(dino_img, reshape=True)[0].flatten(start_dim=-2).transpose(-2,-1)
|
| 135 |
+
dino_feats_raw=dino.get_intermediate_layers(dino_img, reshape=True)[0].flatten(start_dim=-2).transpose(-2,-1)
|
| 136 |
+
dino_feats = F.normalize(dino_feats_raw, dim=2)
|
| 137 |
+
sim_dino = torch.einsum('bic,bjc->bij', dino_feats, dino_feats).squeeze(0)
|
| 138 |
+
self_att=cache_attn.to(sim_dino.dtype)
|
| 139 |
+
refined_sim_dino = self_att @ sim_dino @ self_att.transpose(0, 1)
|
| 140 |
+
# alpha = 0.1 # 你可以把它设置成任意[0,1]的数,逐渐试
|
| 141 |
+
# sim_dino_mixed = (1 - alpha) * sim_dino_softmax + alpha * sim_dino_refined
|
| 142 |
+
|
| 143 |
+
output_dir = "sd_vis"
|
| 144 |
+
if not os.path.exists(output_dir):
|
| 145 |
+
os.mkdir(output_dir)
|
| 146 |
+
|
| 147 |
+
token_choosen=(15, 15)
|
| 148 |
+
vis_img = img_transform(image)
|
| 149 |
+
visualize_sd_dino_att(
|
| 150 |
+
ori_img=vis_img, # [1,3,H,W],归一化 0-1 float
|
| 151 |
+
self_att=self_att, # (4096,4096)
|
| 152 |
+
sim_dino_soft=sim_dino, # (4096,4096)
|
| 153 |
+
sim_dino_refined=refined_sim_dino, # (4096,4096)
|
| 154 |
+
token_choosen=token_choosen,
|
| 155 |
+
filename=os.path.join(output_dir, f"vis.png"),
|
| 156 |
+
attn_map_hw=(35, 35),
|
| 157 |
+
vis_hw=(560, 560)
|
| 158 |
+
)
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
# visualize_sd_self_att(sd_img, self_att, (30,30), os.path.join(output_dir,"vis.png"),)
|
analysis/prompt_ensemble_ablation/configs/fvit_vitb16_ovcoco_clearclip_single_prompt.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# ClearCLIP EVA-B Single Prompt 消融实验配置
|
| 2 |
+
# 使用原始 EVA-CLIP + QQ attention (ClearCLIP方式)
|
| 3 |
+
# feature_mode='qq'
|
| 4 |
+
#
|
| 5 |
+
# 注意:必须设置 force_reload_embed=True
|
| 6 |
+
|
| 7 |
+
custom_imports = dict(
|
| 8 |
+
imports=['datasets', 'models'],
|
| 9 |
+
allow_failed_imports=False
|
| 10 |
+
)
|
| 11 |
+
|
| 12 |
+
_base_ = '../../CLIPSelf/F-ViT/work_dirs/clearclip_ovcoco/fvit_vitb16_upsample_fpn_bs64_3e_ovcoco_clearclip.py'
|
| 13 |
+
|
| 14 |
+
model = dict(
|
| 15 |
+
roi_head=dict(
|
| 16 |
+
bbox_head=dict(
|
| 17 |
+
# 使用 single prompt embedding (消融实验)
|
| 18 |
+
class_embed='/mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/prompt_ensemble_ablation/embeddings/coco_eva02_clip_b_16_eva_single_prompt.pt',
|
| 19 |
+
# 强制从配置文件重新加载 embedding
|
| 20 |
+
force_reload_embed=True,
|
| 21 |
+
),
|
| 22 |
+
),
|
| 23 |
+
)
|
analysis/prompt_ensemble_ablation/configs/fvit_vitb16_ovcoco_declip_ensemble.py
ADDED
|
@@ -0,0 +1,208 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# DeCLIP EVA-B Prompt Ensemble 配置
|
| 2 |
+
# 使用 EVAB_dinov2B_epoch2.pth 检测器权重
|
| 3 |
+
|
| 4 |
+
custom_imports = dict(
|
| 5 |
+
imports=['datasets', 'models'],
|
| 6 |
+
allow_failed_imports=False
|
| 7 |
+
)
|
| 8 |
+
|
| 9 |
+
find_unused_parameters = True
|
| 10 |
+
num_classes = 65
|
| 11 |
+
class_weight = [
|
| 12 |
+
1.0, 1.0, 1.0, 1.0, 0, 0, 1.0, 1.0, 1.0, 1.0, 1.0, 0, 0, 1.0, 1.0, 0, 0,
|
| 13 |
+
1.0, 1.0, 1.0, 1.0, 0, 1.0, 0, 1.0, 1.0, 1.0, 0, 1.0, 0, 1.0, 1.0, 0, 1.0,
|
| 14 |
+
0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0, 1.0, 0, 1.0, 1.0,
|
| 15 |
+
1.0, 1.0, 1.0, 1.0, 0, 1.0, 1.0, 1.0, 0, 1.0, 1.0, 1.0, 1.0, 0, 1.0, 0.6
|
| 16 |
+
]
|
| 17 |
+
norm_cfg = dict(type='SyncBN', requires_grad=True)
|
| 18 |
+
|
| 19 |
+
model = dict(
|
| 20 |
+
type='FViT',
|
| 21 |
+
backbone=dict(
|
| 22 |
+
type='EvaCLIPViT',
|
| 23 |
+
model_name='EVA02-CLIP-B-16',
|
| 24 |
+
pretrained='/opt/tiger/xiaomoguhzz/EVA02_CLIP_B_psz16_s8B.pt',
|
| 25 |
+
norm_cfg=norm_cfg,
|
| 26 |
+
out_indices=[3, 5, 7, 11],
|
| 27 |
+
feature_mode='csa'), # DeCLIP: Q*Q^T + K*K^T, 无 scale, 无残差, 无 MLP
|
| 28 |
+
neck=dict(
|
| 29 |
+
type='FPN',
|
| 30 |
+
in_channels=[768, 768, 768, 768],
|
| 31 |
+
out_channels=256,
|
| 32 |
+
num_outs=5,
|
| 33 |
+
norm_cfg=norm_cfg),
|
| 34 |
+
rpn_head=dict(
|
| 35 |
+
type='RPNHead',
|
| 36 |
+
in_channels=256,
|
| 37 |
+
feat_channels=256,
|
| 38 |
+
anchor_generator=dict(
|
| 39 |
+
type='AnchorGenerator',
|
| 40 |
+
scales=[8],
|
| 41 |
+
ratios=[0.5, 1.0, 2.0],
|
| 42 |
+
strides=[4, 8, 16, 32, 64]),
|
| 43 |
+
bbox_coder=dict(
|
| 44 |
+
type='DeltaXYWHBBoxCoder',
|
| 45 |
+
target_means=[0.0, 0.0, 0.0, 0.0],
|
| 46 |
+
target_stds=[1.0, 1.0, 1.0, 1.0]),
|
| 47 |
+
loss_cls=dict(
|
| 48 |
+
type='CrossEntropyLoss', use_sigmoid=True, loss_weight=1.0),
|
| 49 |
+
loss_bbox=dict(type='L1Loss', loss_weight=1.0),
|
| 50 |
+
num_convs=2),
|
| 51 |
+
roi_head=dict(
|
| 52 |
+
type='FViTRoIHead',
|
| 53 |
+
bbox_roi_extractor=dict(
|
| 54 |
+
type='SingleRoIExtractor',
|
| 55 |
+
roi_layer=dict(type='RoIAlign', output_size=7, sampling_ratio=0),
|
| 56 |
+
out_channels=256,
|
| 57 |
+
featmap_strides=[4, 8, 16, 32]),
|
| 58 |
+
bbox_head=dict(
|
| 59 |
+
type='FViTBBoxHead',
|
| 60 |
+
in_channels=256,
|
| 61 |
+
fc_out_channels=512,
|
| 62 |
+
roi_feat_size=7,
|
| 63 |
+
num_classes=num_classes,
|
| 64 |
+
bbox_coder=dict(
|
| 65 |
+
type='DeltaXYWHBBoxCoder',
|
| 66 |
+
target_means=[0.0, 0.0, 0.0, 0.0],
|
| 67 |
+
target_stds=[0.1, 0.1, 0.2, 0.2]),
|
| 68 |
+
reg_class_agnostic=True,
|
| 69 |
+
loss_cls=dict(
|
| 70 |
+
type='CustomCrossEntropyLoss',
|
| 71 |
+
use_sigmoid=False,
|
| 72 |
+
loss_weight=1.0,
|
| 73 |
+
class_weight=class_weight),
|
| 74 |
+
loss_bbox=dict(type='L1Loss', loss_weight=1.0),
|
| 75 |
+
norm_cfg=norm_cfg,
|
| 76 |
+
fixed_temperature=0,
|
| 77 |
+
learned_temperature=50.0,
|
| 78 |
+
vlm_temperature=75.0,
|
| 79 |
+
alpha=0.1,
|
| 80 |
+
beta=0.8,
|
| 81 |
+
# Prompt Ensemble embedding
|
| 82 |
+
class_embed='/mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/prompt_ensemble_ablation/embeddings/coco_eva02_clip_b_16_eva_ensemble.pt',
|
| 83 |
+
force_reload_embed=True,
|
| 84 |
+
seen_classes='datasets/mscoco_seen_classes.json',
|
| 85 |
+
all_classes='datasets/mscoco_65_classes.json',
|
| 86 |
+
num_shared_convs=4,
|
| 87 |
+
num_shared_fcs=2,
|
| 88 |
+
num_cls_fcs=1,
|
| 89 |
+
num_reg_fcs=1),
|
| 90 |
+
vlm_roi_extractor=dict(
|
| 91 |
+
type='SingleRoIExtractor',
|
| 92 |
+
roi_layer=dict(
|
| 93 |
+
type='RoIAlign',
|
| 94 |
+
output_size=1,
|
| 95 |
+
sampling_ratio=0,
|
| 96 |
+
use_torchvision=True),
|
| 97 |
+
out_channels=512,
|
| 98 |
+
featmap_strides=[16])),
|
| 99 |
+
train_cfg=dict(
|
| 100 |
+
rpn=dict(
|
| 101 |
+
assigner=dict(
|
| 102 |
+
type='MaxIoUAssigner',
|
| 103 |
+
pos_iou_thr=0.7,
|
| 104 |
+
neg_iou_thr=0.3,
|
| 105 |
+
min_pos_iou=0.3,
|
| 106 |
+
match_low_quality=True,
|
| 107 |
+
ignore_iof_thr=-1),
|
| 108 |
+
sampler=dict(
|
| 109 |
+
type='RandomSampler',
|
| 110 |
+
num=256,
|
| 111 |
+
pos_fraction=0.5,
|
| 112 |
+
neg_pos_ub=-1,
|
| 113 |
+
add_gt_as_proposals=False),
|
| 114 |
+
allowed_border=-1,
|
| 115 |
+
pos_weight=-1,
|
| 116 |
+
debug=False),
|
| 117 |
+
rpn_proposal=dict(
|
| 118 |
+
nms_pre=2000,
|
| 119 |
+
max_per_img=1000,
|
| 120 |
+
nms=dict(type='nms', iou_threshold=0.7),
|
| 121 |
+
min_bbox_size=0),
|
| 122 |
+
rcnn=dict(
|
| 123 |
+
assigner=dict(
|
| 124 |
+
type='MaxIoUAssigner',
|
| 125 |
+
pos_iou_thr=0.5,
|
| 126 |
+
neg_iou_thr=0.5,
|
| 127 |
+
min_pos_iou=0.5,
|
| 128 |
+
match_low_quality=False,
|
| 129 |
+
ignore_iof_thr=-1),
|
| 130 |
+
sampler=dict(
|
| 131 |
+
type='RandomSampler',
|
| 132 |
+
num=512,
|
| 133 |
+
pos_fraction=0.25,
|
| 134 |
+
neg_pos_ub=-1,
|
| 135 |
+
add_gt_as_proposals=True),
|
| 136 |
+
pos_weight=-1,
|
| 137 |
+
debug=False)),
|
| 138 |
+
test_cfg=dict(
|
| 139 |
+
rpn=dict(
|
| 140 |
+
nms_pre=2000,
|
| 141 |
+
max_per_img=1000,
|
| 142 |
+
nms=dict(type='nms', iou_threshold=0.7),
|
| 143 |
+
min_bbox_size=0),
|
| 144 |
+
rcnn=dict(
|
| 145 |
+
score_thr=0.01,
|
| 146 |
+
nms=dict(type='nms', iou_threshold=0.4),
|
| 147 |
+
max_per_img=100)))
|
| 148 |
+
|
| 149 |
+
checkpoint_config = dict(interval=1)
|
| 150 |
+
log_config = dict(interval=50, hooks=[dict(type='TextLoggerHook')])
|
| 151 |
+
dist_params = dict(backend='nccl')
|
| 152 |
+
log_level = 'INFO'
|
| 153 |
+
load_from = None
|
| 154 |
+
resume_from = None
|
| 155 |
+
workflow = [('train', 1)]
|
| 156 |
+
opencv_num_threads = 0
|
| 157 |
+
mp_start_method = 'fork'
|
| 158 |
+
auto_scale_lr = dict(enable=True, base_batch_size=64)
|
| 159 |
+
|
| 160 |
+
dataset_type = 'CocoDatasetOV'
|
| 161 |
+
image_size = (640, 640)
|
| 162 |
+
file_client_args = dict(backend='disk')
|
| 163 |
+
|
| 164 |
+
test_pipeline = [
|
| 165 |
+
dict(type='LoadImageFromFile', file_client_args=file_client_args),
|
| 166 |
+
dict(
|
| 167 |
+
type='MultiScaleFlipAug',
|
| 168 |
+
img_scale=image_size,
|
| 169 |
+
flip=False,
|
| 170 |
+
transforms=[
|
| 171 |
+
dict(type='Resize', keep_ratio=True),
|
| 172 |
+
dict(type='RandomFlip'),
|
| 173 |
+
dict(
|
| 174 |
+
type='Normalize',
|
| 175 |
+
mean=[123.675, 116.28, 103.53],
|
| 176 |
+
std=[58.395, 57.12, 57.375],
|
| 177 |
+
to_rgb=True),
|
| 178 |
+
dict(type='Pad', pad_to_square=True),
|
| 179 |
+
dict(type='ImageToTensor', keys=['img']),
|
| 180 |
+
dict(type='Collect', keys=['img'])
|
| 181 |
+
])
|
| 182 |
+
]
|
| 183 |
+
|
| 184 |
+
data = dict(
|
| 185 |
+
samples_per_gpu=8,
|
| 186 |
+
workers_per_gpu=4,
|
| 187 |
+
val=dict(
|
| 188 |
+
type=dataset_type,
|
| 189 |
+
ann_file='data/coco/zero-shot/instances_val2017_all_2.json',
|
| 190 |
+
img_prefix='data/coco/val2017/',
|
| 191 |
+
pipeline=test_pipeline),
|
| 192 |
+
test=dict(
|
| 193 |
+
type=dataset_type,
|
| 194 |
+
ann_file='data/coco/zero-shot/instances_val2017_all_2.json',
|
| 195 |
+
img_prefix='data/coco/val2017/',
|
| 196 |
+
pipeline=test_pipeline))
|
| 197 |
+
|
| 198 |
+
evaluation = dict(interval=1, metric=['bbox'])
|
| 199 |
+
optimizer = dict(type='AdamW', lr=0.0001, betas=(0.9, 0.999), weight_decay=0.1)
|
| 200 |
+
optimizer_config = dict(grad_clip=dict(max_norm=1.0, norm_type=2))
|
| 201 |
+
lr_config = dict(
|
| 202 |
+
policy='step',
|
| 203 |
+
warmup='linear',
|
| 204 |
+
warmup_iters=250,
|
| 205 |
+
warmup_ratio=0.001,
|
| 206 |
+
step=[100])
|
| 207 |
+
runner = dict(type='EpochBasedRunner', max_epochs=3)
|
| 208 |
+
fp16 = dict(loss_scale=512.0)
|
analysis/prompt_ensemble_ablation/configs/fvit_vitb16_ovcoco_declip_single_prompt.py
ADDED
|
@@ -0,0 +1,209 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# DeCLIP EVA-B Single Prompt 消融实验配置
|
| 2 |
+
# 使用 EVAB_dinov2B_epoch2.pth 检测器权重
|
| 3 |
+
# 注意:backbone.pretrained 指向 DeCLIP 预训练的 backbone,检测器权重通过命令行加载
|
| 4 |
+
|
| 5 |
+
custom_imports = dict(
|
| 6 |
+
imports=['datasets', 'models'],
|
| 7 |
+
allow_failed_imports=False
|
| 8 |
+
)
|
| 9 |
+
|
| 10 |
+
find_unused_parameters = True
|
| 11 |
+
num_classes = 65
|
| 12 |
+
class_weight = [
|
| 13 |
+
1.0, 1.0, 1.0, 1.0, 0, 0, 1.0, 1.0, 1.0, 1.0, 1.0, 0, 0, 1.0, 1.0, 0, 0,
|
| 14 |
+
1.0, 1.0, 1.0, 1.0, 0, 1.0, 0, 1.0, 1.0, 1.0, 0, 1.0, 0, 1.0, 1.0, 0, 1.0,
|
| 15 |
+
0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0, 1.0, 0, 1.0, 1.0,
|
| 16 |
+
1.0, 1.0, 1.0, 1.0, 0, 1.0, 1.0, 1.0, 0, 1.0, 1.0, 1.0, 1.0, 0, 1.0, 0.6
|
| 17 |
+
]
|
| 18 |
+
norm_cfg = dict(type='SyncBN', requires_grad=True)
|
| 19 |
+
|
| 20 |
+
model = dict(
|
| 21 |
+
type='FViT',
|
| 22 |
+
backbone=dict(
|
| 23 |
+
type='EvaCLIPViT',
|
| 24 |
+
model_name='EVA02-CLIP-B-16',
|
| 25 |
+
pretrained='/opt/tiger/xiaomoguhzz/EVA02_CLIP_B_psz16_s8B.pt',
|
| 26 |
+
norm_cfg=norm_cfg,
|
| 27 |
+
out_indices=[3, 5, 7, 11],
|
| 28 |
+
feature_mode='csa'), # DeCLIP: Q*Q^T + K*K^T, 无 scale, 无残差, 无 MLP
|
| 29 |
+
neck=dict(
|
| 30 |
+
type='FPN',
|
| 31 |
+
in_channels=[768, 768, 768, 768],
|
| 32 |
+
out_channels=256,
|
| 33 |
+
num_outs=5,
|
| 34 |
+
norm_cfg=norm_cfg),
|
| 35 |
+
rpn_head=dict(
|
| 36 |
+
type='RPNHead',
|
| 37 |
+
in_channels=256,
|
| 38 |
+
feat_channels=256,
|
| 39 |
+
anchor_generator=dict(
|
| 40 |
+
type='AnchorGenerator',
|
| 41 |
+
scales=[8],
|
| 42 |
+
ratios=[0.5, 1.0, 2.0],
|
| 43 |
+
strides=[4, 8, 16, 32, 64]),
|
| 44 |
+
bbox_coder=dict(
|
| 45 |
+
type='DeltaXYWHBBoxCoder',
|
| 46 |
+
target_means=[0.0, 0.0, 0.0, 0.0],
|
| 47 |
+
target_stds=[1.0, 1.0, 1.0, 1.0]),
|
| 48 |
+
loss_cls=dict(
|
| 49 |
+
type='CrossEntropyLoss', use_sigmoid=True, loss_weight=1.0),
|
| 50 |
+
loss_bbox=dict(type='L1Loss', loss_weight=1.0),
|
| 51 |
+
num_convs=2),
|
| 52 |
+
roi_head=dict(
|
| 53 |
+
type='FViTRoIHead',
|
| 54 |
+
bbox_roi_extractor=dict(
|
| 55 |
+
type='SingleRoIExtractor',
|
| 56 |
+
roi_layer=dict(type='RoIAlign', output_size=7, sampling_ratio=0),
|
| 57 |
+
out_channels=256,
|
| 58 |
+
featmap_strides=[4, 8, 16, 32]),
|
| 59 |
+
bbox_head=dict(
|
| 60 |
+
type='FViTBBoxHead',
|
| 61 |
+
in_channels=256,
|
| 62 |
+
fc_out_channels=512,
|
| 63 |
+
roi_feat_size=7,
|
| 64 |
+
num_classes=num_classes,
|
| 65 |
+
bbox_coder=dict(
|
| 66 |
+
type='DeltaXYWHBBoxCoder',
|
| 67 |
+
target_means=[0.0, 0.0, 0.0, 0.0],
|
| 68 |
+
target_stds=[0.1, 0.1, 0.2, 0.2]),
|
| 69 |
+
reg_class_agnostic=True,
|
| 70 |
+
loss_cls=dict(
|
| 71 |
+
type='CustomCrossEntropyLoss',
|
| 72 |
+
use_sigmoid=False,
|
| 73 |
+
loss_weight=1.0,
|
| 74 |
+
class_weight=class_weight),
|
| 75 |
+
loss_bbox=dict(type='L1Loss', loss_weight=1.0),
|
| 76 |
+
norm_cfg=norm_cfg,
|
| 77 |
+
fixed_temperature=0,
|
| 78 |
+
learned_temperature=50.0,
|
| 79 |
+
vlm_temperature=75.0,
|
| 80 |
+
alpha=0.1,
|
| 81 |
+
beta=0.8,
|
| 82 |
+
# Single Prompt embedding
|
| 83 |
+
class_embed='/mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/prompt_ensemble_ablation/embeddings/coco_eva02_clip_b_16_eva_single_prompt.pt',
|
| 84 |
+
force_reload_embed=True,
|
| 85 |
+
seen_classes='datasets/mscoco_seen_classes.json',
|
| 86 |
+
all_classes='datasets/mscoco_65_classes.json',
|
| 87 |
+
num_shared_convs=4,
|
| 88 |
+
num_shared_fcs=2,
|
| 89 |
+
num_cls_fcs=1,
|
| 90 |
+
num_reg_fcs=1),
|
| 91 |
+
vlm_roi_extractor=dict(
|
| 92 |
+
type='SingleRoIExtractor',
|
| 93 |
+
roi_layer=dict(
|
| 94 |
+
type='RoIAlign',
|
| 95 |
+
output_size=1,
|
| 96 |
+
sampling_ratio=0,
|
| 97 |
+
use_torchvision=True),
|
| 98 |
+
out_channels=512,
|
| 99 |
+
featmap_strides=[16])),
|
| 100 |
+
train_cfg=dict(
|
| 101 |
+
rpn=dict(
|
| 102 |
+
assigner=dict(
|
| 103 |
+
type='MaxIoUAssigner',
|
| 104 |
+
pos_iou_thr=0.7,
|
| 105 |
+
neg_iou_thr=0.3,
|
| 106 |
+
min_pos_iou=0.3,
|
| 107 |
+
match_low_quality=True,
|
| 108 |
+
ignore_iof_thr=-1),
|
| 109 |
+
sampler=dict(
|
| 110 |
+
type='RandomSampler',
|
| 111 |
+
num=256,
|
| 112 |
+
pos_fraction=0.5,
|
| 113 |
+
neg_pos_ub=-1,
|
| 114 |
+
add_gt_as_proposals=False),
|
| 115 |
+
allowed_border=-1,
|
| 116 |
+
pos_weight=-1,
|
| 117 |
+
debug=False),
|
| 118 |
+
rpn_proposal=dict(
|
| 119 |
+
nms_pre=2000,
|
| 120 |
+
max_per_img=1000,
|
| 121 |
+
nms=dict(type='nms', iou_threshold=0.7),
|
| 122 |
+
min_bbox_size=0),
|
| 123 |
+
rcnn=dict(
|
| 124 |
+
assigner=dict(
|
| 125 |
+
type='MaxIoUAssigner',
|
| 126 |
+
pos_iou_thr=0.5,
|
| 127 |
+
neg_iou_thr=0.5,
|
| 128 |
+
min_pos_iou=0.5,
|
| 129 |
+
match_low_quality=False,
|
| 130 |
+
ignore_iof_thr=-1),
|
| 131 |
+
sampler=dict(
|
| 132 |
+
type='RandomSampler',
|
| 133 |
+
num=512,
|
| 134 |
+
pos_fraction=0.25,
|
| 135 |
+
neg_pos_ub=-1,
|
| 136 |
+
add_gt_as_proposals=True),
|
| 137 |
+
pos_weight=-1,
|
| 138 |
+
debug=False)),
|
| 139 |
+
test_cfg=dict(
|
| 140 |
+
rpn=dict(
|
| 141 |
+
nms_pre=2000,
|
| 142 |
+
max_per_img=1000,
|
| 143 |
+
nms=dict(type='nms', iou_threshold=0.7),
|
| 144 |
+
min_bbox_size=0),
|
| 145 |
+
rcnn=dict(
|
| 146 |
+
score_thr=0.01,
|
| 147 |
+
nms=dict(type='nms', iou_threshold=0.4),
|
| 148 |
+
max_per_img=100)))
|
| 149 |
+
|
| 150 |
+
checkpoint_config = dict(interval=1)
|
| 151 |
+
log_config = dict(interval=50, hooks=[dict(type='TextLoggerHook')])
|
| 152 |
+
dist_params = dict(backend='nccl')
|
| 153 |
+
log_level = 'INFO'
|
| 154 |
+
load_from = None
|
| 155 |
+
resume_from = None
|
| 156 |
+
workflow = [('train', 1)]
|
| 157 |
+
opencv_num_threads = 0
|
| 158 |
+
mp_start_method = 'fork'
|
| 159 |
+
auto_scale_lr = dict(enable=True, base_batch_size=64)
|
| 160 |
+
|
| 161 |
+
dataset_type = 'CocoDatasetOV'
|
| 162 |
+
image_size = (640, 640)
|
| 163 |
+
file_client_args = dict(backend='disk')
|
| 164 |
+
|
| 165 |
+
test_pipeline = [
|
| 166 |
+
dict(type='LoadImageFromFile', file_client_args=file_client_args),
|
| 167 |
+
dict(
|
| 168 |
+
type='MultiScaleFlipAug',
|
| 169 |
+
img_scale=image_size,
|
| 170 |
+
flip=False,
|
| 171 |
+
transforms=[
|
| 172 |
+
dict(type='Resize', keep_ratio=True),
|
| 173 |
+
dict(type='RandomFlip'),
|
| 174 |
+
dict(
|
| 175 |
+
type='Normalize',
|
| 176 |
+
mean=[123.675, 116.28, 103.53],
|
| 177 |
+
std=[58.395, 57.12, 57.375],
|
| 178 |
+
to_rgb=True),
|
| 179 |
+
dict(type='Pad', pad_to_square=True),
|
| 180 |
+
dict(type='ImageToTensor', keys=['img']),
|
| 181 |
+
dict(type='Collect', keys=['img'])
|
| 182 |
+
])
|
| 183 |
+
]
|
| 184 |
+
|
| 185 |
+
data = dict(
|
| 186 |
+
samples_per_gpu=8,
|
| 187 |
+
workers_per_gpu=4,
|
| 188 |
+
val=dict(
|
| 189 |
+
type=dataset_type,
|
| 190 |
+
ann_file='data/coco/zero-shot/instances_val2017_all_2.json',
|
| 191 |
+
img_prefix='data/coco/val2017/',
|
| 192 |
+
pipeline=test_pipeline),
|
| 193 |
+
test=dict(
|
| 194 |
+
type=dataset_type,
|
| 195 |
+
ann_file='data/coco/zero-shot/instances_val2017_all_2.json',
|
| 196 |
+
img_prefix='data/coco/val2017/',
|
| 197 |
+
pipeline=test_pipeline))
|
| 198 |
+
|
| 199 |
+
evaluation = dict(interval=1, metric=['bbox'])
|
| 200 |
+
optimizer = dict(type='AdamW', lr=0.0001, betas=(0.9, 0.999), weight_decay=0.1)
|
| 201 |
+
optimizer_config = dict(grad_clip=dict(max_norm=1.0, norm_type=2))
|
| 202 |
+
lr_config = dict(
|
| 203 |
+
policy='step',
|
| 204 |
+
warmup='linear',
|
| 205 |
+
warmup_iters=250,
|
| 206 |
+
warmup_ratio=0.001,
|
| 207 |
+
step=[100])
|
| 208 |
+
runner = dict(type='EpochBasedRunner', max_epochs=3)
|
| 209 |
+
fp16 = dict(loss_scale=512.0)
|
analysis/prompt_ensemble_ablation/configs/fvit_vitb16_ovcoco_ensemble.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Prompt Ensemble 配置
|
| 2 |
+
# 基于 CLIPSelf EVA-ViT-B/16,使用 prompt ensemble embedding
|
| 3 |
+
#
|
| 4 |
+
# 注意:必须设置 force_reload_embed=True,否则会使用 checkpoint 中保存的 embedding
|
| 5 |
+
# 而不是配置文件中指定的 embedding 文件
|
| 6 |
+
|
| 7 |
+
custom_imports = dict(
|
| 8 |
+
imports=['datasets', 'models'],
|
| 9 |
+
allow_failed_imports=False
|
| 10 |
+
)
|
| 11 |
+
|
| 12 |
+
_base_ = '../../CLIPSelf/F-ViT/configs/ov_coco/fvit_vitb16_upsample_fpn_bs64_3e_ovcoco_eva_original.py'
|
| 13 |
+
|
| 14 |
+
model = dict(
|
| 15 |
+
backbone=dict(
|
| 16 |
+
pretrained='/opt/tiger/xiaomoguhzz/EVA02_CLIP_B_psz16_s8B.pt',
|
| 17 |
+
feature_mode='maskclip',
|
| 18 |
+
),
|
| 19 |
+
roi_head=dict(
|
| 20 |
+
bbox_head=dict(
|
| 21 |
+
# 使用 prompt ensemble embedding
|
| 22 |
+
class_embed='/mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/prompt_ensemble_ablation/embeddings/coco_eva02_clip_b_16_eva_ensemble.pt',
|
| 23 |
+
# 强制从配置文件重新加载 embedding,忽略 checkpoint 中保存的 embedding
|
| 24 |
+
force_reload_embed=True,
|
| 25 |
+
),
|
| 26 |
+
),
|
| 27 |
+
)
|
analysis/prompt_ensemble_ablation/configs/fvit_vitb16_ovcoco_maskclip_ensemble.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# MaskCLIP EVA-B Ensemble 配置
|
| 2 |
+
# 使用原始 EVA-CLIP (不经过 CLIPSelf 训练)
|
| 3 |
+
#
|
| 4 |
+
# 注意:必须设置 force_reload_embed=True
|
| 5 |
+
|
| 6 |
+
custom_imports = dict(
|
| 7 |
+
imports=['datasets', 'models'],
|
| 8 |
+
allow_failed_imports=False
|
| 9 |
+
)
|
| 10 |
+
|
| 11 |
+
_base_ = '../../CLIPSelf/F-ViT/configs/declip/fvit_vitb16_upsample_fpn_bs64_3e_ovcoco_maskclip.py'
|
| 12 |
+
|
| 13 |
+
model = dict(
|
| 14 |
+
roi_head=dict(
|
| 15 |
+
bbox_head=dict(
|
| 16 |
+
# 使用 prompt ensemble embedding
|
| 17 |
+
class_embed='/mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/prompt_ensemble_ablation/embeddings/coco_eva02_clip_b_16_eva_ensemble.pt',
|
| 18 |
+
# 强制从配置文件重新加载 embedding
|
| 19 |
+
force_reload_embed=True,
|
| 20 |
+
),
|
| 21 |
+
),
|
| 22 |
+
)
|
analysis/prompt_ensemble_ablation/configs/fvit_vitb16_ovcoco_maskclip_single_prompt.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# MaskCLIP EVA-B Single Prompt 消融实验配置
|
| 2 |
+
# 使用原始 EVA-CLIP (不经过 CLIPSelf 训练)
|
| 3 |
+
#
|
| 4 |
+
# 注意:必须设置 force_reload_embed=True
|
| 5 |
+
|
| 6 |
+
custom_imports = dict(
|
| 7 |
+
imports=['datasets', 'models'],
|
| 8 |
+
allow_failed_imports=False
|
| 9 |
+
)
|
| 10 |
+
|
| 11 |
+
_base_ = '../../CLIPSelf/F-ViT/configs/declip/fvit_vitb16_upsample_fpn_bs64_3e_ovcoco_maskclip.py'
|
| 12 |
+
|
| 13 |
+
model = dict(
|
| 14 |
+
roi_head=dict(
|
| 15 |
+
bbox_head=dict(
|
| 16 |
+
# 使用 single prompt embedding (消融实验)
|
| 17 |
+
class_embed='/mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/prompt_ensemble_ablation/embeddings/coco_eva02_clip_b_16_eva_single_prompt.pt',
|
| 18 |
+
# 强制从配置文件重新加载 embedding
|
| 19 |
+
force_reload_embed=True,
|
| 20 |
+
),
|
| 21 |
+
),
|
| 22 |
+
)
|
analysis/prompt_ensemble_ablation/configs/fvit_vitb16_ovcoco_single_prompt.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Single Prompt 消融实验配置
|
| 2 |
+
# 基于 CLIPSelf EVA-ViT-B/16,使用 single prompt embedding 替代 prompt ensemble
|
| 3 |
+
#
|
| 4 |
+
# 注意:必须设置 force_reload_embed=True,否则会使用 checkpoint 中保存的 embedding
|
| 5 |
+
# 而不是配置文件中指定的 embedding 文件
|
| 6 |
+
|
| 7 |
+
custom_imports = dict(
|
| 8 |
+
imports=['datasets', 'models'],
|
| 9 |
+
allow_failed_imports=False
|
| 10 |
+
)
|
| 11 |
+
|
| 12 |
+
_base_ = '../../CLIPSelf/F-ViT/configs/ov_coco/fvit_vitb16_upsample_fpn_bs64_3e_ovcoco_eva_original.py'
|
| 13 |
+
|
| 14 |
+
model = dict(
|
| 15 |
+
backbone=dict(
|
| 16 |
+
pretrained='/opt/tiger/xiaomoguhzz/EVA02_CLIP_B_psz16_s8B.pt',
|
| 17 |
+
feature_mode='maskclip',
|
| 18 |
+
),
|
| 19 |
+
roi_head=dict(
|
| 20 |
+
bbox_head=dict(
|
| 21 |
+
# 使用 single prompt embedding (消融实验)
|
| 22 |
+
class_embed='/mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/prompt_ensemble_ablation/embeddings/coco_eva02_clip_b_16_eva_single_prompt.pt',
|
| 23 |
+
# 强制从配置文件重新加载 embedding,忽略 checkpoint 中保存的 embedding
|
| 24 |
+
force_reload_embed=True,
|
| 25 |
+
),
|
| 26 |
+
),
|
| 27 |
+
)
|
analysis/prompt_ensemble_ablation/configs/fvit_vitl14_ovcoco_clearclip_ensemble.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# ClearCLIP EVA-L Ensemble 配置
|
| 2 |
+
# 使用原始 EVA-CLIP Large + QQ attention (ClearCLIP方式)
|
| 3 |
+
# feature_mode='qq'
|
| 4 |
+
#
|
| 5 |
+
# 注意:必须设置 force_reload_embed=True
|
| 6 |
+
|
| 7 |
+
custom_imports = dict(
|
| 8 |
+
imports=['datasets', 'models'],
|
| 9 |
+
allow_failed_imports=False
|
| 10 |
+
)
|
| 11 |
+
|
| 12 |
+
_base_ = '../../CLIPSelf/F-ViT/configs/declip/fvit_vitl14_upsample_fpn_bs64_3e_ovcoco_clearclip.py'
|
| 13 |
+
|
| 14 |
+
model = dict(
|
| 15 |
+
roi_head=dict(
|
| 16 |
+
bbox_head=dict(
|
| 17 |
+
# 使用 prompt ensemble embedding
|
| 18 |
+
class_embed='/mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/prompt_ensemble_ablation/embeddings/coco_eva02_clip_l_14_336_eva_ensemble.pt',
|
| 19 |
+
# 强制从配置文件重新加载 embedding
|
| 20 |
+
force_reload_embed=True,
|
| 21 |
+
),
|
| 22 |
+
),
|
| 23 |
+
)
|
analysis/prompt_ensemble_ablation/configs/fvit_vitl14_ovcoco_clearclip_single_prompt.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# ClearCLIP EVA-L Single Prompt 消融实验配置
|
| 2 |
+
# 使用原始 EVA-CLIP Large + QQ attention (ClearCLIP方式)
|
| 3 |
+
# feature_mode='qq'
|
| 4 |
+
#
|
| 5 |
+
# 注意:必须设置 force_reload_embed=True
|
| 6 |
+
|
| 7 |
+
custom_imports = dict(
|
| 8 |
+
imports=['datasets', 'models'],
|
| 9 |
+
allow_failed_imports=False
|
| 10 |
+
)
|
| 11 |
+
|
| 12 |
+
_base_ = '../../CLIPSelf/F-ViT/configs/declip/fvit_vitl14_upsample_fpn_bs64_3e_ovcoco_clearclip.py'
|
| 13 |
+
|
| 14 |
+
model = dict(
|
| 15 |
+
roi_head=dict(
|
| 16 |
+
bbox_head=dict(
|
| 17 |
+
# 使用 single prompt embedding (消融实验)
|
| 18 |
+
class_embed='/mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/prompt_ensemble_ablation/embeddings/coco_eva02_clip_l_14_336_eva_single_prompt.pt',
|
| 19 |
+
# 强制从配置文件重新加载 embedding
|
| 20 |
+
force_reload_embed=True,
|
| 21 |
+
),
|
| 22 |
+
),
|
| 23 |
+
)
|
analysis/prompt_ensemble_ablation/configs/fvit_vitl14_ovcoco_declip_ensemble.py
ADDED
|
@@ -0,0 +1,208 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# DeCLIP EVA-L Prompt Ensemble 配置
|
| 2 |
+
# 使用 EVAL_dinov2L_epoch3.pth 检测器权重
|
| 3 |
+
# image_size=896, model_name='EVA02-CLIP-L-14-336'
|
| 4 |
+
|
| 5 |
+
custom_imports = dict(
|
| 6 |
+
imports=['datasets', 'models'],
|
| 7 |
+
allow_failed_imports=False
|
| 8 |
+
)
|
| 9 |
+
|
| 10 |
+
find_unused_parameters = True
|
| 11 |
+
num_classes = 65
|
| 12 |
+
class_weight = [
|
| 13 |
+
1.0, 1.0, 1.0, 1.0, 0, 0, 1.0, 1.0, 1.0, 1.0, 1.0, 0, 0, 1.0, 1.0, 0, 0,
|
| 14 |
+
1.0, 1.0, 1.0, 1.0, 0, 1.0, 0, 1.0, 1.0, 1.0, 0, 1.0, 0, 1.0, 1.0, 0, 1.0,
|
| 15 |
+
0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0, 1.0, 0, 1.0, 1.0,
|
| 16 |
+
1.0, 1.0, 1.0, 1.0, 0, 1.0, 1.0, 1.0, 0, 1.0, 1.0, 1.0, 1.0, 0, 1.0, 0.6
|
| 17 |
+
]
|
| 18 |
+
norm_cfg = dict(type='SyncBN', requires_grad=True)
|
| 19 |
+
|
| 20 |
+
model = dict(
|
| 21 |
+
type='FViT',
|
| 22 |
+
backbone=dict(
|
| 23 |
+
type='EvaCLIPViT',
|
| 24 |
+
model_name='EVA02-CLIP-L-14-336',
|
| 25 |
+
pretrained='/opt/tiger/xiaomoguhzz/EVA02_CLIP_L_336_psz14_s6B.pt',
|
| 26 |
+
norm_cfg=norm_cfg,
|
| 27 |
+
out_indices=[6, 10, 14, 23],
|
| 28 |
+
feature_mode='csa'), # DeCLIP: Q*Q^T + K*K^T, 无 scale, 无残差, 无 MLP
|
| 29 |
+
neck=dict(
|
| 30 |
+
type='FPN',
|
| 31 |
+
in_channels=[1024, 1024, 1024, 1024],
|
| 32 |
+
out_channels=256,
|
| 33 |
+
num_outs=5,
|
| 34 |
+
norm_cfg=norm_cfg),
|
| 35 |
+
rpn_head=dict(
|
| 36 |
+
type='RPNHead',
|
| 37 |
+
in_channels=256,
|
| 38 |
+
feat_channels=256,
|
| 39 |
+
anchor_generator=dict(
|
| 40 |
+
type='AnchorGenerator',
|
| 41 |
+
scales=[8],
|
| 42 |
+
ratios=[0.5, 1.0, 2.0],
|
| 43 |
+
strides=[3.5, 7, 14, 28, 56]),
|
| 44 |
+
bbox_coder=dict(
|
| 45 |
+
type='DeltaXYWHBBoxCoder',
|
| 46 |
+
target_means=[0.0, 0.0, 0.0, 0.0],
|
| 47 |
+
target_stds=[1.0, 1.0, 1.0, 1.0]),
|
| 48 |
+
loss_cls=dict(
|
| 49 |
+
type='CrossEntropyLoss', use_sigmoid=True, loss_weight=1.0),
|
| 50 |
+
loss_bbox=dict(type='L1Loss', loss_weight=1.0),
|
| 51 |
+
num_convs=2),
|
| 52 |
+
roi_head=dict(
|
| 53 |
+
type='FViTRoIHead',
|
| 54 |
+
bbox_roi_extractor=dict(
|
| 55 |
+
type='SingleRoIExtractor',
|
| 56 |
+
roi_layer=dict(type='RoIAlign', output_size=7, sampling_ratio=0),
|
| 57 |
+
out_channels=256,
|
| 58 |
+
featmap_strides=[3.5, 7, 14, 28]),
|
| 59 |
+
bbox_head=dict(
|
| 60 |
+
type='FViTBBoxHead',
|
| 61 |
+
in_channels=256,
|
| 62 |
+
fc_out_channels=768,
|
| 63 |
+
roi_feat_size=7,
|
| 64 |
+
num_classes=num_classes,
|
| 65 |
+
bbox_coder=dict(
|
| 66 |
+
type='DeltaXYWHBBoxCoder',
|
| 67 |
+
target_means=[0.0, 0.0, 0.0, 0.0],
|
| 68 |
+
target_stds=[0.1, 0.1, 0.2, 0.2]),
|
| 69 |
+
reg_class_agnostic=True,
|
| 70 |
+
loss_cls=dict(
|
| 71 |
+
type='CustomCrossEntropyLoss',
|
| 72 |
+
use_sigmoid=False,
|
| 73 |
+
loss_weight=1.0,
|
| 74 |
+
class_weight=class_weight),
|
| 75 |
+
loss_bbox=dict(type='L1Loss', loss_weight=1.0),
|
| 76 |
+
norm_cfg=norm_cfg,
|
| 77 |
+
learned_temperature=50.0,
|
| 78 |
+
vlm_temperature=75.0,
|
| 79 |
+
alpha=0.1,
|
| 80 |
+
beta=0.8,
|
| 81 |
+
# Prompt Ensemble embedding (EVA-L)
|
| 82 |
+
class_embed='/mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/prompt_ensemble_ablation/embeddings/coco_eva02_clip_l_14_336_eva_ensemble.pt',
|
| 83 |
+
force_reload_embed=True,
|
| 84 |
+
seen_classes='datasets/mscoco_seen_classes.json',
|
| 85 |
+
all_classes='datasets/mscoco_65_classes.json',
|
| 86 |
+
num_shared_convs=4,
|
| 87 |
+
num_shared_fcs=2,
|
| 88 |
+
num_cls_fcs=1,
|
| 89 |
+
num_reg_fcs=1),
|
| 90 |
+
vlm_roi_extractor=dict(
|
| 91 |
+
type='SingleRoIExtractor',
|
| 92 |
+
roi_layer=dict(
|
| 93 |
+
type='RoIAlign',
|
| 94 |
+
output_size=1,
|
| 95 |
+
sampling_ratio=0,
|
| 96 |
+
use_torchvision=True),
|
| 97 |
+
out_channels=768,
|
| 98 |
+
featmap_strides=[14])),
|
| 99 |
+
train_cfg=dict(
|
| 100 |
+
rpn=dict(
|
| 101 |
+
assigner=dict(
|
| 102 |
+
type='MaxIoUAssigner',
|
| 103 |
+
pos_iou_thr=0.7,
|
| 104 |
+
neg_iou_thr=0.3,
|
| 105 |
+
min_pos_iou=0.3,
|
| 106 |
+
match_low_quality=True,
|
| 107 |
+
ignore_iof_thr=-1),
|
| 108 |
+
sampler=dict(
|
| 109 |
+
type='RandomSampler',
|
| 110 |
+
num=256,
|
| 111 |
+
pos_fraction=0.5,
|
| 112 |
+
neg_pos_ub=-1,
|
| 113 |
+
add_gt_as_proposals=False),
|
| 114 |
+
allowed_border=-1,
|
| 115 |
+
pos_weight=-1,
|
| 116 |
+
debug=False),
|
| 117 |
+
rpn_proposal=dict(
|
| 118 |
+
nms_pre=2000,
|
| 119 |
+
max_per_img=1000,
|
| 120 |
+
nms=dict(type='nms', iou_threshold=0.7),
|
| 121 |
+
min_bbox_size=0),
|
| 122 |
+
rcnn=dict(
|
| 123 |
+
assigner=dict(
|
| 124 |
+
type='MaxIoUAssigner',
|
| 125 |
+
pos_iou_thr=0.5,
|
| 126 |
+
neg_iou_thr=0.5,
|
| 127 |
+
min_pos_iou=0.5,
|
| 128 |
+
match_low_quality=False,
|
| 129 |
+
ignore_iof_thr=-1),
|
| 130 |
+
sampler=dict(
|
| 131 |
+
type='RandomSampler',
|
| 132 |
+
num=512,
|
| 133 |
+
pos_fraction=0.25,
|
| 134 |
+
neg_pos_ub=-1,
|
| 135 |
+
add_gt_as_proposals=True),
|
| 136 |
+
pos_weight=-1,
|
| 137 |
+
debug=False)),
|
| 138 |
+
test_cfg=dict(
|
| 139 |
+
rpn=dict(
|
| 140 |
+
nms_pre=2000,
|
| 141 |
+
max_per_img=1000,
|
| 142 |
+
nms=dict(type='nms', iou_threshold=0.7),
|
| 143 |
+
min_bbox_size=0),
|
| 144 |
+
rcnn=dict(
|
| 145 |
+
score_thr=0.01,
|
| 146 |
+
nms=dict(type='nms', iou_threshold=0.4),
|
| 147 |
+
max_per_img=100)))
|
| 148 |
+
|
| 149 |
+
checkpoint_config = dict(interval=1)
|
| 150 |
+
log_config = dict(interval=50, hooks=[dict(type='TextLoggerHook')])
|
| 151 |
+
dist_params = dict(backend='nccl')
|
| 152 |
+
log_level = 'INFO'
|
| 153 |
+
load_from = None
|
| 154 |
+
resume_from = None
|
| 155 |
+
workflow = [('train', 1)]
|
| 156 |
+
opencv_num_threads = 0
|
| 157 |
+
mp_start_method = 'fork'
|
| 158 |
+
auto_scale_lr = dict(enable=True, base_batch_size=64)
|
| 159 |
+
|
| 160 |
+
dataset_type = 'CocoDatasetOV'
|
| 161 |
+
image_size = (896, 896)
|
| 162 |
+
file_client_args = dict(backend='disk')
|
| 163 |
+
|
| 164 |
+
test_pipeline = [
|
| 165 |
+
dict(type='LoadImageFromFile', file_client_args=file_client_args),
|
| 166 |
+
dict(
|
| 167 |
+
type='MultiScaleFlipAug',
|
| 168 |
+
img_scale=image_size,
|
| 169 |
+
flip=False,
|
| 170 |
+
transforms=[
|
| 171 |
+
dict(type='Resize', keep_ratio=True),
|
| 172 |
+
dict(type='RandomFlip'),
|
| 173 |
+
dict(
|
| 174 |
+
type='Normalize',
|
| 175 |
+
mean=[122.771, 116.746, 104.094],
|
| 176 |
+
std=[68.501, 66.632, 70.323],
|
| 177 |
+
to_rgb=True),
|
| 178 |
+
dict(type='Pad', pad_to_square=True),
|
| 179 |
+
dict(type='ImageToTensor', keys=['img']),
|
| 180 |
+
dict(type='Collect', keys=['img'])
|
| 181 |
+
])
|
| 182 |
+
]
|
| 183 |
+
|
| 184 |
+
data = dict(
|
| 185 |
+
samples_per_gpu=2,
|
| 186 |
+
workers_per_gpu=4,
|
| 187 |
+
val=dict(
|
| 188 |
+
type=dataset_type,
|
| 189 |
+
ann_file='data/coco/zero-shot/instances_val2017_all_2.json',
|
| 190 |
+
img_prefix='data/coco/val2017/',
|
| 191 |
+
pipeline=test_pipeline),
|
| 192 |
+
test=dict(
|
| 193 |
+
type=dataset_type,
|
| 194 |
+
ann_file='data/coco/zero-shot/instances_val2017_all_2.json',
|
| 195 |
+
img_prefix='data/coco/val2017/',
|
| 196 |
+
pipeline=test_pipeline))
|
| 197 |
+
|
| 198 |
+
evaluation = dict(interval=1, metric=['bbox'])
|
| 199 |
+
optimizer = dict(type='AdamW', lr=0.0001, betas=(0.9, 0.999), weight_decay=0.1)
|
| 200 |
+
optimizer_config = dict(grad_clip=dict(max_norm=1.0, norm_type=2))
|
| 201 |
+
lr_config = dict(
|
| 202 |
+
policy='step',
|
| 203 |
+
warmup='linear',
|
| 204 |
+
warmup_iters=250,
|
| 205 |
+
warmup_ratio=0.001,
|
| 206 |
+
step=[100])
|
| 207 |
+
runner = dict(type='EpochBasedRunner', max_epochs=3)
|
| 208 |
+
fp16 = dict(loss_scale=512.0)
|
analysis/prompt_ensemble_ablation/configs/fvit_vitl14_ovcoco_declip_single_prompt.py
ADDED
|
@@ -0,0 +1,208 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# DeCLIP EVA-L Single Prompt 消融实验配置
|
| 2 |
+
# 使用 EVAL_dinov2L_epoch3.pth 检测器权重
|
| 3 |
+
# image_size=896, model_name='EVA02-CLIP-L-14-336'
|
| 4 |
+
|
| 5 |
+
custom_imports = dict(
|
| 6 |
+
imports=['datasets', 'models'],
|
| 7 |
+
allow_failed_imports=False
|
| 8 |
+
)
|
| 9 |
+
|
| 10 |
+
find_unused_parameters = True
|
| 11 |
+
num_classes = 65
|
| 12 |
+
class_weight = [
|
| 13 |
+
1.0, 1.0, 1.0, 1.0, 0, 0, 1.0, 1.0, 1.0, 1.0, 1.0, 0, 0, 1.0, 1.0, 0, 0,
|
| 14 |
+
1.0, 1.0, 1.0, 1.0, 0, 1.0, 0, 1.0, 1.0, 1.0, 0, 1.0, 0, 1.0, 1.0, 0, 1.0,
|
| 15 |
+
0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0, 1.0, 0, 1.0, 1.0,
|
| 16 |
+
1.0, 1.0, 1.0, 1.0, 0, 1.0, 1.0, 1.0, 0, 1.0, 1.0, 1.0, 1.0, 0, 1.0, 0.6
|
| 17 |
+
]
|
| 18 |
+
norm_cfg = dict(type='SyncBN', requires_grad=True)
|
| 19 |
+
|
| 20 |
+
model = dict(
|
| 21 |
+
type='FViT',
|
| 22 |
+
backbone=dict(
|
| 23 |
+
type='EvaCLIPViT',
|
| 24 |
+
model_name='EVA02-CLIP-L-14-336',
|
| 25 |
+
pretrained='/opt/tiger/xiaomoguhzz/EVA02_CLIP_L_336_psz14_s6B.pt',
|
| 26 |
+
norm_cfg=norm_cfg,
|
| 27 |
+
out_indices=[6, 10, 14, 23],
|
| 28 |
+
feature_mode='csa'), # DeCLIP: Q*Q^T + K*K^T, 无 scale, 无残差, 无 MLP
|
| 29 |
+
neck=dict(
|
| 30 |
+
type='FPN',
|
| 31 |
+
in_channels=[1024, 1024, 1024, 1024],
|
| 32 |
+
out_channels=256,
|
| 33 |
+
num_outs=5,
|
| 34 |
+
norm_cfg=norm_cfg),
|
| 35 |
+
rpn_head=dict(
|
| 36 |
+
type='RPNHead',
|
| 37 |
+
in_channels=256,
|
| 38 |
+
feat_channels=256,
|
| 39 |
+
anchor_generator=dict(
|
| 40 |
+
type='AnchorGenerator',
|
| 41 |
+
scales=[8],
|
| 42 |
+
ratios=[0.5, 1.0, 2.0],
|
| 43 |
+
strides=[3.5, 7, 14, 28, 56]),
|
| 44 |
+
bbox_coder=dict(
|
| 45 |
+
type='DeltaXYWHBBoxCoder',
|
| 46 |
+
target_means=[0.0, 0.0, 0.0, 0.0],
|
| 47 |
+
target_stds=[1.0, 1.0, 1.0, 1.0]),
|
| 48 |
+
loss_cls=dict(
|
| 49 |
+
type='CrossEntropyLoss', use_sigmoid=True, loss_weight=1.0),
|
| 50 |
+
loss_bbox=dict(type='L1Loss', loss_weight=1.0),
|
| 51 |
+
num_convs=2),
|
| 52 |
+
roi_head=dict(
|
| 53 |
+
type='FViTRoIHead',
|
| 54 |
+
bbox_roi_extractor=dict(
|
| 55 |
+
type='SingleRoIExtractor',
|
| 56 |
+
roi_layer=dict(type='RoIAlign', output_size=7, sampling_ratio=0),
|
| 57 |
+
out_channels=256,
|
| 58 |
+
featmap_strides=[3.5, 7, 14, 28]),
|
| 59 |
+
bbox_head=dict(
|
| 60 |
+
type='FViTBBoxHead',
|
| 61 |
+
in_channels=256,
|
| 62 |
+
fc_out_channels=768,
|
| 63 |
+
roi_feat_size=7,
|
| 64 |
+
num_classes=num_classes,
|
| 65 |
+
bbox_coder=dict(
|
| 66 |
+
type='DeltaXYWHBBoxCoder',
|
| 67 |
+
target_means=[0.0, 0.0, 0.0, 0.0],
|
| 68 |
+
target_stds=[0.1, 0.1, 0.2, 0.2]),
|
| 69 |
+
reg_class_agnostic=True,
|
| 70 |
+
loss_cls=dict(
|
| 71 |
+
type='CustomCrossEntropyLoss',
|
| 72 |
+
use_sigmoid=False,
|
| 73 |
+
loss_weight=1.0,
|
| 74 |
+
class_weight=class_weight),
|
| 75 |
+
loss_bbox=dict(type='L1Loss', loss_weight=1.0),
|
| 76 |
+
norm_cfg=norm_cfg,
|
| 77 |
+
learned_temperature=50.0,
|
| 78 |
+
vlm_temperature=75.0,
|
| 79 |
+
alpha=0.1,
|
| 80 |
+
beta=0.8,
|
| 81 |
+
# Single Prompt embedding (EVA-L)
|
| 82 |
+
class_embed='/mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/prompt_ensemble_ablation/embeddings/coco_eva02_clip_l_14_336_eva_single_prompt.pt',
|
| 83 |
+
force_reload_embed=True,
|
| 84 |
+
seen_classes='datasets/mscoco_seen_classes.json',
|
| 85 |
+
all_classes='datasets/mscoco_65_classes.json',
|
| 86 |
+
num_shared_convs=4,
|
| 87 |
+
num_shared_fcs=2,
|
| 88 |
+
num_cls_fcs=1,
|
| 89 |
+
num_reg_fcs=1),
|
| 90 |
+
vlm_roi_extractor=dict(
|
| 91 |
+
type='SingleRoIExtractor',
|
| 92 |
+
roi_layer=dict(
|
| 93 |
+
type='RoIAlign',
|
| 94 |
+
output_size=1,
|
| 95 |
+
sampling_ratio=0,
|
| 96 |
+
use_torchvision=True),
|
| 97 |
+
out_channels=768,
|
| 98 |
+
featmap_strides=[14])),
|
| 99 |
+
train_cfg=dict(
|
| 100 |
+
rpn=dict(
|
| 101 |
+
assigner=dict(
|
| 102 |
+
type='MaxIoUAssigner',
|
| 103 |
+
pos_iou_thr=0.7,
|
| 104 |
+
neg_iou_thr=0.3,
|
| 105 |
+
min_pos_iou=0.3,
|
| 106 |
+
match_low_quality=True,
|
| 107 |
+
ignore_iof_thr=-1),
|
| 108 |
+
sampler=dict(
|
| 109 |
+
type='RandomSampler',
|
| 110 |
+
num=256,
|
| 111 |
+
pos_fraction=0.5,
|
| 112 |
+
neg_pos_ub=-1,
|
| 113 |
+
add_gt_as_proposals=False),
|
| 114 |
+
allowed_border=-1,
|
| 115 |
+
pos_weight=-1,
|
| 116 |
+
debug=False),
|
| 117 |
+
rpn_proposal=dict(
|
| 118 |
+
nms_pre=2000,
|
| 119 |
+
max_per_img=1000,
|
| 120 |
+
nms=dict(type='nms', iou_threshold=0.7),
|
| 121 |
+
min_bbox_size=0),
|
| 122 |
+
rcnn=dict(
|
| 123 |
+
assigner=dict(
|
| 124 |
+
type='MaxIoUAssigner',
|
| 125 |
+
pos_iou_thr=0.5,
|
| 126 |
+
neg_iou_thr=0.5,
|
| 127 |
+
min_pos_iou=0.5,
|
| 128 |
+
match_low_quality=False,
|
| 129 |
+
ignore_iof_thr=-1),
|
| 130 |
+
sampler=dict(
|
| 131 |
+
type='RandomSampler',
|
| 132 |
+
num=512,
|
| 133 |
+
pos_fraction=0.25,
|
| 134 |
+
neg_pos_ub=-1,
|
| 135 |
+
add_gt_as_proposals=True),
|
| 136 |
+
pos_weight=-1,
|
| 137 |
+
debug=False)),
|
| 138 |
+
test_cfg=dict(
|
| 139 |
+
rpn=dict(
|
| 140 |
+
nms_pre=2000,
|
| 141 |
+
max_per_img=1000,
|
| 142 |
+
nms=dict(type='nms', iou_threshold=0.7),
|
| 143 |
+
min_bbox_size=0),
|
| 144 |
+
rcnn=dict(
|
| 145 |
+
score_thr=0.01,
|
| 146 |
+
nms=dict(type='nms', iou_threshold=0.4),
|
| 147 |
+
max_per_img=100)))
|
| 148 |
+
|
| 149 |
+
checkpoint_config = dict(interval=1)
|
| 150 |
+
log_config = dict(interval=50, hooks=[dict(type='TextLoggerHook')])
|
| 151 |
+
dist_params = dict(backend='nccl')
|
| 152 |
+
log_level = 'INFO'
|
| 153 |
+
load_from = None
|
| 154 |
+
resume_from = None
|
| 155 |
+
workflow = [('train', 1)]
|
| 156 |
+
opencv_num_threads = 0
|
| 157 |
+
mp_start_method = 'fork'
|
| 158 |
+
auto_scale_lr = dict(enable=True, base_batch_size=64)
|
| 159 |
+
|
| 160 |
+
dataset_type = 'CocoDatasetOV'
|
| 161 |
+
image_size = (896, 896)
|
| 162 |
+
file_client_args = dict(backend='disk')
|
| 163 |
+
|
| 164 |
+
test_pipeline = [
|
| 165 |
+
dict(type='LoadImageFromFile', file_client_args=file_client_args),
|
| 166 |
+
dict(
|
| 167 |
+
type='MultiScaleFlipAug',
|
| 168 |
+
img_scale=image_size,
|
| 169 |
+
flip=False,
|
| 170 |
+
transforms=[
|
| 171 |
+
dict(type='Resize', keep_ratio=True),
|
| 172 |
+
dict(type='RandomFlip'),
|
| 173 |
+
dict(
|
| 174 |
+
type='Normalize',
|
| 175 |
+
mean=[122.771, 116.746, 104.094],
|
| 176 |
+
std=[68.501, 66.632, 70.323],
|
| 177 |
+
to_rgb=True),
|
| 178 |
+
dict(type='Pad', pad_to_square=True),
|
| 179 |
+
dict(type='ImageToTensor', keys=['img']),
|
| 180 |
+
dict(type='Collect', keys=['img'])
|
| 181 |
+
])
|
| 182 |
+
]
|
| 183 |
+
|
| 184 |
+
data = dict(
|
| 185 |
+
samples_per_gpu=2,
|
| 186 |
+
workers_per_gpu=4,
|
| 187 |
+
val=dict(
|
| 188 |
+
type=dataset_type,
|
| 189 |
+
ann_file='data/coco/zero-shot/instances_val2017_all_2.json',
|
| 190 |
+
img_prefix='data/coco/val2017/',
|
| 191 |
+
pipeline=test_pipeline),
|
| 192 |
+
test=dict(
|
| 193 |
+
type=dataset_type,
|
| 194 |
+
ann_file='data/coco/zero-shot/instances_val2017_all_2.json',
|
| 195 |
+
img_prefix='data/coco/val2017/',
|
| 196 |
+
pipeline=test_pipeline))
|
| 197 |
+
|
| 198 |
+
evaluation = dict(interval=1, metric=['bbox'])
|
| 199 |
+
optimizer = dict(type='AdamW', lr=0.0001, betas=(0.9, 0.999), weight_decay=0.1)
|
| 200 |
+
optimizer_config = dict(grad_clip=dict(max_norm=1.0, norm_type=2))
|
| 201 |
+
lr_config = dict(
|
| 202 |
+
policy='step',
|
| 203 |
+
warmup='linear',
|
| 204 |
+
warmup_iters=250,
|
| 205 |
+
warmup_ratio=0.001,
|
| 206 |
+
step=[100])
|
| 207 |
+
runner = dict(type='EpochBasedRunner', max_epochs=3)
|
| 208 |
+
fp16 = dict(loss_scale=512.0)
|
analysis/prompt_ensemble_ablation/configs/fvit_vitl14_ovcoco_ensemble.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# CLIPSelf EVA-L Ensemble 配置
|
| 2 |
+
# 基于 CLIPSelf EVA-ViT-L/14-336
|
| 3 |
+
#
|
| 4 |
+
# 注意:必须设置 force_reload_embed=True,否则会使用 checkpoint 中保存的 embedding
|
| 5 |
+
|
| 6 |
+
custom_imports = dict(
|
| 7 |
+
imports=['datasets', 'models'],
|
| 8 |
+
allow_failed_imports=False
|
| 9 |
+
)
|
| 10 |
+
|
| 11 |
+
_base_ = '../../CLIPSelf/F-ViT/configs/ov_coco/fvit_vitl14_upsample_fpn_bs64_3e_ovcoco_eva_original.py'
|
| 12 |
+
|
| 13 |
+
model = dict(
|
| 14 |
+
backbone=dict(
|
| 15 |
+
pretrained='/opt/tiger/xiaomoguhzz/EVA02_CLIP_L_336_psz14_s6B.pt',
|
| 16 |
+
feature_mode='maskclip',
|
| 17 |
+
),
|
| 18 |
+
roi_head=dict(
|
| 19 |
+
bbox_head=dict(
|
| 20 |
+
# 使用 prompt ensemble embedding
|
| 21 |
+
class_embed='/mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/prompt_ensemble_ablation/embeddings/coco_eva02_clip_l_14_336_eva_ensemble.pt',
|
| 22 |
+
# 强制从配置文件重新加载 embedding,忽略 checkpoint 中保存的 embedding
|
| 23 |
+
force_reload_embed=True,
|
| 24 |
+
),
|
| 25 |
+
),
|
| 26 |
+
)
|
analysis/prompt_ensemble_ablation/configs/fvit_vitl14_ovcoco_maskclip_ensemble.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# MaskCLIP EVA-L Ensemble 配置
|
| 2 |
+
# 使用原始 EVA-CLIP Large (不经过 CLIPSelf 训练)
|
| 3 |
+
#
|
| 4 |
+
# 注意:必须设置 force_reload_embed=True
|
| 5 |
+
|
| 6 |
+
custom_imports = dict(
|
| 7 |
+
imports=['datasets', 'models'],
|
| 8 |
+
allow_failed_imports=False
|
| 9 |
+
)
|
| 10 |
+
|
| 11 |
+
_base_ = '../../CLIPSelf/F-ViT/configs/ov_coco/fvit_vitl14_upsample_fpn_bs64_3e_ovcoco_eva_original.py'
|
| 12 |
+
|
| 13 |
+
model = dict(
|
| 14 |
+
backbone=dict(
|
| 15 |
+
pretrained='/opt/tiger/xiaomoguhzz/EVA02_CLIP_L_336_psz14_s6B.pt',
|
| 16 |
+
feature_mode='maskclip',
|
| 17 |
+
),
|
| 18 |
+
roi_head=dict(
|
| 19 |
+
bbox_head=dict(
|
| 20 |
+
# 使用 prompt ensemble embedding
|
| 21 |
+
class_embed='/mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/prompt_ensemble_ablation/embeddings/coco_eva02_clip_l_14_336_eva_ensemble.pt',
|
| 22 |
+
# 强制从配置文件重新加载 embedding
|
| 23 |
+
force_reload_embed=True,
|
| 24 |
+
),
|
| 25 |
+
),
|
| 26 |
+
)
|
analysis/prompt_ensemble_ablation/configs/fvit_vitl14_ovcoco_maskclip_single_prompt.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# MaskCLIP EVA-L Single Prompt 消融实验配置
|
| 2 |
+
# 使用原始 EVA-CLIP Large (不经过 CLIPSelf 训练)
|
| 3 |
+
#
|
| 4 |
+
# 注意:必须设置 force_reload_embed=True
|
| 5 |
+
|
| 6 |
+
custom_imports = dict(
|
| 7 |
+
imports=['datasets', 'models'],
|
| 8 |
+
allow_failed_imports=False
|
| 9 |
+
)
|
| 10 |
+
|
| 11 |
+
_base_ = '../../CLIPSelf/F-ViT/configs/ov_coco/fvit_vitl14_upsample_fpn_bs64_3e_ovcoco_eva_original.py'
|
| 12 |
+
|
| 13 |
+
model = dict(
|
| 14 |
+
backbone=dict(
|
| 15 |
+
pretrained='/opt/tiger/xiaomoguhzz/EVA02_CLIP_L_336_psz14_s6B.pt',
|
| 16 |
+
feature_mode='maskclip',
|
| 17 |
+
),
|
| 18 |
+
roi_head=dict(
|
| 19 |
+
bbox_head=dict(
|
| 20 |
+
# 使用 single prompt embedding (消融实验)
|
| 21 |
+
class_embed='/mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/prompt_ensemble_ablation/embeddings/coco_eva02_clip_l_14_336_eva_single_prompt.pt',
|
| 22 |
+
# 强制从配置文件重新加载 embedding
|
| 23 |
+
force_reload_embed=True,
|
| 24 |
+
),
|
| 25 |
+
),
|
| 26 |
+
)
|
analysis/prompt_ensemble_ablation/configs/fvit_vitl14_ovcoco_single_prompt.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# CLIPSelf EVA-L Single Prompt 消融实验配置
|
| 2 |
+
# 基于 CLIPSelf EVA-ViT-L/14-336
|
| 3 |
+
#
|
| 4 |
+
# 注意:必须设置 force_reload_embed=True,否则会使用 checkpoint 中保存的 embedding
|
| 5 |
+
|
| 6 |
+
custom_imports = dict(
|
| 7 |
+
imports=['datasets', 'models'],
|
| 8 |
+
allow_failed_imports=False
|
| 9 |
+
)
|
| 10 |
+
|
| 11 |
+
_base_ = '../../CLIPSelf/F-ViT/configs/ov_coco/fvit_vitl14_upsample_fpn_bs64_3e_ovcoco_eva_original.py'
|
| 12 |
+
|
| 13 |
+
model = dict(
|
| 14 |
+
backbone=dict(
|
| 15 |
+
pretrained='/opt/tiger/xiaomoguhzz/EVA02_CLIP_L_336_psz14_s6B.pt',
|
| 16 |
+
feature_mode='maskclip',
|
| 17 |
+
),
|
| 18 |
+
roi_head=dict(
|
| 19 |
+
bbox_head=dict(
|
| 20 |
+
# 使用 single prompt embedding (消融实验)
|
| 21 |
+
class_embed='/mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/prompt_ensemble_ablation/embeddings/coco_eva02_clip_l_14_336_eva_single_prompt.pt',
|
| 22 |
+
# 强制从配置文件重新加载 embedding,忽略 checkpoint 中保存的 embedding
|
| 23 |
+
force_reload_embed=True,
|
| 24 |
+
),
|
| 25 |
+
),
|
| 26 |
+
)
|
analysis/prompt_ensemble_ablation/prompt_ensemble_ablation_results.xlsx
ADDED
|
Binary file (7.81 kB). View file
|
|
|
analysis/prompt_ensemble_ablation/results/clearclip_b_results.txt
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
================================================
|
| 2 |
+
ClearCLIP-B (QQ mode) Ablation Results
|
| 3 |
+
Date: Thu Jan 22 04:26:36 AM UTC 2026
|
| 4 |
+
================================================
|
| 5 |
+
|
| 6 |
+
## clearclip_evab_single
|
| 7 |
+
Config: fvit_vitb16_ovcoco_clearclip_single_prompt.py
|
| 8 |
+
|
| 9 |
+
Results:
|
| 10 |
+
OrderedDict([('base_ap50', 43.736), ('novel_ap50', 26.62), ('all_ap50', 39.259), ('bbox_mAP', 0.201), ('bbox_mAP_50', 0.393), ('bbox_mAP_75', 0.19), ('bbox_mAP_s', 0.086), ('bbox_mAP_m', 0.205), ('bbox_mAP_l', 0.318), ('bbox_mAP_copypaste', '0.201 0.393 0.190 0.086 0.205 0.318')])
|
| 11 |
+
|
| 12 |
+
----------------------------------------
|
| 13 |
+
|
| 14 |
+
## clearclip_evab_ensemble
|
| 15 |
+
Config: fvit_vitb16_ovcoco_clearclip_ensemble.py
|
| 16 |
+
|
| 17 |
+
Results:
|
| 18 |
+
OrderedDict([('base_ap50', 43.999), ('novel_ap50', 26.743), ('all_ap50', 39.486), ('bbox_mAP', 0.203), ('bbox_mAP_50', 0.395), ('bbox_mAP_75', 0.193), ('bbox_mAP_s', 0.087), ('bbox_mAP_m', 0.207), ('bbox_mAP_l', 0.322), ('bbox_mAP_copypaste', '0.203 0.395 0.193 0.087 0.207 0.322')])
|
| 19 |
+
|
| 20 |
+
----------------------------------------
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
================================================
|
| 24 |
+
Summary
|
| 25 |
+
================================================
|
| 26 |
+
|
| 27 |
+
| Model | Method | base_ap50 | novel_ap50 | all_ap50 | bbox_mAP |
|
| 28 |
+
|-------|--------|-----------|------------|----------|----------|
|
| 29 |
+
| ClearCLIP-B | Single | 43.736 | 26.62 | 39.259 | 0.201 |
|
| 30 |
+
| ClearCLIP-B | Ensemble | 43.999 | 26.743 | 39.486 | 0.203 |
|
| 31 |
+
|
| 32 |
+
Completed at: Thu Jan 22 04:30:51 AM UTC 2026
|
analysis/prompt_ensemble_ablation/results/clearclip_l_results.txt
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
================================================
|
| 2 |
+
ClearCLIP-L (QQ mode) Ablation Results
|
| 3 |
+
Date: Thu Jan 22 06:40:03 AM UTC 2026
|
| 4 |
+
================================================
|
| 5 |
+
|
| 6 |
+
## clearclip_eval_single
|
| 7 |
+
Config: fvit_vitl14_ovcoco_clearclip_single_prompt.py
|
| 8 |
+
|
| 9 |
+
Results:
|
| 10 |
+
OrderedDict([('base_ap50', 55.841), ('novel_ap50', 27.962), ('all_ap50', 48.549), ('bbox_mAP', 0.25), ('bbox_mAP_50', 0.485), ('bbox_mAP_75', 0.238), ('bbox_mAP_s', 0.155), ('bbox_mAP_m', 0.275), ('bbox_mAP_l', 0.35), ('bbox_mAP_copypaste', '0.250 0.485 0.238 0.155 0.275 0.350')])
|
| 11 |
+
|
| 12 |
+
----------------------------------------
|
| 13 |
+
|
| 14 |
+
## clearclip_eval_ensemble
|
| 15 |
+
Config: fvit_vitl14_ovcoco_clearclip_ensemble.py
|
| 16 |
+
|
| 17 |
+
Results:
|
| 18 |
+
OrderedDict([('base_ap50', 56.091), ('novel_ap50', 30.003), ('all_ap50', 49.268), ('bbox_mAP', 0.255), ('bbox_mAP_50', 0.493), ('bbox_mAP_75', 0.244), ('bbox_mAP_s', 0.156), ('bbox_mAP_m', 0.282), ('bbox_mAP_l', 0.356), ('bbox_mAP_copypaste', '0.255 0.493 0.244 0.156 0.282 0.356')])
|
| 19 |
+
|
| 20 |
+
----------------------------------------
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
================================================
|
| 24 |
+
Summary
|
| 25 |
+
================================================
|
| 26 |
+
|
| 27 |
+
| Model | Method | base_ap50 | novel_ap50 | all_ap50 | bbox_mAP |
|
| 28 |
+
|-------|--------|-----------|------------|----------|----------|
|
| 29 |
+
| ClearCLIP-L | Single | 55.841 | 27.962 | 48.549 | 0.25 |
|
| 30 |
+
| ClearCLIP-L | Ensemble | 56.091 | 30.003 | 49.268 | 0.255 |
|
| 31 |
+
|
| 32 |
+
Completed at: Thu Jan 22 06:44:06 AM UTC 2026
|
analysis/prompt_ensemble_ablation/results/declip_ablation_results.txt
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
================================================
|
| 2 |
+
DeCLIP Prompt Ensemble Ablation Results
|
| 3 |
+
Date: Thu Jan 22 03:46:09 AM UTC 2026
|
| 4 |
+
================================================
|
| 5 |
+
|
| 6 |
+
## declip_evab_single_prompt
|
| 7 |
+
Config: fvit_vitb16_ovcoco_declip_single_prompt.py
|
| 8 |
+
Checkpoint: EVAB_dinov2B_epoch2.pth
|
| 9 |
+
|
| 10 |
+
Results:
|
| 11 |
+
OrderedDict([('base_ap50', 56.66), ('novel_ap50', 43.644), ('all_ap50', 53.256), ('bbox_mAP', 0.288), ('bbox_mAP_50', 0.533), ('bbox_mAP_75', 0.284), ('bbox_mAP_s', 0.152), ('bbox_mAP_m', 0.315), ('bbox_mAP_l', 0.408), ('bbox_mAP_copypaste', '0.288 0.533 0.284 0.152 0.315 0.408')])
|
| 12 |
+
|
| 13 |
+
----------------------------------------
|
| 14 |
+
|
| 15 |
+
## declip_evab_ensemble
|
| 16 |
+
Config: fvit_vitb16_ovcoco_declip_ensemble.py
|
| 17 |
+
Checkpoint: EVAB_dinov2B_epoch2.pth
|
| 18 |
+
|
| 19 |
+
Results:
|
| 20 |
+
OrderedDict([('base_ap50', 56.718), ('novel_ap50', 43.634), ('all_ap50', 53.296), ('bbox_mAP', 0.289), ('bbox_mAP_50', 0.533), ('bbox_mAP_75', 0.284), ('bbox_mAP_s', 0.154), ('bbox_mAP_m', 0.316), ('bbox_mAP_l', 0.41), ('bbox_mAP_copypaste', '0.289 0.533 0.284 0.154 0.316 0.410')])
|
| 21 |
+
|
| 22 |
+
----------------------------------------
|
| 23 |
+
|
| 24 |
+
## declip_eval_single_prompt
|
| 25 |
+
Config: fvit_vitl14_ovcoco_declip_single_prompt.py
|
| 26 |
+
Checkpoint: EVAL_dinov2L_epoch3.pth
|
| 27 |
+
|
| 28 |
+
Results:
|
| 29 |
+
OrderedDict([('base_ap50', 65.598), ('novel_ap50', 49.358), ('all_ap50', 61.35), ('bbox_mAP', 0.347), ('bbox_mAP_50', 0.614), ('bbox_mAP_75', 0.358), ('bbox_mAP_s', 0.252), ('bbox_mAP_m', 0.382), ('bbox_mAP_l', 0.442), ('bbox_mAP_copypaste', '0.347 0.614 0.358 0.252 0.382 0.442')])
|
| 30 |
+
|
| 31 |
+
----------------------------------------
|
| 32 |
+
|
| 33 |
+
## declip_eval_ensemble
|
| 34 |
+
Config: fvit_vitl14_ovcoco_declip_ensemble.py
|
| 35 |
+
Checkpoint: EVAL_dinov2L_epoch3.pth
|
| 36 |
+
|
| 37 |
+
Results:
|
| 38 |
+
OrderedDict([('base_ap50', 65.767), ('novel_ap50', 50.327), ('all_ap50', 61.729), ('bbox_mAP', 0.349), ('bbox_mAP_50', 0.617), ('bbox_mAP_75', 0.361), ('bbox_mAP_s', 0.255), ('bbox_mAP_m', 0.383), ('bbox_mAP_l', 0.446), ('bbox_mAP_copypaste', '0.349 0.617 0.361 0.255 0.383 0.446')])
|
| 39 |
+
|
| 40 |
+
----------------------------------------
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
================================================
|
| 44 |
+
Summary
|
| 45 |
+
================================================
|
| 46 |
+
|
| 47 |
+
| Model | Method | base_ap50 | novel_ap50 | all_ap50 | bbox_mAP |
|
| 48 |
+
|-------|--------|-----------|------------|----------|----------|
|
| 49 |
+
| DeCLIP-B | Single | 56.66 | 43.644 | 53.256 | 0.288 |
|
| 50 |
+
| DeCLIP-B | Ensemble | 56.718 | 43.634 | 53.296 | 0.289 |
|
| 51 |
+
| DeCLIP-L | Single | 65.598 | 49.358 | 61.35 | 0.347 |
|
| 52 |
+
| DeCLIP-L | Ensemble | 65.767 | 50.327 | 61.729 | 0.349 |
|
| 53 |
+
|
| 54 |
+
Completed at: Thu Jan 22 03:53:32 AM UTC 2026
|
analysis/prompt_ensemble_ablation/results/maskclip_b_clipself_l_results.txt
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
================================================
|
| 2 |
+
MaskCLIP-B + CLIPSelf-L Ablation Results
|
| 3 |
+
Date: Thu Jan 22 04:10:11 AM UTC 2026
|
| 4 |
+
================================================
|
| 5 |
+
|
| 6 |
+
## maskclip_evab_single
|
| 7 |
+
Config: fvit_vitb16_ovcoco_maskclip_single_prompt.py
|
| 8 |
+
|
| 9 |
+
Results:
|
| 10 |
+
OrderedDict([('base_ap50', 43.4), ('novel_ap50', 17.65), ('all_ap50', 36.665), ('bbox_mAP', 0.187), ('bbox_mAP_50', 0.367), ('bbox_mAP_75', 0.173), ('bbox_mAP_s', 0.081), ('bbox_mAP_m', 0.184), ('bbox_mAP_l', 0.305), ('bbox_mAP_copypaste', '0.187 0.367 0.173 0.081 0.184 0.305')])
|
| 11 |
+
|
| 12 |
+
----------------------------------------
|
| 13 |
+
|
| 14 |
+
## maskclip_evab_ensemble
|
| 15 |
+
Config: fvit_vitb16_ovcoco_maskclip_ensemble.py
|
| 16 |
+
|
| 17 |
+
Results:
|
| 18 |
+
OrderedDict([('base_ap50', 43.815), ('novel_ap50', 17.386), ('all_ap50', 36.903), ('bbox_mAP', 0.188), ('bbox_mAP_50', 0.369), ('bbox_mAP_75', 0.175), ('bbox_mAP_s', 0.081), ('bbox_mAP_m', 0.186), ('bbox_mAP_l', 0.306), ('bbox_mAP_copypaste', '0.188 0.369 0.175 0.081 0.186 0.306')])
|
| 19 |
+
|
| 20 |
+
----------------------------------------
|
| 21 |
+
|
| 22 |
+
## clipself_eval_single
|
| 23 |
+
Config: fvit_vitl14_ovcoco_single_prompt.py
|
| 24 |
+
|
| 25 |
+
Results:
|
| 26 |
+
OrderedDict([('base_ap50', 63.843), ('novel_ap50', 44.475), ('all_ap50', 58.777), ('bbox_mAP', 0.329), ('bbox_mAP_50', 0.588), ('bbox_mAP_75', 0.335), ('bbox_mAP_s', 0.229), ('bbox_mAP_m', 0.37), ('bbox_mAP_l', 0.418), ('bbox_mAP_copypaste', '0.329 0.588 0.335 0.229 0.370 0.418')])
|
| 27 |
+
|
| 28 |
+
----------------------------------------
|
| 29 |
+
|
| 30 |
+
## clipself_eval_ensemble
|
| 31 |
+
Config: fvit_vitl14_ovcoco_ensemble.py
|
| 32 |
+
|
| 33 |
+
Results:
|
| 34 |
+
OrderedDict([('base_ap50', 64.147), ('novel_ap50', 44.508), ('all_ap50', 59.011), ('bbox_mAP', 0.331), ('bbox_mAP_50', 0.59), ('bbox_mAP_75', 0.339), ('bbox_mAP_s', 0.228), ('bbox_mAP_m', 0.372), ('bbox_mAP_l', 0.422), ('bbox_mAP_copypaste', '0.331 0.590 0.339 0.228 0.372 0.422')])
|
| 35 |
+
|
| 36 |
+
----------------------------------------
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
================================================
|
| 40 |
+
Summary
|
| 41 |
+
================================================
|
| 42 |
+
|
| 43 |
+
| Model | Method | base_ap50 | novel_ap50 | all_ap50 | bbox_mAP |
|
| 44 |
+
|-------|--------|-----------|------------|----------|----------|
|
| 45 |
+
| MaskCLIP-B | Single | 43.4 | 17.65 | 36.665 | 0.187 |
|
| 46 |
+
| MaskCLIP-B | Ensemble | 43.815 | 17.386 | 36.903 | 0.188 |
|
| 47 |
+
| CLIPSelf-L | Single | 63.843 | 44.475 | 58.777 | 0.329 |
|
| 48 |
+
| CLIPSelf-L | Ensemble | 64.147 | 44.508 | 59.011 | 0.331 |
|
| 49 |
+
|
| 50 |
+
Completed at: Thu Jan 22 04:19:18 AM UTC 2026
|
analysis/prompt_ensemble_ablation/scripts/generate_all_embeddings.sh
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# 生成所有模型的 single prompt 和 ensemble embeddings
|
| 3 |
+
# 用于 prompt ensemble 消融实验
|
| 4 |
+
|
| 5 |
+
set -e
|
| 6 |
+
|
| 7 |
+
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
| 8 |
+
PROJECT_DIR="$(dirname "$SCRIPT_DIR")"
|
| 9 |
+
DECLIP_ROOT="/mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private"
|
| 10 |
+
FVIT_DIR="$DECLIP_ROOT/CLIPSelf/F-ViT"
|
| 11 |
+
|
| 12 |
+
# 设置 PYTHONPATH 以使用项目中的 open_clip
|
| 13 |
+
export PYTHONPATH="$DECLIP_ROOT/src:$PYTHONPATH"
|
| 14 |
+
|
| 15 |
+
# COCO 类别文件 (80 classes)
|
| 16 |
+
CLASS_FILE="$FVIT_DIR/datasets/mscoco_all_classes.json"
|
| 17 |
+
|
| 18 |
+
# 输出目录
|
| 19 |
+
OUT_DIR="$PROJECT_DIR/embeddings"
|
| 20 |
+
|
| 21 |
+
# EVA-CLIP 权重路径 (需要先运行 build_env/download_eva_clip.sh 下载)
|
| 22 |
+
EVA_B_CKPT="/opt/tiger/xiaomoguhzz/EVA02_CLIP_B_psz16_s8B.pt"
|
| 23 |
+
EVA_L_CKPT="/opt/tiger/xiaomoguhzz/EVA02_CLIP_L_336_psz14_s6B.pt"
|
| 24 |
+
|
| 25 |
+
echo "=========================================="
|
| 26 |
+
echo "Prompt Ensemble Ablation: Generate Embeddings"
|
| 27 |
+
echo "=========================================="
|
| 28 |
+
echo "Output directory: $OUT_DIR"
|
| 29 |
+
echo ""
|
| 30 |
+
|
| 31 |
+
# 检查 EVA-CLIP 权重是否存在
|
| 32 |
+
if [ ! -f "$EVA_B_CKPT" ]; then
|
| 33 |
+
echo "WARNING: EVA-CLIP Base weights not found at $EVA_B_CKPT"
|
| 34 |
+
echo "Please run: bash build_env/download_eva_clip.sh"
|
| 35 |
+
echo "Skipping EVA-CLIP models..."
|
| 36 |
+
SKIP_EVA=true
|
| 37 |
+
else
|
| 38 |
+
SKIP_EVA=false
|
| 39 |
+
fi
|
| 40 |
+
|
| 41 |
+
# 1. EVA-CLIP Base
|
| 42 |
+
if [ "$SKIP_EVA" = false ]; then
|
| 43 |
+
echo "[1/4] EVA-CLIP Base (EVA02-CLIP-B-16)"
|
| 44 |
+
python "$SCRIPT_DIR/generate_single_prompt_embeddings.py" \
|
| 45 |
+
--class_file "$CLASS_FILE" \
|
| 46 |
+
--out_dir "$OUT_DIR" \
|
| 47 |
+
--model_name EVA02-CLIP-B-16 \
|
| 48 |
+
--pretrained eva \
|
| 49 |
+
--cache_dir "$EVA_B_CKPT" \
|
| 50 |
+
--mode both
|
| 51 |
+
else
|
| 52 |
+
echo "[1/4] EVA-CLIP Base - SKIPPED (weights not found)"
|
| 53 |
+
fi
|
| 54 |
+
|
| 55 |
+
# 2. EVA-CLIP Large
|
| 56 |
+
if [ "$SKIP_EVA" = false ] && [ -f "$EVA_L_CKPT" ]; then
|
| 57 |
+
echo ""
|
| 58 |
+
echo "[2/4] EVA-CLIP Large (EVA02-CLIP-L-14-336)"
|
| 59 |
+
python "$SCRIPT_DIR/generate_single_prompt_embeddings.py" \
|
| 60 |
+
--class_file "$CLASS_FILE" \
|
| 61 |
+
--out_dir "$OUT_DIR" \
|
| 62 |
+
--model_name EVA02-CLIP-L-14-336 \
|
| 63 |
+
--pretrained eva \
|
| 64 |
+
--cache_dir "$EVA_L_CKPT" \
|
| 65 |
+
--mode both
|
| 66 |
+
else
|
| 67 |
+
echo ""
|
| 68 |
+
echo "[2/4] EVA-CLIP Large - SKIPPED (weights not found at $EVA_L_CKPT)"
|
| 69 |
+
fi
|
| 70 |
+
|
| 71 |
+
# 3. OpenAI CLIP Base (会自动下载)
|
| 72 |
+
echo ""
|
| 73 |
+
echo "[3/4] OpenAI CLIP Base (ViT-B-16)"
|
| 74 |
+
python "$SCRIPT_DIR/generate_single_prompt_embeddings.py" \
|
| 75 |
+
--class_file "$CLASS_FILE" \
|
| 76 |
+
--out_dir "$OUT_DIR" \
|
| 77 |
+
--model_name ViT-B-16 \
|
| 78 |
+
--pretrained openai \
|
| 79 |
+
--mode both
|
| 80 |
+
|
| 81 |
+
# 4. OpenAI CLIP Large (会自动下载)
|
| 82 |
+
echo ""
|
| 83 |
+
echo "[4/4] OpenAI CLIP Large (ViT-L-14)"
|
| 84 |
+
python "$SCRIPT_DIR/generate_single_prompt_embeddings.py" \
|
| 85 |
+
--class_file "$CLASS_FILE" \
|
| 86 |
+
--out_dir "$OUT_DIR" \
|
| 87 |
+
--model_name ViT-L-14 \
|
| 88 |
+
--pretrained openai \
|
| 89 |
+
--mode both
|
| 90 |
+
|
| 91 |
+
echo ""
|
| 92 |
+
echo "=========================================="
|
| 93 |
+
echo "All embeddings generated!"
|
| 94 |
+
echo "=========================================="
|
| 95 |
+
ls -lh "$OUT_DIR"
|
analysis/prompt_ensemble_ablation/scripts/generate_single_prompt_embeddings.py
ADDED
|
@@ -0,0 +1,224 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
生成不使用 Prompt Ensemble 的 Text Embeddings
|
| 4 |
+
用于消融实验:对比 prompt ensemble vs single prompt 的性能差异
|
| 5 |
+
|
| 6 |
+
背景:审稿人问题 (3) - optimization for misalignment (prompt engineering)
|
| 7 |
+
实验目的:验证 prompt ensemble 技术对 V-L 对齐的贡献
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
import argparse
|
| 11 |
+
import json
|
| 12 |
+
import os
|
| 13 |
+
import torch
|
| 14 |
+
from tqdm import tqdm
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def article(name):
|
| 18 |
+
return "an" if name[0] in "aeiou" else "a"
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def processed_name(name, rm_dot=False):
|
| 22 |
+
res = name.replace("_", " ").replace("/", " or ").lower()
|
| 23 |
+
if rm_dot:
|
| 24 |
+
res = res.rstrip(".")
|
| 25 |
+
return res
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
# 单模板 (用于消融实验)
|
| 29 |
+
SINGLE_TEMPLATE = "a photo of a {}."
|
| 30 |
+
|
| 31 |
+
# 多模板 (原始 prompt ensemble,用于对比)
|
| 32 |
+
MULTIPLE_TEMPLATES = [
|
| 33 |
+
"There is {article} {} in the scene.",
|
| 34 |
+
"There is the {} in the scene.",
|
| 35 |
+
"a photo of {article} {} in the scene.",
|
| 36 |
+
"a photo of the {} in the scene.",
|
| 37 |
+
"a photo of one {} in the scene.",
|
| 38 |
+
"itap of {article} {}.",
|
| 39 |
+
"itap of my {}.",
|
| 40 |
+
"itap of the {}.",
|
| 41 |
+
"a photo of {article} {}.",
|
| 42 |
+
"a photo of my {}.",
|
| 43 |
+
"a photo of the {}.",
|
| 44 |
+
"a photo of one {}.",
|
| 45 |
+
"a photo of many {}.",
|
| 46 |
+
"a good photo of {article} {}.",
|
| 47 |
+
"a good photo of the {}.",
|
| 48 |
+
"a bad photo of {article} {}.",
|
| 49 |
+
"a bad photo of the {}.",
|
| 50 |
+
"a photo of a nice {}.",
|
| 51 |
+
"a photo of the nice {}.",
|
| 52 |
+
"a photo of a cool {}.",
|
| 53 |
+
"a photo of the cool {}.",
|
| 54 |
+
"a photo of a weird {}.",
|
| 55 |
+
"a photo of the weird {}.",
|
| 56 |
+
"a photo of a small {}.",
|
| 57 |
+
"a photo of the small {}.",
|
| 58 |
+
"a photo of a large {}.",
|
| 59 |
+
"a photo of the large {}.",
|
| 60 |
+
"a photo of a clean {}.",
|
| 61 |
+
"a photo of the clean {}.",
|
| 62 |
+
"a photo of a dirty {}.",
|
| 63 |
+
"a photo of the dirty {}.",
|
| 64 |
+
"a bright photo of {article} {}.",
|
| 65 |
+
"a bright photo of the {}.",
|
| 66 |
+
"a dark photo of {article} {}.",
|
| 67 |
+
"a dark photo of the {}.",
|
| 68 |
+
"a photo of a hard to see {}.",
|
| 69 |
+
"a photo of the hard to see {}.",
|
| 70 |
+
"a low resolution photo of {article} {}.",
|
| 71 |
+
"a low resolution photo of the {}.",
|
| 72 |
+
"a cropped photo of {article} {}.",
|
| 73 |
+
"a cropped photo of the {}.",
|
| 74 |
+
"a close-up photo of {article} {}.",
|
| 75 |
+
"a close-up photo of the {}.",
|
| 76 |
+
"a jpeg corrupted photo of {article} {}.",
|
| 77 |
+
"a jpeg corrupted photo of the {}.",
|
| 78 |
+
"a blurry photo of {article} {}.",
|
| 79 |
+
"a blurry photo of the {}.",
|
| 80 |
+
"a pixelated photo of {article} {}.",
|
| 81 |
+
"a pixelated photo of the {}.",
|
| 82 |
+
"a black and white photo of the {}.",
|
| 83 |
+
"a black and white photo of {article} {}.",
|
| 84 |
+
"a plastic {}.",
|
| 85 |
+
"the plastic {}.",
|
| 86 |
+
"a toy {}.",
|
| 87 |
+
"the toy {}.",
|
| 88 |
+
"a plushie {}.",
|
| 89 |
+
"the plushie {}.",
|
| 90 |
+
"a cartoon {}.",
|
| 91 |
+
"the cartoon {}.",
|
| 92 |
+
"an embroidered {}.",
|
| 93 |
+
"the embroidered {}.",
|
| 94 |
+
"a painting of the {}.",
|
| 95 |
+
"a painting of a {}.",
|
| 96 |
+
]
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def build_text_embedding_single_prompt(categories, model, tokenizer, device='cuda'):
|
| 100 |
+
"""使用单一模板生成 text embedding (无 prompt ensemble)"""
|
| 101 |
+
with torch.no_grad():
|
| 102 |
+
all_text_embeddings = []
|
| 103 |
+
for category in tqdm(categories, desc="Single prompt"):
|
| 104 |
+
text = SINGLE_TEMPLATE.format(processed_name(category, rm_dot=True))
|
| 105 |
+
tokens = tokenizer([text])
|
| 106 |
+
if device == 'cuda':
|
| 107 |
+
tokens = tokens.cuda()
|
| 108 |
+
text_embedding = model.encode_text(tokens)
|
| 109 |
+
text_embedding = text_embedding / text_embedding.norm(dim=-1, keepdim=True)
|
| 110 |
+
all_text_embeddings.append(text_embedding.squeeze(0))
|
| 111 |
+
|
| 112 |
+
all_text_embeddings = torch.stack(all_text_embeddings, dim=0)
|
| 113 |
+
|
| 114 |
+
return all_text_embeddings
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def build_text_embedding_ensemble(categories, model, tokenizer, device='cuda'):
|
| 118 |
+
"""使用多模板生成 text embedding (prompt ensemble)"""
|
| 119 |
+
with torch.no_grad():
|
| 120 |
+
all_text_embeddings = []
|
| 121 |
+
for category in tqdm(categories, desc="Prompt ensemble"):
|
| 122 |
+
texts = [
|
| 123 |
+
template.format(
|
| 124 |
+
processed_name(category, rm_dot=True),
|
| 125 |
+
article=article(category)
|
| 126 |
+
)
|
| 127 |
+
for template in MULTIPLE_TEMPLATES
|
| 128 |
+
]
|
| 129 |
+
texts = [
|
| 130 |
+
"This is " + text if text.startswith("a") or text.startswith("the") else text
|
| 131 |
+
for text in texts
|
| 132 |
+
]
|
| 133 |
+
tokens = tokenizer(texts)
|
| 134 |
+
if device == 'cuda':
|
| 135 |
+
tokens = tokens.cuda()
|
| 136 |
+
text_embeddings = model.encode_text(tokens)
|
| 137 |
+
text_embeddings = text_embeddings / text_embeddings.norm(dim=-1, keepdim=True)
|
| 138 |
+
text_embedding = text_embeddings.mean(dim=0)
|
| 139 |
+
text_embedding = text_embedding / text_embedding.norm()
|
| 140 |
+
all_text_embeddings.append(text_embedding)
|
| 141 |
+
|
| 142 |
+
all_text_embeddings = torch.stack(all_text_embeddings, dim=0)
|
| 143 |
+
|
| 144 |
+
return all_text_embeddings
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def load_categories(class_file):
|
| 148 |
+
"""从类别 JSON 文件加载类别名称"""
|
| 149 |
+
print(f'Loading {class_file}')
|
| 150 |
+
with open(class_file, 'r') as f:
|
| 151 |
+
cat_names = json.load(f)
|
| 152 |
+
cat_names = cat_names + ['background']
|
| 153 |
+
print(f'Categories ({len(cat_names)}): {cat_names[:5]}...{cat_names[-3:]}')
|
| 154 |
+
return cat_names
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def main():
|
| 158 |
+
parser = argparse.ArgumentParser(description='Generate text embeddings with/without prompt ensemble')
|
| 159 |
+
parser.add_argument('--class_file', type=str, required=True, help='Path to class names JSON (e.g., mscoco_all_classes.json)')
|
| 160 |
+
parser.add_argument('--out_dir', type=str, required=True, help='Output directory for embeddings')
|
| 161 |
+
parser.add_argument('--model_name', type=str, required=True,
|
| 162 |
+
choices=['EVA02-CLIP-B-16', 'EVA02-CLIP-L-14-336', 'ViT-B-16', 'ViT-L-14'],
|
| 163 |
+
help='Model name')
|
| 164 |
+
parser.add_argument('--pretrained', type=str, required=True,
|
| 165 |
+
help='Pretrained source (eva, openai)')
|
| 166 |
+
parser.add_argument('--cache_dir', type=str, default='',
|
| 167 |
+
help='Path to checkpoint file (for EVA-CLIP)')
|
| 168 |
+
parser.add_argument('--mode', type=str, default='both', choices=['single', 'ensemble', 'both'],
|
| 169 |
+
help='Generate single prompt, ensemble, or both')
|
| 170 |
+
args = parser.parse_args()
|
| 171 |
+
|
| 172 |
+
# 加载类别
|
| 173 |
+
categories = load_categories(args.class_file)
|
| 174 |
+
|
| 175 |
+
# 加载模型
|
| 176 |
+
print(f'\nLoading model: {args.model_name} (pretrained={args.pretrained})')
|
| 177 |
+
from open_clip import create_model, get_tokenizer
|
| 178 |
+
|
| 179 |
+
model = create_model(
|
| 180 |
+
model_name=args.model_name,
|
| 181 |
+
pretrained=args.pretrained,
|
| 182 |
+
cache_dir=args.cache_dir if args.cache_dir else None
|
| 183 |
+
)
|
| 184 |
+
tokenizer = get_tokenizer(model_name=args.model_name)
|
| 185 |
+
|
| 186 |
+
device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
| 187 |
+
model = model.to(device)
|
| 188 |
+
model.eval()
|
| 189 |
+
|
| 190 |
+
# 确定输出文件名前缀
|
| 191 |
+
model_suffix = args.model_name.lower().replace('-', '_').replace('/', '_')
|
| 192 |
+
pretrained_suffix = args.pretrained.lower()
|
| 193 |
+
|
| 194 |
+
os.makedirs(args.out_dir, exist_ok=True)
|
| 195 |
+
|
| 196 |
+
# 生成 embeddings
|
| 197 |
+
if args.mode in ['single', 'both']:
|
| 198 |
+
print('\n=== Generating Single Prompt Embeddings ===')
|
| 199 |
+
single_embeddings = build_text_embedding_single_prompt(categories, model, tokenizer, device)
|
| 200 |
+
single_embeddings = single_embeddings.cpu().float()
|
| 201 |
+
print(f'Shape: {single_embeddings.shape}')
|
| 202 |
+
|
| 203 |
+
# 保存为 dict 格式 (与原始格式兼容)
|
| 204 |
+
single_dict = {k: v for k, v in zip(categories, single_embeddings)}
|
| 205 |
+
out_path = os.path.join(args.out_dir, f'coco_{model_suffix}_{pretrained_suffix}_single_prompt.pt')
|
| 206 |
+
torch.save(single_dict, out_path)
|
| 207 |
+
print(f'Saved: {out_path}')
|
| 208 |
+
|
| 209 |
+
if args.mode in ['ensemble', 'both']:
|
| 210 |
+
print('\n=== Generating Prompt Ensemble Embeddings ===')
|
| 211 |
+
ensemble_embeddings = build_text_embedding_ensemble(categories, model, tokenizer, device)
|
| 212 |
+
ensemble_embeddings = ensemble_embeddings.cpu().float()
|
| 213 |
+
print(f'Shape: {ensemble_embeddings.shape}')
|
| 214 |
+
|
| 215 |
+
ensemble_dict = {k: v for k, v in zip(categories, ensemble_embeddings)}
|
| 216 |
+
out_path = os.path.join(args.out_dir, f'coco_{model_suffix}_{pretrained_suffix}_ensemble.pt')
|
| 217 |
+
torch.save(ensemble_dict, out_path)
|
| 218 |
+
print(f'Saved: {out_path}')
|
| 219 |
+
|
| 220 |
+
print('\nDone!')
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
if __name__ == '__main__':
|
| 224 |
+
main()
|
analysis/prompt_ensemble_ablation/scripts/run_all_ablation.sh
ADDED
|
@@ -0,0 +1,211 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# Prompt Ensemble 消融实验完整测试脚本
|
| 3 |
+
# 包含: CLIPSelf (Base/Large), MaskCLIP (Base/Large), DeCLIP (Base/Large)
|
| 4 |
+
# 每个模型测试 Single Prompt vs Ensemble
|
| 5 |
+
|
| 6 |
+
set -e
|
| 7 |
+
|
| 8 |
+
# 路径配置
|
| 9 |
+
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
| 10 |
+
ABLATION_DIR="$(dirname "${SCRIPT_DIR}")"
|
| 11 |
+
FVIT_DIR="${ABLATION_DIR}/../CLIPSelf/F-ViT"
|
| 12 |
+
RESULT_DIR="${ABLATION_DIR}/results"
|
| 13 |
+
RESULT_FILE="${RESULT_DIR}/all_ablation_results.txt"
|
| 14 |
+
|
| 15 |
+
# ==================== 权重路径 ====================
|
| 16 |
+
# CLIPSelf 权重
|
| 17 |
+
CLIPSELF_B_CKPT="/opt/tiger/xiaomoguhzz/fvit_eva_vitb16_ovcoco_clipself_proposals.pth"
|
| 18 |
+
CLIPSELF_L_CKPT="/opt/tiger/xiaomoguhzz/fvit_eva_vitl14_ovcoco_clipself_proposals.pth"
|
| 19 |
+
|
| 20 |
+
# MaskCLIP 权重 (原始 EVA-CLIP,经过检测器训练)
|
| 21 |
+
MASKCLIP_B_CKPT="/mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/CLIPSelf/F-ViT/work_dirs/fvit_vitb16_ovcoco_maskclip/epoch_3.pth"
|
| 22 |
+
# MaskCLIP Large 权重 - 需要提供路径
|
| 23 |
+
MASKCLIP_L_CKPT="" # TODO: 填写 MaskCLIP Large 权重路径
|
| 24 |
+
|
| 25 |
+
# DeCLIP 权重
|
| 26 |
+
DECLIP_B_CKPT="/opt/tiger/xiaomoguhzz/declip2_ovcoco_detector/EVAB_dinov2B_epoch2.pth"
|
| 27 |
+
DECLIP_L_CKPT="/opt/tiger/xiaomoguhzz/declip2_ovcoco_detector/EVAL_dinov2L_epoch3.pth"
|
| 28 |
+
|
| 29 |
+
# ==================== 配置文件路径 ====================
|
| 30 |
+
CONFIG_DIR="${ABLATION_DIR}/configs"
|
| 31 |
+
|
| 32 |
+
# CLIPSelf 配置
|
| 33 |
+
CLIPSELF_B_SINGLE="${CONFIG_DIR}/fvit_vitb16_ovcoco_single_prompt.py"
|
| 34 |
+
CLIPSELF_B_ENSEMBLE="${CONFIG_DIR}/fvit_vitb16_ovcoco_ensemble.py"
|
| 35 |
+
CLIPSELF_L_SINGLE="${CONFIG_DIR}/fvit_vitl14_ovcoco_single_prompt.py"
|
| 36 |
+
CLIPSELF_L_ENSEMBLE="${CONFIG_DIR}/fvit_vitl14_ovcoco_ensemble.py"
|
| 37 |
+
|
| 38 |
+
# MaskCLIP 配置
|
| 39 |
+
MASKCLIP_B_SINGLE="${CONFIG_DIR}/fvit_vitb16_ovcoco_maskclip_single_prompt.py"
|
| 40 |
+
MASKCLIP_B_ENSEMBLE="${CONFIG_DIR}/fvit_vitb16_ovcoco_maskclip_ensemble.py"
|
| 41 |
+
MASKCLIP_L_SINGLE="${CONFIG_DIR}/fvit_vitl14_ovcoco_maskclip_single_prompt.py"
|
| 42 |
+
MASKCLIP_L_ENSEMBLE="${CONFIG_DIR}/fvit_vitl14_ovcoco_maskclip_ensemble.py"
|
| 43 |
+
|
| 44 |
+
# DeCLIP 配置
|
| 45 |
+
DECLIP_B_SINGLE="${CONFIG_DIR}/fvit_vitb16_ovcoco_declip_single_prompt.py"
|
| 46 |
+
DECLIP_B_ENSEMBLE="${CONFIG_DIR}/fvit_vitb16_ovcoco_declip_ensemble.py"
|
| 47 |
+
DECLIP_L_SINGLE="${CONFIG_DIR}/fvit_vitl14_ovcoco_declip_single_prompt.py"
|
| 48 |
+
DECLIP_L_ENSEMBLE="${CONFIG_DIR}/fvit_vitl14_ovcoco_declip_ensemble.py"
|
| 49 |
+
|
| 50 |
+
# 创建结果目录
|
| 51 |
+
mkdir -p "${RESULT_DIR}"
|
| 52 |
+
|
| 53 |
+
# 初始化结果文件
|
| 54 |
+
echo "================================================" > "${RESULT_FILE}"
|
| 55 |
+
echo "Prompt Ensemble Ablation - All Models Results" >> "${RESULT_FILE}"
|
| 56 |
+
echo "Date: $(date)" >> "${RESULT_FILE}"
|
| 57 |
+
echo "================================================" >> "${RESULT_FILE}"
|
| 58 |
+
echo "" >> "${RESULT_FILE}"
|
| 59 |
+
|
| 60 |
+
cd "${FVIT_DIR}"
|
| 61 |
+
export PYTHONPATH="$(pwd)/..":$PYTHONPATH
|
| 62 |
+
|
| 63 |
+
# 运行单个测试的函数
|
| 64 |
+
run_test() {
|
| 65 |
+
local name=$1
|
| 66 |
+
local config=$2
|
| 67 |
+
local checkpoint=$3
|
| 68 |
+
local tmpdir=$4
|
| 69 |
+
local log_file="${RESULT_DIR}/${name}.log"
|
| 70 |
+
|
| 71 |
+
# 检查权重是否存在
|
| 72 |
+
if [ ! -f "${checkpoint}" ]; then
|
| 73 |
+
echo "SKIP: ${name} - 权重不存在: ${checkpoint}"
|
| 74 |
+
echo "## ${name} - SKIPPED (权重不存在)" >> "${RESULT_FILE}"
|
| 75 |
+
echo "" >> "${RESULT_FILE}"
|
| 76 |
+
return
|
| 77 |
+
fi
|
| 78 |
+
|
| 79 |
+
echo ""
|
| 80 |
+
echo "================================================"
|
| 81 |
+
echo "Running: ${name}"
|
| 82 |
+
echo "Config: ${config}"
|
| 83 |
+
echo "Checkpoint: ${checkpoint}"
|
| 84 |
+
echo "================================================"
|
| 85 |
+
|
| 86 |
+
echo "## ${name}" >> "${RESULT_FILE}"
|
| 87 |
+
echo "Config: $(basename ${config})" >> "${RESULT_FILE}"
|
| 88 |
+
echo "Checkpoint: $(basename ${checkpoint})" >> "${RESULT_FILE}"
|
| 89 |
+
echo "" >> "${RESULT_FILE}"
|
| 90 |
+
|
| 91 |
+
# 运行测试并保存日志
|
| 92 |
+
torchrun --nproc_per_node=8 --master_port=12346 \
|
| 93 |
+
test.py \
|
| 94 |
+
"${config}" \
|
| 95 |
+
"${checkpoint}" \
|
| 96 |
+
--launcher pytorch \
|
| 97 |
+
--eval bbox \
|
| 98 |
+
--tmpdir "${tmpdir}" \
|
| 99 |
+
2>&1 | tee "${log_file}"
|
| 100 |
+
|
| 101 |
+
# 提取结果
|
| 102 |
+
echo "Results:" >> "${RESULT_FILE}"
|
| 103 |
+
grep -E "OrderedDict" "${log_file}" | tail -1 >> "${RESULT_FILE}"
|
| 104 |
+
echo "" >> "${RESULT_FILE}"
|
| 105 |
+
echo "----------------------------------------" >> "${RESULT_FILE}"
|
| 106 |
+
echo "" >> "${RESULT_FILE}"
|
| 107 |
+
|
| 108 |
+
echo "Completed: ${name}"
|
| 109 |
+
}
|
| 110 |
+
|
| 111 |
+
echo ""
|
| 112 |
+
echo "=========================================="
|
| 113 |
+
echo "开始 Prompt Ensemble 消融实验"
|
| 114 |
+
echo "=========================================="
|
| 115 |
+
|
| 116 |
+
# ==================== 1. CLIPSelf 测试 ====================
|
| 117 |
+
echo ""
|
| 118 |
+
echo "========== CLIPSelf Tests =========="
|
| 119 |
+
|
| 120 |
+
# CLIPSelf Base
|
| 121 |
+
run_test "clipself_evab_single" "${CLIPSELF_B_SINGLE}" "${CLIPSELF_B_CKPT}" "/tmp/clipself_b_single"
|
| 122 |
+
run_test "clipself_evab_ensemble" "${CLIPSELF_B_ENSEMBLE}" "${CLIPSELF_B_CKPT}" "/tmp/clipself_b_ensemble"
|
| 123 |
+
|
| 124 |
+
# CLIPSelf Large
|
| 125 |
+
run_test "clipself_eval_single" "${CLIPSELF_L_SINGLE}" "${CLIPSELF_L_CKPT}" "/tmp/clipself_l_single"
|
| 126 |
+
run_test "clipself_eval_ensemble" "${CLIPSELF_L_ENSEMBLE}" "${CLIPSELF_L_CKPT}" "/tmp/clipself_l_ensemble"
|
| 127 |
+
|
| 128 |
+
# ==================== 2. MaskCLIP 测试 ====================
|
| 129 |
+
echo ""
|
| 130 |
+
echo "========== MaskCLIP Tests =========="
|
| 131 |
+
|
| 132 |
+
# MaskCLIP Base
|
| 133 |
+
run_test "maskclip_evab_single" "${MASKCLIP_B_SINGLE}" "${MASKCLIP_B_CKPT}" "/tmp/maskclip_b_single"
|
| 134 |
+
run_test "maskclip_evab_ensemble" "${MASKCLIP_B_ENSEMBLE}" "${MASKCLIP_B_CKPT}" "/tmp/maskclip_b_ensemble"
|
| 135 |
+
|
| 136 |
+
# MaskCLIP Large (如果权重存在)
|
| 137 |
+
if [ -n "${MASKCLIP_L_CKPT}" ]; then
|
| 138 |
+
run_test "maskclip_eval_single" "${MASKCLIP_L_SINGLE}" "${MASKCLIP_L_CKPT}" "/tmp/maskclip_l_single"
|
| 139 |
+
run_test "maskclip_eval_ensemble" "${MASKCLIP_L_ENSEMBLE}" "${MASKCLIP_L_CKPT}" "/tmp/maskclip_l_ensemble"
|
| 140 |
+
else
|
| 141 |
+
echo "SKIP: MaskCLIP Large - 权重路径未设置"
|
| 142 |
+
echo "## MaskCLIP Large - SKIPPED (权重路径未设置)" >> "${RESULT_FILE}"
|
| 143 |
+
fi
|
| 144 |
+
|
| 145 |
+
# ==================== 3. DeCLIP 测试 ====================
|
| 146 |
+
echo ""
|
| 147 |
+
echo "========== DeCLIP Tests =========="
|
| 148 |
+
|
| 149 |
+
# DeCLIP Base
|
| 150 |
+
run_test "declip_evab_single" "${DECLIP_B_SINGLE}" "${DECLIP_B_CKPT}" "/tmp/declip_b_single"
|
| 151 |
+
run_test "declip_evab_ensemble" "${DECLIP_B_ENSEMBLE}" "${DECLIP_B_CKPT}" "/tmp/declip_b_ensemble"
|
| 152 |
+
|
| 153 |
+
# DeCLIP Large
|
| 154 |
+
run_test "declip_eval_single" "${DECLIP_L_SINGLE}" "${DECLIP_L_CKPT}" "/tmp/declip_l_single"
|
| 155 |
+
run_test "declip_eval_ensemble" "${DECLIP_L_ENSEMBLE}" "${DECLIP_L_CKPT}" "/tmp/declip_l_ensemble"
|
| 156 |
+
|
| 157 |
+
# ==================== 汇总结果 ====================
|
| 158 |
+
echo "" >> "${RESULT_FILE}"
|
| 159 |
+
echo "================================================" >> "${RESULT_FILE}"
|
| 160 |
+
echo "Summary Table" >> "${RESULT_FILE}"
|
| 161 |
+
echo "================================================" >> "${RESULT_FILE}"
|
| 162 |
+
echo "" >> "${RESULT_FILE}"
|
| 163 |
+
echo "| Model | Size | Method | base_ap50 | novel_ap50 | all_ap50 | bbox_mAP |" >> "${RESULT_FILE}"
|
| 164 |
+
echo "|-------|------|--------|-----------|------------|----------|----------|" >> "${RESULT_FILE}"
|
| 165 |
+
|
| 166 |
+
# 从日志中提取并格式化结果
|
| 167 |
+
extract_result() {
|
| 168 |
+
local log=$1
|
| 169 |
+
local model=$2
|
| 170 |
+
local size=$3
|
| 171 |
+
local method=$4
|
| 172 |
+
|
| 173 |
+
if [ -f "${RESULT_DIR}/${log}.log" ]; then
|
| 174 |
+
result_line=$(grep "OrderedDict" "${RESULT_DIR}/${log}.log" | tail -1)
|
| 175 |
+
if [ -n "${result_line}" ]; then
|
| 176 |
+
base_ap50=$(echo "${result_line}" | grep -oP "base_ap50', \K[0-9.]+" || echo "N/A")
|
| 177 |
+
novel_ap50=$(echo "${result_line}" | grep -oP "novel_ap50', \K[0-9.]+" || echo "N/A")
|
| 178 |
+
all_ap50=$(echo "${result_line}" | grep -oP "all_ap50', \K[0-9.]+" || echo "N/A")
|
| 179 |
+
bbox_mAP=$(echo "${result_line}" | grep -oP "bbox_mAP', \K[0-9.]+" || echo "N/A")
|
| 180 |
+
echo "| ${model} | ${size} | ${method} | ${base_ap50} | ${novel_ap50} | ${all_ap50} | ${bbox_mAP} |" >> "${RESULT_FILE}"
|
| 181 |
+
fi
|
| 182 |
+
fi
|
| 183 |
+
}
|
| 184 |
+
|
| 185 |
+
# CLIPSelf 结果
|
| 186 |
+
extract_result "clipself_evab_single" "CLIPSelf" "Base" "Single"
|
| 187 |
+
extract_result "clipself_evab_ensemble" "CLIPSelf" "Base" "Ensemble"
|
| 188 |
+
extract_result "clipself_eval_single" "CLIPSelf" "Large" "Single"
|
| 189 |
+
extract_result "clipself_eval_ensemble" "CLIPSelf" "Large" "Ensemble"
|
| 190 |
+
|
| 191 |
+
# MaskCLIP 结果
|
| 192 |
+
extract_result "maskclip_evab_single" "MaskCLIP" "Base" "Single"
|
| 193 |
+
extract_result "maskclip_evab_ensemble" "MaskCLIP" "Base" "Ensemble"
|
| 194 |
+
extract_result "maskclip_eval_single" "MaskCLIP" "Large" "Single"
|
| 195 |
+
extract_result "maskclip_eval_ensemble" "MaskCLIP" "Large" "Ensemble"
|
| 196 |
+
|
| 197 |
+
# DeCLIP 结果
|
| 198 |
+
extract_result "declip_evab_single" "DeCLIP" "Base" "Single"
|
| 199 |
+
extract_result "declip_evab_ensemble" "DeCLIP" "Base" "Ensemble"
|
| 200 |
+
extract_result "declip_eval_single" "DeCLIP" "Large" "Single"
|
| 201 |
+
extract_result "declip_eval_ensemble" "DeCLIP" "Large" "Ensemble"
|
| 202 |
+
|
| 203 |
+
echo "" >> "${RESULT_FILE}"
|
| 204 |
+
echo "Completed at: $(date)" >> "${RESULT_FILE}"
|
| 205 |
+
|
| 206 |
+
echo ""
|
| 207 |
+
echo "================================================"
|
| 208 |
+
echo "所有测试完成!"
|
| 209 |
+
echo "结果保存在: ${RESULT_FILE}"
|
| 210 |
+
echo "================================================"
|
| 211 |
+
cat "${RESULT_FILE}"
|
analysis/prompt_ensemble_ablation/scripts/run_clearclip_b.sh
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# 测试 ClearCLIP Base 的 Prompt Ensemble 消融
|
| 3 |
+
# feature_mode='qq', 共 2 个测试
|
| 4 |
+
|
| 5 |
+
set -e
|
| 6 |
+
|
| 7 |
+
# 路径配置
|
| 8 |
+
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
| 9 |
+
ABLATION_DIR="$(dirname "${SCRIPT_DIR}")"
|
| 10 |
+
FVIT_DIR="${ABLATION_DIR}/../CLIPSelf/F-ViT"
|
| 11 |
+
RESULT_DIR="${ABLATION_DIR}/results"
|
| 12 |
+
RESULT_FILE="${RESULT_DIR}/clearclip_b_results.txt"
|
| 13 |
+
|
| 14 |
+
# 权重路径
|
| 15 |
+
CLEARCLIP_B_CKPT="/mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/CLIPSelf/F-ViT/work_dirs/clearclip_ovcoco/epoch_3.pth"
|
| 16 |
+
|
| 17 |
+
# 配置文件
|
| 18 |
+
CONFIG_DIR="${ABLATION_DIR}/configs"
|
| 19 |
+
CLEARCLIP_B_SINGLE="${CONFIG_DIR}/fvit_vitb16_ovcoco_clearclip_single_prompt.py"
|
| 20 |
+
CLEARCLIP_B_ENSEMBLE="${CONFIG_DIR}/fvit_vitb16_ovcoco_clearclip_ensemble.py"
|
| 21 |
+
|
| 22 |
+
# 创建结果目录
|
| 23 |
+
mkdir -p "${RESULT_DIR}"
|
| 24 |
+
|
| 25 |
+
# 初始化结果文件
|
| 26 |
+
echo "================================================" > "${RESULT_FILE}"
|
| 27 |
+
echo "ClearCLIP-B (QQ mode) Ablation Results" >> "${RESULT_FILE}"
|
| 28 |
+
echo "Date: $(date)" >> "${RESULT_FILE}"
|
| 29 |
+
echo "================================================" >> "${RESULT_FILE}"
|
| 30 |
+
echo "" >> "${RESULT_FILE}"
|
| 31 |
+
|
| 32 |
+
# 检查权重文件
|
| 33 |
+
echo "检查权重文件..."
|
| 34 |
+
if [ ! -f "${CLEARCLIP_B_CKPT}" ]; then
|
| 35 |
+
echo "错误: 权重不存在: ${CLEARCLIP_B_CKPT}"
|
| 36 |
+
exit 1
|
| 37 |
+
fi
|
| 38 |
+
echo "权重文件检查通过"
|
| 39 |
+
|
| 40 |
+
cd "${FVIT_DIR}"
|
| 41 |
+
export PYTHONPATH="$(pwd)/..":$PYTHONPATH
|
| 42 |
+
|
| 43 |
+
# 运行测试函数
|
| 44 |
+
run_test() {
|
| 45 |
+
local name=$1
|
| 46 |
+
local config=$2
|
| 47 |
+
local checkpoint=$3
|
| 48 |
+
local tmpdir=$4
|
| 49 |
+
local log_file="${RESULT_DIR}/${name}.log"
|
| 50 |
+
|
| 51 |
+
echo ""
|
| 52 |
+
echo "================================================"
|
| 53 |
+
echo "Running: ${name}"
|
| 54 |
+
echo "Config: $(basename ${config})"
|
| 55 |
+
echo "Checkpoint: $(basename ${checkpoint})"
|
| 56 |
+
echo "================================================"
|
| 57 |
+
|
| 58 |
+
echo "## ${name}" >> "${RESULT_FILE}"
|
| 59 |
+
echo "Config: $(basename ${config})" >> "${RESULT_FILE}"
|
| 60 |
+
echo "" >> "${RESULT_FILE}"
|
| 61 |
+
|
| 62 |
+
torchrun --nproc_per_node=8 --master_port=12346 \
|
| 63 |
+
test.py \
|
| 64 |
+
"${config}" \
|
| 65 |
+
"${checkpoint}" \
|
| 66 |
+
--launcher pytorch \
|
| 67 |
+
--eval bbox \
|
| 68 |
+
--tmpdir "${tmpdir}" \
|
| 69 |
+
2>&1 | tee "${log_file}"
|
| 70 |
+
|
| 71 |
+
echo "Results:" >> "${RESULT_FILE}"
|
| 72 |
+
grep -E "OrderedDict" "${log_file}" | tail -1 >> "${RESULT_FILE}"
|
| 73 |
+
echo "" >> "${RESULT_FILE}"
|
| 74 |
+
echo "----------------------------------------" >> "${RESULT_FILE}"
|
| 75 |
+
echo "" >> "${RESULT_FILE}"
|
| 76 |
+
}
|
| 77 |
+
|
| 78 |
+
echo ""
|
| 79 |
+
echo "开始测试 ClearCLIP-B (共 2 个)..."
|
| 80 |
+
|
| 81 |
+
# 1. ClearCLIP Base Single
|
| 82 |
+
run_test "clearclip_evab_single" "${CLEARCLIP_B_SINGLE}" "${CLEARCLIP_B_CKPT}" "/tmp/clearclip_b_single"
|
| 83 |
+
|
| 84 |
+
# 2. ClearCLIP Base Ensemble
|
| 85 |
+
run_test "clearclip_evab_ensemble" "${CLEARCLIP_B_ENSEMBLE}" "${CLEARCLIP_B_CKPT}" "/tmp/clearclip_b_ensemble"
|
| 86 |
+
|
| 87 |
+
# 汇总结果
|
| 88 |
+
echo "" >> "${RESULT_FILE}"
|
| 89 |
+
echo "================================================" >> "${RESULT_FILE}"
|
| 90 |
+
echo "Summary" >> "${RESULT_FILE}"
|
| 91 |
+
echo "================================================" >> "${RESULT_FILE}"
|
| 92 |
+
echo "" >> "${RESULT_FILE}"
|
| 93 |
+
echo "| Model | Method | base_ap50 | novel_ap50 | all_ap50 | bbox_mAP |" >> "${RESULT_FILE}"
|
| 94 |
+
echo "|-------|--------|-----------|------------|----------|----------|" >> "${RESULT_FILE}"
|
| 95 |
+
|
| 96 |
+
for log in clearclip_evab_single clearclip_evab_ensemble; do
|
| 97 |
+
if [ -f "${RESULT_DIR}/${log}.log" ]; then
|
| 98 |
+
model="ClearCLIP-B"
|
| 99 |
+
if [[ "${log}" == *"single"* ]]; then
|
| 100 |
+
method="Single"
|
| 101 |
+
else
|
| 102 |
+
method="Ensemble"
|
| 103 |
+
fi
|
| 104 |
+
|
| 105 |
+
result_line=$(grep "OrderedDict" "${RESULT_DIR}/${log}.log" | tail -1)
|
| 106 |
+
if [ -n "${result_line}" ]; then
|
| 107 |
+
base_ap50=$(echo "${result_line}" | grep -oP "base_ap50', \K[0-9.]+" || echo "N/A")
|
| 108 |
+
novel_ap50=$(echo "${result_line}" | grep -oP "novel_ap50', \K[0-9.]+" || echo "N/A")
|
| 109 |
+
all_ap50=$(echo "${result_line}" | grep -oP "all_ap50', \K[0-9.]+" || echo "N/A")
|
| 110 |
+
bbox_mAP=$(echo "${result_line}" | grep -oP "bbox_mAP', \K[0-9.]+" || echo "N/A")
|
| 111 |
+
echo "| ${model} | ${method} | ${base_ap50} | ${novel_ap50} | ${all_ap50} | ${bbox_mAP} |" >> "${RESULT_FILE}"
|
| 112 |
+
fi
|
| 113 |
+
fi
|
| 114 |
+
done
|
| 115 |
+
|
| 116 |
+
echo "" >> "${RESULT_FILE}"
|
| 117 |
+
echo "Completed at: $(date)" >> "${RESULT_FILE}"
|
| 118 |
+
|
| 119 |
+
echo ""
|
| 120 |
+
echo "================================================"
|
| 121 |
+
echo "所有测试完成!"
|
| 122 |
+
echo "结果保存在: ${RESULT_FILE}"
|
| 123 |
+
echo "================================================"
|
| 124 |
+
echo ""
|
| 125 |
+
cat "${RESULT_FILE}"
|
analysis/prompt_ensemble_ablation/scripts/run_clearclip_l.sh
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# 测试 ClearCLIP Large 的 Prompt Ensemble 消融
|
| 3 |
+
# feature_mode='qq', 共 2 个测试
|
| 4 |
+
|
| 5 |
+
set -e
|
| 6 |
+
|
| 7 |
+
# 路径配置
|
| 8 |
+
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
| 9 |
+
ABLATION_DIR="$(dirname "${SCRIPT_DIR}")"
|
| 10 |
+
FVIT_DIR="${ABLATION_DIR}/../CLIPSelf/F-ViT"
|
| 11 |
+
RESULT_DIR="${ABLATION_DIR}/results"
|
| 12 |
+
RESULT_FILE="${RESULT_DIR}/clearclip_l_results.txt"
|
| 13 |
+
|
| 14 |
+
# 权重路径
|
| 15 |
+
CLEARCLIP_L_CKPT="/mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/CLIPSelf/F-ViT/work_dirs/clearclip_ovcoco_large/epoch_3.pth"
|
| 16 |
+
|
| 17 |
+
# 配置文件
|
| 18 |
+
CONFIG_DIR="${ABLATION_DIR}/configs"
|
| 19 |
+
CLEARCLIP_L_SINGLE="${CONFIG_DIR}/fvit_vitl14_ovcoco_clearclip_single_prompt.py"
|
| 20 |
+
CLEARCLIP_L_ENSEMBLE="${CONFIG_DIR}/fvit_vitl14_ovcoco_clearclip_ensemble.py"
|
| 21 |
+
|
| 22 |
+
# 创建结果目录
|
| 23 |
+
mkdir -p "${RESULT_DIR}"
|
| 24 |
+
|
| 25 |
+
# 初始化结果文件
|
| 26 |
+
echo "================================================" > "${RESULT_FILE}"
|
| 27 |
+
echo "ClearCLIP-L (QQ mode) Ablation Results" >> "${RESULT_FILE}"
|
| 28 |
+
echo "Date: $(date)" >> "${RESULT_FILE}"
|
| 29 |
+
echo "================================================" >> "${RESULT_FILE}"
|
| 30 |
+
echo "" >> "${RESULT_FILE}"
|
| 31 |
+
|
| 32 |
+
# 检查权重文件
|
| 33 |
+
echo "检查权重文件..."
|
| 34 |
+
if [ ! -f "${CLEARCLIP_L_CKPT}" ]; then
|
| 35 |
+
echo "错误: 权重不存在: ${CLEARCLIP_L_CKPT}"
|
| 36 |
+
exit 1
|
| 37 |
+
fi
|
| 38 |
+
echo "权重文件检查通过"
|
| 39 |
+
|
| 40 |
+
cd "${FVIT_DIR}"
|
| 41 |
+
export PYTHONPATH="$(pwd)/..":$PYTHONPATH
|
| 42 |
+
|
| 43 |
+
# 运行测试函数
|
| 44 |
+
run_test() {
|
| 45 |
+
local name=$1
|
| 46 |
+
local config=$2
|
| 47 |
+
local checkpoint=$3
|
| 48 |
+
local tmpdir=$4
|
| 49 |
+
local log_file="${RESULT_DIR}/${name}.log"
|
| 50 |
+
|
| 51 |
+
echo ""
|
| 52 |
+
echo "================================================"
|
| 53 |
+
echo "Running: ${name}"
|
| 54 |
+
echo "Config: $(basename ${config})"
|
| 55 |
+
echo "Checkpoint: $(basename ${checkpoint})"
|
| 56 |
+
echo "================================================"
|
| 57 |
+
|
| 58 |
+
echo "## ${name}" >> "${RESULT_FILE}"
|
| 59 |
+
echo "Config: $(basename ${config})" >> "${RESULT_FILE}"
|
| 60 |
+
echo "" >> "${RESULT_FILE}"
|
| 61 |
+
|
| 62 |
+
torchrun --nproc_per_node=8 --master_port=12346 \
|
| 63 |
+
test.py \
|
| 64 |
+
"${config}" \
|
| 65 |
+
"${checkpoint}" \
|
| 66 |
+
--launcher pytorch \
|
| 67 |
+
--eval bbox \
|
| 68 |
+
--tmpdir "${tmpdir}" \
|
| 69 |
+
2>&1 | tee "${log_file}"
|
| 70 |
+
|
| 71 |
+
echo "Results:" >> "${RESULT_FILE}"
|
| 72 |
+
grep -E "OrderedDict" "${log_file}" | tail -1 >> "${RESULT_FILE}"
|
| 73 |
+
echo "" >> "${RESULT_FILE}"
|
| 74 |
+
echo "----------------------------------------" >> "${RESULT_FILE}"
|
| 75 |
+
echo "" >> "${RESULT_FILE}"
|
| 76 |
+
}
|
| 77 |
+
|
| 78 |
+
echo ""
|
| 79 |
+
echo "开始测试 ClearCLIP-L (共 2 个)..."
|
| 80 |
+
|
| 81 |
+
# 1. ClearCLIP Large Single
|
| 82 |
+
run_test "clearclip_eval_single" "${CLEARCLIP_L_SINGLE}" "${CLEARCLIP_L_CKPT}" "/tmp/clearclip_l_single"
|
| 83 |
+
|
| 84 |
+
# 2. ClearCLIP Large Ensemble
|
| 85 |
+
run_test "clearclip_eval_ensemble" "${CLEARCLIP_L_ENSEMBLE}" "${CLEARCLIP_L_CKPT}" "/tmp/clearclip_l_ensemble"
|
| 86 |
+
|
| 87 |
+
# 汇总结果
|
| 88 |
+
echo "" >> "${RESULT_FILE}"
|
| 89 |
+
echo "================================================" >> "${RESULT_FILE}"
|
| 90 |
+
echo "Summary" >> "${RESULT_FILE}"
|
| 91 |
+
echo "================================================" >> "${RESULT_FILE}"
|
| 92 |
+
echo "" >> "${RESULT_FILE}"
|
| 93 |
+
echo "| Model | Method | base_ap50 | novel_ap50 | all_ap50 | bbox_mAP |" >> "${RESULT_FILE}"
|
| 94 |
+
echo "|-------|--------|-----------|------------|----------|----------|" >> "${RESULT_FILE}"
|
| 95 |
+
|
| 96 |
+
for log in clearclip_eval_single clearclip_eval_ensemble; do
|
| 97 |
+
if [ -f "${RESULT_DIR}/${log}.log" ]; then
|
| 98 |
+
model="ClearCLIP-L"
|
| 99 |
+
if [[ "${log}" == *"single"* ]]; then
|
| 100 |
+
method="Single"
|
| 101 |
+
else
|
| 102 |
+
method="Ensemble"
|
| 103 |
+
fi
|
| 104 |
+
|
| 105 |
+
result_line=$(grep "OrderedDict" "${RESULT_DIR}/${log}.log" | tail -1)
|
| 106 |
+
if [ -n "${result_line}" ]; then
|
| 107 |
+
base_ap50=$(echo "${result_line}" | grep -oP "base_ap50', \K[0-9.]+" || echo "N/A")
|
| 108 |
+
novel_ap50=$(echo "${result_line}" | grep -oP "novel_ap50', \K[0-9.]+" || echo "N/A")
|
| 109 |
+
all_ap50=$(echo "${result_line}" | grep -oP "all_ap50', \K[0-9.]+" || echo "N/A")
|
| 110 |
+
bbox_mAP=$(echo "${result_line}" | grep -oP "bbox_mAP', \K[0-9.]+" || echo "N/A")
|
| 111 |
+
echo "| ${model} | ${method} | ${base_ap50} | ${novel_ap50} | ${all_ap50} | ${bbox_mAP} |" >> "${RESULT_FILE}"
|
| 112 |
+
fi
|
| 113 |
+
fi
|
| 114 |
+
done
|
| 115 |
+
|
| 116 |
+
echo "" >> "${RESULT_FILE}"
|
| 117 |
+
echo "Completed at: $(date)" >> "${RESULT_FILE}"
|
| 118 |
+
|
| 119 |
+
echo ""
|
| 120 |
+
echo "================================================"
|
| 121 |
+
echo "所有测试完成!"
|
| 122 |
+
echo "结果保存在: ${RESULT_FILE}"
|
| 123 |
+
echo "================================================"
|
| 124 |
+
echo ""
|
| 125 |
+
cat "${RESULT_FILE}"
|
analysis/prompt_ensemble_ablation/scripts/run_declip_ablation.sh
ADDED
|
@@ -0,0 +1,163 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# DeCLIP Prompt Ensemble 消融实验脚本
|
| 3 |
+
# 运行 4 个测试: EVA-B/L x Single/Ensemble
|
| 4 |
+
# 结果保存到 results/declip_ablation_results.txt
|
| 5 |
+
|
| 6 |
+
set -e
|
| 7 |
+
|
| 8 |
+
# 路径配置
|
| 9 |
+
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
| 10 |
+
ABLATION_DIR="$(dirname "${SCRIPT_DIR}")"
|
| 11 |
+
FVIT_DIR="${ABLATION_DIR}/../CLIPSelf/F-ViT"
|
| 12 |
+
RESULT_DIR="${ABLATION_DIR}/results"
|
| 13 |
+
RESULT_FILE="${RESULT_DIR}/declip_ablation_results.txt"
|
| 14 |
+
|
| 15 |
+
# 权重路径
|
| 16 |
+
EVAB_CKPT="/opt/tiger/xiaomoguhzz/declip2_ovcoco_detector/EVAB_dinov2B_epoch2.pth"
|
| 17 |
+
EVAL_CKPT="/opt/tiger/xiaomoguhzz/declip2_ovcoco_detector/EVAL_dinov2L_epoch3.pth"
|
| 18 |
+
|
| 19 |
+
# 配置文件路径
|
| 20 |
+
CONFIG_B_SINGLE="${ABLATION_DIR}/configs/fvit_vitb16_ovcoco_declip_single_prompt.py"
|
| 21 |
+
CONFIG_B_ENSEMBLE="${ABLATION_DIR}/configs/fvit_vitb16_ovcoco_declip_ensemble.py"
|
| 22 |
+
CONFIG_L_SINGLE="${ABLATION_DIR}/configs/fvit_vitl14_ovcoco_declip_single_prompt.py"
|
| 23 |
+
CONFIG_L_ENSEMBLE="${ABLATION_DIR}/configs/fvit_vitl14_ovcoco_declip_ensemble.py"
|
| 24 |
+
|
| 25 |
+
# 创建结果目录
|
| 26 |
+
mkdir -p "${RESULT_DIR}"
|
| 27 |
+
|
| 28 |
+
# 初始化结果文件
|
| 29 |
+
echo "================================================" > "${RESULT_FILE}"
|
| 30 |
+
echo "DeCLIP Prompt Ensemble Ablation Results" >> "${RESULT_FILE}"
|
| 31 |
+
echo "Date: $(date)" >> "${RESULT_FILE}"
|
| 32 |
+
echo "================================================" >> "${RESULT_FILE}"
|
| 33 |
+
echo "" >> "${RESULT_FILE}"
|
| 34 |
+
|
| 35 |
+
# 检查权重文件
|
| 36 |
+
echo "检查权重文件..."
|
| 37 |
+
if [ ! -f "${EVAB_CKPT}" ]; then
|
| 38 |
+
echo "错误: EVA-B 权重不存在: ${EVAB_CKPT}"
|
| 39 |
+
exit 1
|
| 40 |
+
fi
|
| 41 |
+
if [ ! -f "${EVAL_CKPT}" ]; then
|
| 42 |
+
echo "错误: EVA-L 权重不存在: ${EVAL_CKPT}"
|
| 43 |
+
exit 1
|
| 44 |
+
fi
|
| 45 |
+
echo "权重文件检查通过"
|
| 46 |
+
|
| 47 |
+
cd "${FVIT_DIR}"
|
| 48 |
+
export PYTHONPATH="$(pwd)/..":$PYTHONPATH
|
| 49 |
+
|
| 50 |
+
# 运行单个测试的函数
|
| 51 |
+
run_test() {
|
| 52 |
+
local name=$1
|
| 53 |
+
local config=$2
|
| 54 |
+
local checkpoint=$3
|
| 55 |
+
local tmpdir=$4
|
| 56 |
+
local log_file="${RESULT_DIR}/${name}.log"
|
| 57 |
+
|
| 58 |
+
echo ""
|
| 59 |
+
echo "================================================"
|
| 60 |
+
echo "Running: ${name}"
|
| 61 |
+
echo "Config: ${config}"
|
| 62 |
+
echo "Checkpoint: ${checkpoint}"
|
| 63 |
+
echo "================================================"
|
| 64 |
+
|
| 65 |
+
echo "## ${name}" >> "${RESULT_FILE}"
|
| 66 |
+
echo "Config: $(basename ${config})" >> "${RESULT_FILE}"
|
| 67 |
+
echo "Checkpoint: $(basename ${checkpoint})" >> "${RESULT_FILE}"
|
| 68 |
+
echo "" >> "${RESULT_FILE}"
|
| 69 |
+
|
| 70 |
+
# 运行测试并保存日志
|
| 71 |
+
torchrun --nproc_per_node=8 --master_port=12346 \
|
| 72 |
+
test.py \
|
| 73 |
+
"${config}" \
|
| 74 |
+
"${checkpoint}" \
|
| 75 |
+
--launcher pytorch \
|
| 76 |
+
--eval bbox \
|
| 77 |
+
--tmpdir "${tmpdir}" \
|
| 78 |
+
2>&1 | tee "${log_file}"
|
| 79 |
+
|
| 80 |
+
# 提取结果
|
| 81 |
+
echo "Results:" >> "${RESULT_FILE}"
|
| 82 |
+
grep -E "(base_ap50|novel_ap50|all_ap50|bbox_mAP)" "${log_file}" | tail -1 >> "${RESULT_FILE}"
|
| 83 |
+
echo "" >> "${RESULT_FILE}"
|
| 84 |
+
echo "----------------------------------------" >> "${RESULT_FILE}"
|
| 85 |
+
echo "" >> "${RESULT_FILE}"
|
| 86 |
+
|
| 87 |
+
echo "Completed: ${name}"
|
| 88 |
+
}
|
| 89 |
+
|
| 90 |
+
# 运行 4 个测试
|
| 91 |
+
echo ""
|
| 92 |
+
echo "开始运行 DeCLIP 消融实验 (共 4 个测试)..."
|
| 93 |
+
echo ""
|
| 94 |
+
|
| 95 |
+
# 1. DeCLIP EVA-B Single Prompt
|
| 96 |
+
run_test "declip_evab_single_prompt" \
|
| 97 |
+
"${CONFIG_B_SINGLE}" \
|
| 98 |
+
"${EVAB_CKPT}" \
|
| 99 |
+
"/tmp/dist_test_declip_b_single"
|
| 100 |
+
|
| 101 |
+
# 2. DeCLIP EVA-B Ensemble
|
| 102 |
+
run_test "declip_evab_ensemble" \
|
| 103 |
+
"${CONFIG_B_ENSEMBLE}" \
|
| 104 |
+
"${EVAB_CKPT}" \
|
| 105 |
+
"/tmp/dist_test_declip_b_ensemble"
|
| 106 |
+
|
| 107 |
+
# 3. DeCLIP EVA-L Single Prompt
|
| 108 |
+
run_test "declip_eval_single_prompt" \
|
| 109 |
+
"${CONFIG_L_SINGLE}" \
|
| 110 |
+
"${EVAL_CKPT}" \
|
| 111 |
+
"/tmp/dist_test_declip_l_single"
|
| 112 |
+
|
| 113 |
+
# 4. DeCLIP EVA-L Ensemble
|
| 114 |
+
run_test "declip_eval_ensemble" \
|
| 115 |
+
"${CONFIG_L_ENSEMBLE}" \
|
| 116 |
+
"${EVAL_CKPT}" \
|
| 117 |
+
"/tmp/dist_test_declip_l_ensemble"
|
| 118 |
+
|
| 119 |
+
# 汇总结果
|
| 120 |
+
echo "" >> "${RESULT_FILE}"
|
| 121 |
+
echo "================================================" >> "${RESULT_FILE}"
|
| 122 |
+
echo "Summary" >> "${RESULT_FILE}"
|
| 123 |
+
echo "================================================" >> "${RESULT_FILE}"
|
| 124 |
+
echo "" >> "${RESULT_FILE}"
|
| 125 |
+
echo "| Model | Method | base_ap50 | novel_ap50 | all_ap50 | bbox_mAP |" >> "${RESULT_FILE}"
|
| 126 |
+
echo "|-------|--------|-----------|------------|----------|----------|" >> "${RESULT_FILE}"
|
| 127 |
+
|
| 128 |
+
# 从日志中提取并格式化结果
|
| 129 |
+
for log in declip_evab_single_prompt declip_evab_ensemble declip_eval_single_prompt declip_eval_ensemble; do
|
| 130 |
+
if [ -f "${RESULT_DIR}/${log}.log" ]; then
|
| 131 |
+
# 提取模型和方法名
|
| 132 |
+
if [[ "${log}" == *"evab"* ]]; then
|
| 133 |
+
model="DeCLIP-B"
|
| 134 |
+
else
|
| 135 |
+
model="DeCLIP-L"
|
| 136 |
+
fi
|
| 137 |
+
if [[ "${log}" == *"single"* ]]; then
|
| 138 |
+
method="Single"
|
| 139 |
+
else
|
| 140 |
+
method="Ensemble"
|
| 141 |
+
fi
|
| 142 |
+
|
| 143 |
+
# 提取指标
|
| 144 |
+
result_line=$(grep "OrderedDict" "${RESULT_DIR}/${log}.log" | tail -1)
|
| 145 |
+
if [ -n "${result_line}" ]; then
|
| 146 |
+
base_ap50=$(echo "${result_line}" | grep -oP "base_ap50', \K[0-9.]+" || echo "N/A")
|
| 147 |
+
novel_ap50=$(echo "${result_line}" | grep -oP "novel_ap50', \K[0-9.]+" || echo "N/A")
|
| 148 |
+
all_ap50=$(echo "${result_line}" | grep -oP "all_ap50', \K[0-9.]+" || echo "N/A")
|
| 149 |
+
bbox_mAP=$(echo "${result_line}" | grep -oP "bbox_mAP', \K[0-9.]+" || echo "N/A")
|
| 150 |
+
echo "| ${model} | ${method} | ${base_ap50} | ${novel_ap50} | ${all_ap50} | ${bbox_mAP} |" >> "${RESULT_FILE}"
|
| 151 |
+
fi
|
| 152 |
+
fi
|
| 153 |
+
done
|
| 154 |
+
|
| 155 |
+
echo "" >> "${RESULT_FILE}"
|
| 156 |
+
echo "Completed at: $(date)" >> "${RESULT_FILE}"
|
| 157 |
+
|
| 158 |
+
echo ""
|
| 159 |
+
echo "================================================"
|
| 160 |
+
echo "所有测试完成!"
|
| 161 |
+
echo "结果保存在: ${RESULT_FILE}"
|
| 162 |
+
echo "================================================"
|
| 163 |
+
cat "${RESULT_FILE}"
|
analysis/prompt_ensemble_ablation/scripts/run_maskclip_b_clipself_l.sh
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# 测试 MaskCLIP Base + CLIPSelf Large 的 Prompt Ensemble 消融
|
| 3 |
+
# 共 4 个测试
|
| 4 |
+
|
| 5 |
+
set -e
|
| 6 |
+
|
| 7 |
+
# 路径配置
|
| 8 |
+
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
| 9 |
+
ABLATION_DIR="$(dirname "${SCRIPT_DIR}")"
|
| 10 |
+
FVIT_DIR="${ABLATION_DIR}/../CLIPSelf/F-ViT"
|
| 11 |
+
RESULT_DIR="${ABLATION_DIR}/results"
|
| 12 |
+
RESULT_FILE="${RESULT_DIR}/maskclip_b_clipself_l_results.txt"
|
| 13 |
+
|
| 14 |
+
# 权重路径
|
| 15 |
+
MASKCLIP_B_CKPT="/mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/CLIPSelf/F-ViT/work_dirs/fvit_vitb16_ovcoco_maskclip/epoch_3.pth"
|
| 16 |
+
CLIPSELF_L_CKPT="/opt/tiger/xiaomoguhzz/fvit_eva_vitl14_ovcoco_clipself_proposals.pth"
|
| 17 |
+
|
| 18 |
+
# 配置文件
|
| 19 |
+
CONFIG_DIR="${ABLATION_DIR}/configs"
|
| 20 |
+
MASKCLIP_B_SINGLE="${CONFIG_DIR}/fvit_vitb16_ovcoco_maskclip_single_prompt.py"
|
| 21 |
+
MASKCLIP_B_ENSEMBLE="${CONFIG_DIR}/fvit_vitb16_ovcoco_maskclip_ensemble.py"
|
| 22 |
+
CLIPSELF_L_SINGLE="${CONFIG_DIR}/fvit_vitl14_ovcoco_single_prompt.py"
|
| 23 |
+
CLIPSELF_L_ENSEMBLE="${CONFIG_DIR}/fvit_vitl14_ovcoco_ensemble.py"
|
| 24 |
+
|
| 25 |
+
# 创建结果目录
|
| 26 |
+
mkdir -p "${RESULT_DIR}"
|
| 27 |
+
|
| 28 |
+
# 初始化结果文件
|
| 29 |
+
echo "================================================" > "${RESULT_FILE}"
|
| 30 |
+
echo "MaskCLIP-B + CLIPSelf-L Ablation Results" >> "${RESULT_FILE}"
|
| 31 |
+
echo "Date: $(date)" >> "${RESULT_FILE}"
|
| 32 |
+
echo "================================================" >> "${RESULT_FILE}"
|
| 33 |
+
echo "" >> "${RESULT_FILE}"
|
| 34 |
+
|
| 35 |
+
# 检查权重文件
|
| 36 |
+
echo "检查权重文件..."
|
| 37 |
+
for ckpt in "${MASKCLIP_B_CKPT}" "${CLIPSELF_L_CKPT}"; do
|
| 38 |
+
if [ ! -f "${ckpt}" ]; then
|
| 39 |
+
echo "错误: 权重不存在: ${ckpt}"
|
| 40 |
+
exit 1
|
| 41 |
+
fi
|
| 42 |
+
done
|
| 43 |
+
echo "权重文件检查通过"
|
| 44 |
+
|
| 45 |
+
cd "${FVIT_DIR}"
|
| 46 |
+
export PYTHONPATH="$(pwd)/..":$PYTHONPATH
|
| 47 |
+
|
| 48 |
+
# 运行测试函数
|
| 49 |
+
run_test() {
|
| 50 |
+
local name=$1
|
| 51 |
+
local config=$2
|
| 52 |
+
local checkpoint=$3
|
| 53 |
+
local tmpdir=$4
|
| 54 |
+
local log_file="${RESULT_DIR}/${name}.log"
|
| 55 |
+
|
| 56 |
+
echo ""
|
| 57 |
+
echo "================================================"
|
| 58 |
+
echo "Running: ${name}"
|
| 59 |
+
echo "Config: $(basename ${config})"
|
| 60 |
+
echo "Checkpoint: $(basename ${checkpoint})"
|
| 61 |
+
echo "================================================"
|
| 62 |
+
|
| 63 |
+
echo "## ${name}" >> "${RESULT_FILE}"
|
| 64 |
+
echo "Config: $(basename ${config})" >> "${RESULT_FILE}"
|
| 65 |
+
echo "" >> "${RESULT_FILE}"
|
| 66 |
+
|
| 67 |
+
torchrun --nproc_per_node=8 --master_port=12346 \
|
| 68 |
+
test.py \
|
| 69 |
+
"${config}" \
|
| 70 |
+
"${checkpoint}" \
|
| 71 |
+
--launcher pytorch \
|
| 72 |
+
--eval bbox \
|
| 73 |
+
--tmpdir "${tmpdir}" \
|
| 74 |
+
2>&1 | tee "${log_file}"
|
| 75 |
+
|
| 76 |
+
echo "Results:" >> "${RESULT_FILE}"
|
| 77 |
+
grep -E "OrderedDict" "${log_file}" | tail -1 >> "${RESULT_FILE}"
|
| 78 |
+
echo "" >> "${RESULT_FILE}"
|
| 79 |
+
echo "----------------------------------------" >> "${RESULT_FILE}"
|
| 80 |
+
echo "" >> "${RESULT_FILE}"
|
| 81 |
+
}
|
| 82 |
+
|
| 83 |
+
echo ""
|
| 84 |
+
echo "开始测试 (共 4 个)..."
|
| 85 |
+
|
| 86 |
+
# 1. MaskCLIP Base Single
|
| 87 |
+
run_test "maskclip_evab_single" "${MASKCLIP_B_SINGLE}" "${MASKCLIP_B_CKPT}" "/tmp/maskclip_b_single"
|
| 88 |
+
|
| 89 |
+
# 2. MaskCLIP Base Ensemble
|
| 90 |
+
run_test "maskclip_evab_ensemble" "${MASKCLIP_B_ENSEMBLE}" "${MASKCLIP_B_CKPT}" "/tmp/maskclip_b_ensemble"
|
| 91 |
+
|
| 92 |
+
# 3. CLIPSelf Large Single
|
| 93 |
+
run_test "clipself_eval_single" "${CLIPSELF_L_SINGLE}" "${CLIPSELF_L_CKPT}" "/tmp/clipself_l_single"
|
| 94 |
+
|
| 95 |
+
# 4. CLIPSelf Large Ensemble
|
| 96 |
+
run_test "clipself_eval_ensemble" "${CLIPSELF_L_ENSEMBLE}" "${CLIPSELF_L_CKPT}" "/tmp/clipself_l_ensemble"
|
| 97 |
+
|
| 98 |
+
# 汇总结果
|
| 99 |
+
echo "" >> "${RESULT_FILE}"
|
| 100 |
+
echo "================================================" >> "${RESULT_FILE}"
|
| 101 |
+
echo "Summary" >> "${RESULT_FILE}"
|
| 102 |
+
echo "================================================" >> "${RESULT_FILE}"
|
| 103 |
+
echo "" >> "${RESULT_FILE}"
|
| 104 |
+
echo "| Model | Method | base_ap50 | novel_ap50 | all_ap50 | bbox_mAP |" >> "${RESULT_FILE}"
|
| 105 |
+
echo "|-------|--------|-----------|------------|----------|----------|" >> "${RESULT_FILE}"
|
| 106 |
+
|
| 107 |
+
for log in maskclip_evab_single maskclip_evab_ensemble clipself_eval_single clipself_eval_ensemble; do
|
| 108 |
+
if [ -f "${RESULT_DIR}/${log}.log" ]; then
|
| 109 |
+
if [[ "${log}" == *"maskclip"* ]]; then
|
| 110 |
+
model="MaskCLIP-B"
|
| 111 |
+
else
|
| 112 |
+
model="CLIPSelf-L"
|
| 113 |
+
fi
|
| 114 |
+
if [[ "${log}" == *"single"* ]]; then
|
| 115 |
+
method="Single"
|
| 116 |
+
else
|
| 117 |
+
method="Ensemble"
|
| 118 |
+
fi
|
| 119 |
+
|
| 120 |
+
result_line=$(grep "OrderedDict" "${RESULT_DIR}/${log}.log" | tail -1)
|
| 121 |
+
if [ -n "${result_line}" ]; then
|
| 122 |
+
base_ap50=$(echo "${result_line}" | grep -oP "base_ap50', \K[0-9.]+" || echo "N/A")
|
| 123 |
+
novel_ap50=$(echo "${result_line}" | grep -oP "novel_ap50', \K[0-9.]+" || echo "N/A")
|
| 124 |
+
all_ap50=$(echo "${result_line}" | grep -oP "all_ap50', \K[0-9.]+" || echo "N/A")
|
| 125 |
+
bbox_mAP=$(echo "${result_line}" | grep -oP "bbox_mAP', \K[0-9.]+" || echo "N/A")
|
| 126 |
+
echo "| ${model} | ${method} | ${base_ap50} | ${novel_ap50} | ${all_ap50} | ${bbox_mAP} |" >> "${RESULT_FILE}"
|
| 127 |
+
fi
|
| 128 |
+
fi
|
| 129 |
+
done
|
| 130 |
+
|
| 131 |
+
echo "" >> "${RESULT_FILE}"
|
| 132 |
+
echo "Completed at: $(date)" >> "${RESULT_FILE}"
|
| 133 |
+
|
| 134 |
+
echo ""
|
| 135 |
+
echo "================================================"
|
| 136 |
+
echo "所有测试完成!"
|
| 137 |
+
echo "结果���存在: ${RESULT_FILE}"
|
| 138 |
+
echo "================================================"
|
| 139 |
+
echo ""
|
| 140 |
+
cat "${RESULT_FILE}"
|
analysis/robustness_eval/README.md
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# OV-COCO 鲁棒性评估 (Robustness Evaluation)
|
| 2 |
+
|
| 3 |
+
评估目标检测模型在图像退化条件下的性能,**专为 OV-COCO 数据集设计**,支持 `base_ap50`、`novel_ap50`、`all_ap50` 指标。
|
| 4 |
+
|
| 5 |
+
## 目录结构
|
| 6 |
+
|
| 7 |
+
```
|
| 8 |
+
robustness_eval/
|
| 9 |
+
├── test_robustness_ovcoco.py # OV-COCO 鲁棒性测试脚本
|
| 10 |
+
├── merge_robustness_results.py # 结果合并与报告生成
|
| 11 |
+
├── run_clearclip_robustness.sh # ClearCLIP 8-GPU 并行测试
|
| 12 |
+
├── run_clipself_robustness.sh # CLIPSelf 8-GPU 并行测试
|
| 13 |
+
├── logs/ # 运行日志
|
| 14 |
+
└── results/ # 测试结果
|
| 15 |
+
├── clearclip/
|
| 16 |
+
└── clipself/
|
| 17 |
+
```
|
| 18 |
+
|
| 19 |
+
## 退化类型 (15 种 benchmark)
|
| 20 |
+
|
| 21 |
+
| 类别 | 退化类型 |
|
| 22 |
+
|------|----------|
|
| 23 |
+
| Noise | gaussian_noise, shot_noise, impulse_noise |
|
| 24 |
+
| Blur | defocus_blur, glass_blur, motion_blur, zoom_blur |
|
| 25 |
+
| Weather | snow, frost, fog, brightness |
|
| 26 |
+
| Digital | contrast, elastic_transform, pixelate, jpeg_compression |
|
| 27 |
+
|
| 28 |
+
## 严重程度
|
| 29 |
+
|
| 30 |
+
1-5 级,数字越大退化越严重。共 75 个场景 (15 类型 × 5 级别)。
|
| 31 |
+
|
| 32 |
+
## 评估指标
|
| 33 |
+
|
| 34 |
+
### OV-COCO 特有指标
|
| 35 |
+
- **base_ap50**: 已知类别 (48 类) 的 AP@IoU=0.50
|
| 36 |
+
- **novel_ap50**: 新类别 (17 类) 的 AP@IoU=0.50
|
| 37 |
+
- **all_ap50**: 所有类别 (65 类) 的 AP@IoU=0.50
|
| 38 |
+
|
| 39 |
+
### 鲁棒性指标
|
| 40 |
+
- **P (Performance)**: 原始图像上的性能
|
| 41 |
+
- **mPC (mean Performance under Corruption)**: 所有退化条件下的平均性能
|
| 42 |
+
- **rPC (relative Performance under Corruption)**: mPC / P,衡量鲁棒性
|
| 43 |
+
|
| 44 |
+
## 使用方法
|
| 45 |
+
|
| 46 |
+
### 1. 运行鲁棒性测试
|
| 47 |
+
|
| 48 |
+
```bash
|
| 49 |
+
cd /mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/robustness_eval
|
| 50 |
+
|
| 51 |
+
# ClearCLIP (8 GPU 并行,后台运行)
|
| 52 |
+
bash run_clearclip_robustness.sh --nohup
|
| 53 |
+
|
| 54 |
+
# CLIPSelf (8 GPU 并行,后台运行)
|
| 55 |
+
bash run_clipself_robustness.sh --nohup
|
| 56 |
+
|
| 57 |
+
# 两个可以同时运行(GPU 显存足够时)
|
| 58 |
+
bash run_clearclip_robustness.sh --nohup && bash run_clipself_robustness.sh --nohup
|
| 59 |
+
```
|
| 60 |
+
|
| 61 |
+
### 2. 监控进度
|
| 62 |
+
|
| 63 |
+
```bash
|
| 64 |
+
# 查看日志
|
| 65 |
+
tail -f logs/gpu0_clearclip.log
|
| 66 |
+
|
| 67 |
+
# 检查完成数量 (预期 75 个)
|
| 68 |
+
ls results/clearclip/*_results.pkl 2>/dev/null | wc -l
|
| 69 |
+
ls results/clipself/*_results.pkl 2>/dev/null | wc -l
|
| 70 |
+
```
|
| 71 |
+
|
| 72 |
+
### 3. 合并结果并生成报告
|
| 73 |
+
|
| 74 |
+
```bash
|
| 75 |
+
# ClearCLIP
|
| 76 |
+
python3 merge_robustness_results.py \
|
| 77 |
+
--results-dir results/clearclip \
|
| 78 |
+
--model-name ClearCLIP
|
| 79 |
+
|
| 80 |
+
# CLIPSelf
|
| 81 |
+
python3 merge_robustness_results.py \
|
| 82 |
+
--results-dir results/clipself \
|
| 83 |
+
--model-name CLIPSelf
|
| 84 |
+
```
|
| 85 |
+
|
| 86 |
+
### 4. 输出文件
|
| 87 |
+
|
| 88 |
+
- **日志报告**: 控制台输出 base_ap50、novel_ap50、all_ap50 等汇总
|
| 89 |
+
- **Excel 报告**: `results/<model>/robustness_report.xlsx`
|
| 90 |
+
- Summary: P、mPC、rPC 汇总
|
| 91 |
+
- Category mPC: 按退化类别 (noise/blur/weather/digital) 统计
|
| 92 |
+
- Corruption Avg: 每种退化类型的平均值
|
| 93 |
+
- Base Ap50 / Novel Ap50 / All Ap50: 详细 15×5 矩阵
|
| 94 |
+
- Full Matrix: 完整结果(便于复制到论文)
|
| 95 |
+
|
| 96 |
+
## 单场景测试
|
| 97 |
+
|
| 98 |
+
如需测试单个场景:
|
| 99 |
+
|
| 100 |
+
```bash
|
| 101 |
+
cd /mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/CLIPSelf/F-ViT
|
| 102 |
+
export PYTHONPATH=$PWD:/opt/tiger/xiaomoguhzz/mmdetection:$PYTHONPATH
|
| 103 |
+
|
| 104 |
+
python3 /mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/robustness_eval/test_robustness_ovcoco.py \
|
| 105 |
+
configs/declip/fvit_vitb16_upsample_fpn_bs64_3e_ovcoco_clearclip.py \
|
| 106 |
+
work_dirs/clearclip_ovcoco/epoch_3.pth \
|
| 107 |
+
--out /tmp/test.pkl \
|
| 108 |
+
--corruptions gaussian_noise \
|
| 109 |
+
--severities 1 \
|
| 110 |
+
--eval bbox
|
| 111 |
+
```
|
| 112 |
+
|
| 113 |
+
## 注意事项
|
| 114 |
+
|
| 115 |
+
1. **依赖安装**:
|
| 116 |
+
```bash
|
| 117 |
+
pip install imagecorruptions openpyxl pandas
|
| 118 |
+
```
|
| 119 |
+
|
| 120 |
+
2. **运行时间**: 75 个场景 × 4836 图像,8 GPU 并行约需 2-3 小时
|
| 121 |
+
|
| 122 |
+
3. **与旧脚本的区别**:
|
| 123 |
+
- 旧脚本使用 `mmdet/test_robustness.py`,只输出标准 COCO 指标
|
| 124 |
+
- 新脚本 `test_robustness_ovcoco.py` 调用 `CocoDatasetOV.evaluate()`,输出 OV-COCO 特有的 base/novel AP50
|
| 125 |
+
|
| 126 |
+
## 模型路径
|
| 127 |
+
|
| 128 |
+
| 模型 | Config | Checkpoint |
|
| 129 |
+
|------|--------|------------|
|
| 130 |
+
| ClearCLIP | `configs/declip/fvit_vitb16_upsample_fpn_bs64_3e_ovcoco_clearclip.py` | `work_dirs/clearclip_ovcoco/epoch_3.pth` |
|
| 131 |
+
| CLIPSelf | `configs/ov_coco/fvit_vitb16_upsample_fpn_bs64_3e_ovcoco_eva_clipself_proposals.py` | `/opt/tiger/xiaomoguhzz/fvit_eva_vitb16_ovcoco_clipself_proposals.pth` |
|
analysis/robustness_eval/compare_models.py
ADDED
|
@@ -0,0 +1,225 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
比较多个模型的 OV-COCO 鲁棒性结果
|
| 4 |
+
|
| 5 |
+
生成格式:
|
| 6 |
+
ClearCLIP CLIPSelf
|
| 7 |
+
P_clean mPC rPC (%) P_clean mPC rPC (%)
|
| 8 |
+
novel_ap50 26.74 13.84 51.76 37.51 29.27 78.05
|
| 9 |
+
base_ap50 44.00 26.21 59.57 54.94 40.81 74.27
|
| 10 |
+
all_ap50 39.49 22.97 58.17 50.38 37.79 75.01
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
import os
|
| 14 |
+
import json
|
| 15 |
+
import argparse
|
| 16 |
+
import pickle
|
| 17 |
+
|
| 18 |
+
try:
|
| 19 |
+
import pandas as pd
|
| 20 |
+
HAS_PANDAS = True
|
| 21 |
+
except ImportError:
|
| 22 |
+
HAS_PANDAS = False
|
| 23 |
+
print("Warning: pandas not installed, Excel output disabled")
|
| 24 |
+
|
| 25 |
+
# 预定义的 Clean 数据性能 (P_clean)
|
| 26 |
+
PREDEFINED_CLEAN_METRICS = {
|
| 27 |
+
'clearclip': {
|
| 28 |
+
'base_ap50': 44.00,
|
| 29 |
+
'novel_ap50': 26.74,
|
| 30 |
+
'all_ap50': 39.49,
|
| 31 |
+
'bbox_mAP': 20.30,
|
| 32 |
+
'bbox_mAP_50': 39.50,
|
| 33 |
+
},
|
| 34 |
+
'clipself': {
|
| 35 |
+
'base_ap50': 54.94,
|
| 36 |
+
'novel_ap50': 37.51,
|
| 37 |
+
'all_ap50': 50.38,
|
| 38 |
+
'bbox_mAP': 27.70,
|
| 39 |
+
'bbox_mAP_50': 50.00,
|
| 40 |
+
}
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def load_model_results(results_dir, model_name):
|
| 45 |
+
"""加载单个模型的结果"""
|
| 46 |
+
# 尝试加载 JSON 汇总
|
| 47 |
+
json_path = os.path.join(results_dir, 'robustness_summary.json')
|
| 48 |
+
if os.path.exists(json_path):
|
| 49 |
+
with open(json_path, 'r') as f:
|
| 50 |
+
return json.load(f)
|
| 51 |
+
|
| 52 |
+
# 尝试加载 pkl
|
| 53 |
+
pkl_path = os.path.join(results_dir, 'merged_results.pkl')
|
| 54 |
+
if os.path.exists(pkl_path):
|
| 55 |
+
with open(pkl_path, 'rb') as f:
|
| 56 |
+
data = pickle.load(f)
|
| 57 |
+
robustness = data.get('robustness_results', {})
|
| 58 |
+
return {
|
| 59 |
+
'model': model_name,
|
| 60 |
+
'P_clean': robustness.get('P', {}),
|
| 61 |
+
'mPC': robustness.get('mPC', {}),
|
| 62 |
+
'rPC': {k: v * 100 for k, v in robustness.get('rPC', {}).items()},
|
| 63 |
+
'category_mPC': robustness.get('category_mPC', {})
|
| 64 |
+
}
|
| 65 |
+
|
| 66 |
+
return None
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def print_comparison_table(models_data):
|
| 70 |
+
"""打印多模型比较表格"""
|
| 71 |
+
model_names = list(models_data.keys())
|
| 72 |
+
metrics = ['novel_ap50', 'base_ap50', 'all_ap50']
|
| 73 |
+
|
| 74 |
+
# 计算列宽
|
| 75 |
+
col_width = 10
|
| 76 |
+
|
| 77 |
+
# 打印表头
|
| 78 |
+
print("\n" + "=" * 80)
|
| 79 |
+
print("OV-COCO Robustness Comparison")
|
| 80 |
+
print("=" * 80)
|
| 81 |
+
|
| 82 |
+
# 打印模型名称行
|
| 83 |
+
print(f"{'Metric':<12}", end="")
|
| 84 |
+
for model in model_names:
|
| 85 |
+
print(f" | {model:^{col_width * 3 + 4}}", end="")
|
| 86 |
+
print()
|
| 87 |
+
|
| 88 |
+
# 打印子表头
|
| 89 |
+
print(f"{'':12}", end="")
|
| 90 |
+
for _ in model_names:
|
| 91 |
+
print(f" | {'P_clean':>{col_width}} {'mPC':>{col_width}} {'rPC(%)':>{col_width}}", end="")
|
| 92 |
+
print()
|
| 93 |
+
print("-" * (12 + (col_width * 3 + 5) * len(model_names)))
|
| 94 |
+
|
| 95 |
+
# 打印数据行
|
| 96 |
+
for metric in metrics:
|
| 97 |
+
print(f"{metric:<12}", end="")
|
| 98 |
+
for model in model_names:
|
| 99 |
+
data = models_data[model]
|
| 100 |
+
p_val = data.get('P_clean', {}).get(metric, None)
|
| 101 |
+
mpc_val = data.get('mPC', {}).get(metric, None)
|
| 102 |
+
rpc_val = data.get('rPC', {}).get(metric, None)
|
| 103 |
+
|
| 104 |
+
p_str = f"{p_val:.2f}" if p_val is not None else "N/A"
|
| 105 |
+
mpc_str = f"{mpc_val:.2f}" if mpc_val is not None else "N/A"
|
| 106 |
+
rpc_str = f"{rpc_val:.2f}" if rpc_val is not None else "N/A"
|
| 107 |
+
|
| 108 |
+
print(f" | {p_str:>{col_width}} {mpc_str:>{col_width}} {rpc_str:>{col_width}}", end="")
|
| 109 |
+
print()
|
| 110 |
+
|
| 111 |
+
print("=" * 80)
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def save_comparison_excel(models_data, output_path):
|
| 115 |
+
"""保存多模型比较到 Excel"""
|
| 116 |
+
if not HAS_PANDAS:
|
| 117 |
+
print("ERROR: pandas not installed, cannot save Excel")
|
| 118 |
+
return
|
| 119 |
+
|
| 120 |
+
model_names = list(models_data.keys())
|
| 121 |
+
metrics = ['novel_ap50', 'base_ap50', 'all_ap50', 'bbox_mAP', 'bbox_mAP_50']
|
| 122 |
+
|
| 123 |
+
with pd.ExcelWriter(output_path, engine='openpyxl') as writer:
|
| 124 |
+
# Sheet 1: Core Comparison
|
| 125 |
+
rows = []
|
| 126 |
+
for metric in metrics[:3]: # 只取核心指标
|
| 127 |
+
row = {'Metric': metric}
|
| 128 |
+
for model in model_names:
|
| 129 |
+
data = models_data[model]
|
| 130 |
+
row[f'{model}_P_clean'] = data.get('P_clean', {}).get(metric)
|
| 131 |
+
row[f'{model}_mPC'] = data.get('mPC', {}).get(metric)
|
| 132 |
+
row[f'{model}_rPC(%)'] = data.get('rPC', {}).get(metric)
|
| 133 |
+
rows.append(row)
|
| 134 |
+
|
| 135 |
+
df_core = pd.DataFrame(rows)
|
| 136 |
+
df_core.to_excel(writer, sheet_name='Core Comparison', index=False)
|
| 137 |
+
|
| 138 |
+
# Sheet 2: Extended Comparison
|
| 139 |
+
rows = []
|
| 140 |
+
for metric in metrics:
|
| 141 |
+
row = {'Metric': metric}
|
| 142 |
+
for model in model_names:
|
| 143 |
+
data = models_data[model]
|
| 144 |
+
row[f'{model}_P_clean'] = data.get('P_clean', {}).get(metric)
|
| 145 |
+
row[f'{model}_mPC'] = data.get('mPC', {}).get(metric)
|
| 146 |
+
row[f'{model}_rPC(%)'] = data.get('rPC', {}).get(metric)
|
| 147 |
+
rows.append(row)
|
| 148 |
+
|
| 149 |
+
df_ext = pd.DataFrame(rows)
|
| 150 |
+
df_ext.to_excel(writer, sheet_name='Extended Comparison', index=False)
|
| 151 |
+
|
| 152 |
+
# Sheet 3: Category Comparison
|
| 153 |
+
categories = ['noise', 'blur', 'weather', 'digital']
|
| 154 |
+
for metric in ['base_ap50', 'novel_ap50', 'all_ap50']:
|
| 155 |
+
rows = []
|
| 156 |
+
for cat in categories:
|
| 157 |
+
row = {'Category': cat}
|
| 158 |
+
for model in model_names:
|
| 159 |
+
data = models_data[model]
|
| 160 |
+
val = data.get('category_mPC', {}).get(cat, {}).get(metric)
|
| 161 |
+
row[model] = round(val, 2) if val is not None else None
|
| 162 |
+
rows.append(row)
|
| 163 |
+
|
| 164 |
+
df_cat = pd.DataFrame(rows)
|
| 165 |
+
df_cat.to_excel(writer, sheet_name=f'Category {metric}', index=False)
|
| 166 |
+
|
| 167 |
+
print(f"Comparison Excel saved to: {output_path}")
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
def save_comparison_json(models_data, output_path):
|
| 171 |
+
"""保存比较结果到 JSON"""
|
| 172 |
+
with open(output_path, 'w') as f:
|
| 173 |
+
json.dump(models_data, f, indent=2)
|
| 174 |
+
print(f"Comparison JSON saved to: {output_path}")
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def main():
|
| 178 |
+
parser = argparse.ArgumentParser(description='Compare OV-COCO robustness results across models')
|
| 179 |
+
parser.add_argument('--results-dirs', type=str, nargs='+', required=True,
|
| 180 |
+
help='Directories containing model results')
|
| 181 |
+
parser.add_argument('--model-names', type=str, nargs='+', default=None,
|
| 182 |
+
help='Model names (default: infer from directory names)')
|
| 183 |
+
parser.add_argument('--output-dir', type=str, default='.',
|
| 184 |
+
help='Output directory for comparison files')
|
| 185 |
+
parser.add_argument('--output-prefix', type=str, default='robustness_comparison',
|
| 186 |
+
help='Output file prefix')
|
| 187 |
+
args = parser.parse_args()
|
| 188 |
+
|
| 189 |
+
# 推断模型名称
|
| 190 |
+
if args.model_names is None:
|
| 191 |
+
args.model_names = [os.path.basename(d.rstrip('/')) for d in args.results_dirs]
|
| 192 |
+
|
| 193 |
+
if len(args.model_names) != len(args.results_dirs):
|
| 194 |
+
print("ERROR: Number of model names must match number of results directories")
|
| 195 |
+
return
|
| 196 |
+
|
| 197 |
+
# 加载所有模型结果
|
| 198 |
+
models_data = {}
|
| 199 |
+
for results_dir, model_name in zip(args.results_dirs, args.model_names):
|
| 200 |
+
print(f"Loading results for {model_name} from {results_dir}...")
|
| 201 |
+
data = load_model_results(results_dir, model_name)
|
| 202 |
+
if data:
|
| 203 |
+
models_data[model_name] = data
|
| 204 |
+
else:
|
| 205 |
+
print(f"Warning: Could not load results for {model_name}")
|
| 206 |
+
|
| 207 |
+
if not models_data:
|
| 208 |
+
print("ERROR: No valid results found!")
|
| 209 |
+
return
|
| 210 |
+
|
| 211 |
+
# 打印比较表格
|
| 212 |
+
print_comparison_table(models_data)
|
| 213 |
+
|
| 214 |
+
# 保存结果
|
| 215 |
+
os.makedirs(args.output_dir, exist_ok=True)
|
| 216 |
+
|
| 217 |
+
excel_path = os.path.join(args.output_dir, f'{args.output_prefix}.xlsx')
|
| 218 |
+
save_comparison_excel(models_data, excel_path)
|
| 219 |
+
|
| 220 |
+
json_path = os.path.join(args.output_dir, f'{args.output_prefix}.json')
|
| 221 |
+
save_comparison_json(models_data, json_path)
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
if __name__ == '__main__':
|
| 225 |
+
main()
|
analysis/robustness_eval/generate_corruption_table.py
ADDED
|
@@ -0,0 +1,291 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
生成按退化类型分类的详细表格
|
| 4 |
+
|
| 5 |
+
输出格式:
|
| 6 |
+
Corruption Category novel_ap50_PC_c novel_ap50_rPC(%) base_ap50_PC_c base_ap50_rPC(%) all_ap50_PC_c all_ap50_rPC(%)
|
| 7 |
+
gaussian_noise noise 27.32 72.83 38.18 69.50 35.34 70.15
|
| 8 |
+
shot_noise noise 27.17 72.43 37.67 68.57 34.92 69.32
|
| 9 |
+
...
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
import os
|
| 13 |
+
import json
|
| 14 |
+
import argparse
|
| 15 |
+
import pickle
|
| 16 |
+
|
| 17 |
+
try:
|
| 18 |
+
import pandas as pd
|
| 19 |
+
HAS_PANDAS = True
|
| 20 |
+
except ImportError:
|
| 21 |
+
HAS_PANDAS = False
|
| 22 |
+
print("Warning: pandas not installed, Excel output disabled")
|
| 23 |
+
|
| 24 |
+
# 15 种 benchmark 退化类型
|
| 25 |
+
BENCHMARK_CORRUPTIONS = [
|
| 26 |
+
'gaussian_noise', 'shot_noise', 'impulse_noise',
|
| 27 |
+
'defocus_blur', 'glass_blur', 'motion_blur', 'zoom_blur',
|
| 28 |
+
'snow', 'frost', 'fog', 'brightness',
|
| 29 |
+
'contrast', 'elastic_transform', 'pixelate', 'jpeg_compression'
|
| 30 |
+
]
|
| 31 |
+
|
| 32 |
+
# 退化类别
|
| 33 |
+
CORRUPTION_CATEGORIES = {
|
| 34 |
+
'gaussian_noise': 'noise',
|
| 35 |
+
'shot_noise': 'noise',
|
| 36 |
+
'impulse_noise': 'noise',
|
| 37 |
+
'defocus_blur': 'blur',
|
| 38 |
+
'glass_blur': 'blur',
|
| 39 |
+
'motion_blur': 'blur',
|
| 40 |
+
'zoom_blur': 'blur',
|
| 41 |
+
'snow': 'weather',
|
| 42 |
+
'frost': 'weather',
|
| 43 |
+
'fog': 'weather',
|
| 44 |
+
'brightness': 'weather',
|
| 45 |
+
'contrast': 'digital',
|
| 46 |
+
'elastic_transform': 'digital',
|
| 47 |
+
'pixelate': 'digital',
|
| 48 |
+
'jpeg_compression': 'digital'
|
| 49 |
+
}
|
| 50 |
+
|
| 51 |
+
# 预定义的 Clean 数据性能 (P_clean)
|
| 52 |
+
PREDEFINED_CLEAN_METRICS = {
|
| 53 |
+
'clearclip': {
|
| 54 |
+
'base_ap50': 44.00,
|
| 55 |
+
'novel_ap50': 26.74,
|
| 56 |
+
'all_ap50': 39.49,
|
| 57 |
+
},
|
| 58 |
+
'clipself': {
|
| 59 |
+
'base_ap50': 54.94,
|
| 60 |
+
'novel_ap50': 37.51,
|
| 61 |
+
'all_ap50': 50.38,
|
| 62 |
+
}
|
| 63 |
+
}
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def load_model_results(results_dir, model_name):
|
| 67 |
+
"""加载单个模型的结果"""
|
| 68 |
+
# 尝试加载 merged_results.pkl (包含详细的 corruption_avg)
|
| 69 |
+
pkl_path = os.path.join(results_dir, 'merged_results.pkl')
|
| 70 |
+
if os.path.exists(pkl_path):
|
| 71 |
+
with open(pkl_path, 'rb') as f:
|
| 72 |
+
data = pickle.load(f)
|
| 73 |
+
return data
|
| 74 |
+
|
| 75 |
+
# 尝试加载 JSON 汇总
|
| 76 |
+
json_path = os.path.join(results_dir, 'robustness_summary.json')
|
| 77 |
+
if os.path.exists(json_path):
|
| 78 |
+
with open(json_path, 'r') as f:
|
| 79 |
+
return {'robustness_results': json.load(f)}
|
| 80 |
+
|
| 81 |
+
return None
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def get_clean_metrics(model_name):
|
| 85 |
+
"""获取模型的 clean metrics"""
|
| 86 |
+
model_key = model_name.lower().replace('-', '').replace('_', '')
|
| 87 |
+
for key, metrics in PREDEFINED_CLEAN_METRICS.items():
|
| 88 |
+
if key in model_key or model_key in key:
|
| 89 |
+
return metrics.copy()
|
| 90 |
+
return {}
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def generate_corruption_table(results_dir, model_name):
|
| 94 |
+
"""生成按退化类型的详细表格"""
|
| 95 |
+
data = load_model_results(results_dir, model_name)
|
| 96 |
+
if data is None:
|
| 97 |
+
print(f"ERROR: Could not load results from {results_dir}")
|
| 98 |
+
return None
|
| 99 |
+
|
| 100 |
+
robustness = data.get('robustness_results', data)
|
| 101 |
+
corruption_avg = robustness.get('corruption_avg', {})
|
| 102 |
+
|
| 103 |
+
# 获取 P_clean
|
| 104 |
+
p_clean = robustness.get('P', robustness.get('P_clean', {}))
|
| 105 |
+
if not p_clean:
|
| 106 |
+
p_clean = get_clean_metrics(model_name)
|
| 107 |
+
|
| 108 |
+
rows = []
|
| 109 |
+
for corr in BENCHMARK_CORRUPTIONS:
|
| 110 |
+
category = CORRUPTION_CATEGORIES.get(corr, 'unknown')
|
| 111 |
+
corr_data = corruption_avg.get(corr, {})
|
| 112 |
+
|
| 113 |
+
row = {
|
| 114 |
+
'Corruption': corr,
|
| 115 |
+
'Category': category,
|
| 116 |
+
}
|
| 117 |
+
|
| 118 |
+
for metric in ['novel_ap50', 'base_ap50', 'all_ap50']:
|
| 119 |
+
pc_c = corr_data.get(metric)
|
| 120 |
+
p_clean_val = p_clean.get(metric)
|
| 121 |
+
|
| 122 |
+
# PC_c (Performance under Corruption for this corruption type)
|
| 123 |
+
row[f'{metric}_PC_c'] = round(pc_c, 2) if pc_c is not None else None
|
| 124 |
+
|
| 125 |
+
# rPC(%) = PC_c / P_clean * 100
|
| 126 |
+
if pc_c is not None and p_clean_val is not None and p_clean_val > 0:
|
| 127 |
+
rpc = (pc_c / p_clean_val) * 100
|
| 128 |
+
row[f'{metric}_rPC(%)'] = round(rpc, 2)
|
| 129 |
+
else:
|
| 130 |
+
row[f'{metric}_rPC(%)'] = None
|
| 131 |
+
|
| 132 |
+
rows.append(row)
|
| 133 |
+
|
| 134 |
+
return rows, p_clean
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def print_corruption_table(rows, model_name, p_clean):
|
| 138 |
+
"""打印退化类型表格"""
|
| 139 |
+
print(f"\n{'='*120}")
|
| 140 |
+
print(f"Corruption-level Performance: {model_name}")
|
| 141 |
+
print(f"P_clean: novel_ap50={p_clean.get('novel_ap50')}, base_ap50={p_clean.get('base_ap50')}, all_ap50={p_clean.get('all_ap50')}")
|
| 142 |
+
print(f"{'='*120}")
|
| 143 |
+
|
| 144 |
+
# 表头
|
| 145 |
+
header = f"{'Corruption':<20} {'Category':<10}"
|
| 146 |
+
for metric in ['novel_ap50', 'base_ap50', 'all_ap50']:
|
| 147 |
+
header += f" {metric+'_PC_c':>14} {metric+'_rPC(%)':>14}"
|
| 148 |
+
print(header)
|
| 149 |
+
print("-" * 120)
|
| 150 |
+
|
| 151 |
+
# 数据行
|
| 152 |
+
for row in rows:
|
| 153 |
+
line = f"{row['Corruption']:<20} {row['Category']:<10}"
|
| 154 |
+
for metric in ['novel_ap50', 'base_ap50', 'all_ap50']:
|
| 155 |
+
pc_c = row.get(f'{metric}_PC_c')
|
| 156 |
+
rpc = row.get(f'{metric}_rPC(%)')
|
| 157 |
+
pc_c_str = f"{pc_c:.2f}" if pc_c is not None else "N/A"
|
| 158 |
+
rpc_str = f"{rpc:.2f}" if rpc is not None else "N/A"
|
| 159 |
+
line += f" {pc_c_str:>14} {rpc_str:>14}"
|
| 160 |
+
print(line)
|
| 161 |
+
|
| 162 |
+
print("=" * 120)
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def save_corruption_table_excel(all_tables, output_path):
|
| 166 |
+
"""保存所有模型的退化类型表格到 Excel"""
|
| 167 |
+
if not HAS_PANDAS:
|
| 168 |
+
print("ERROR: pandas not installed, cannot save Excel")
|
| 169 |
+
return
|
| 170 |
+
|
| 171 |
+
columns = ['Corruption', 'Category',
|
| 172 |
+
'novel_ap50_PC_c', 'novel_ap50_rPC(%)',
|
| 173 |
+
'base_ap50_PC_c', 'base_ap50_rPC(%)',
|
| 174 |
+
'all_ap50_PC_c', 'all_ap50_rPC(%)']
|
| 175 |
+
|
| 176 |
+
with pd.ExcelWriter(output_path, engine='openpyxl') as writer:
|
| 177 |
+
for model_name, (rows, p_clean) in all_tables.items():
|
| 178 |
+
# 创建 DataFrame
|
| 179 |
+
df = pd.DataFrame(rows)
|
| 180 |
+
df = df[columns]
|
| 181 |
+
|
| 182 |
+
# 计算 mPC
|
| 183 |
+
mpc = {}
|
| 184 |
+
for metric in ['novel_ap50', 'base_ap50', 'all_ap50']:
|
| 185 |
+
values = [row.get(f'{metric}_PC_c') for row in rows if row.get(f'{metric}_PC_c') is not None]
|
| 186 |
+
if values:
|
| 187 |
+
mpc[metric] = sum(values) / len(values)
|
| 188 |
+
|
| 189 |
+
# 计算整体 rPC
|
| 190 |
+
rpc = {}
|
| 191 |
+
for metric in ['novel_ap50', 'base_ap50', 'all_ap50']:
|
| 192 |
+
if mpc.get(metric) and p_clean.get(metric):
|
| 193 |
+
rpc[metric] = (mpc[metric] / p_clean[metric]) * 100
|
| 194 |
+
|
| 195 |
+
# 创建汇总行 (确保每行都有完整的列)
|
| 196 |
+
summary_rows = [
|
| 197 |
+
# 空行
|
| 198 |
+
{col: None for col in columns},
|
| 199 |
+
# P_clean 行
|
| 200 |
+
{
|
| 201 |
+
'Corruption': 'P_clean',
|
| 202 |
+
'Category': None,
|
| 203 |
+
'novel_ap50_PC_c': p_clean.get('novel_ap50'),
|
| 204 |
+
'novel_ap50_rPC(%)': None,
|
| 205 |
+
'base_ap50_PC_c': p_clean.get('base_ap50'),
|
| 206 |
+
'base_ap50_rPC(%)': None,
|
| 207 |
+
'all_ap50_PC_c': p_clean.get('all_ap50'),
|
| 208 |
+
'all_ap50_rPC(%)': None,
|
| 209 |
+
},
|
| 210 |
+
# mPC 行
|
| 211 |
+
{
|
| 212 |
+
'Corruption': 'mPC',
|
| 213 |
+
'Category': None,
|
| 214 |
+
'novel_ap50_PC_c': round(mpc.get('novel_ap50', 0), 2),
|
| 215 |
+
'novel_ap50_rPC(%)': round(rpc.get('novel_ap50', 0), 2),
|
| 216 |
+
'base_ap50_PC_c': round(mpc.get('base_ap50', 0), 2),
|
| 217 |
+
'base_ap50_rPC(%)': round(rpc.get('base_ap50', 0), 2),
|
| 218 |
+
'all_ap50_PC_c': round(mpc.get('all_ap50', 0), 2),
|
| 219 |
+
'all_ap50_rPC(%)': round(rpc.get('all_ap50', 0), 2),
|
| 220 |
+
},
|
| 221 |
+
]
|
| 222 |
+
|
| 223 |
+
df_summary = pd.DataFrame(summary_rows, columns=columns)
|
| 224 |
+
|
| 225 |
+
# 合并到主 DataFrame
|
| 226 |
+
df_full = pd.concat([df, df_summary], ignore_index=True)
|
| 227 |
+
df_full.to_excel(writer, sheet_name=model_name, index=False)
|
| 228 |
+
|
| 229 |
+
print(f"Corruption table Excel saved to: {output_path}")
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
def save_corruption_table_json(all_tables, output_path):
|
| 233 |
+
"""保存所有模型的退化类型表格到 JSON"""
|
| 234 |
+
result = {}
|
| 235 |
+
for model_name, (rows, p_clean) in all_tables.items():
|
| 236 |
+
result[model_name] = {
|
| 237 |
+
'P_clean': p_clean,
|
| 238 |
+
'corruption_details': rows
|
| 239 |
+
}
|
| 240 |
+
|
| 241 |
+
with open(output_path, 'w') as f:
|
| 242 |
+
json.dump(result, f, indent=2)
|
| 243 |
+
print(f"Corruption table JSON saved to: {output_path}")
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
def main():
|
| 247 |
+
parser = argparse.ArgumentParser(description='Generate corruption-level performance table')
|
| 248 |
+
parser.add_argument('--results-dirs', type=str, nargs='+', required=True,
|
| 249 |
+
help='Directories containing model results')
|
| 250 |
+
parser.add_argument('--model-names', type=str, nargs='+', default=None,
|
| 251 |
+
help='Model names (default: infer from directory names)')
|
| 252 |
+
parser.add_argument('--output-dir', type=str, default='.',
|
| 253 |
+
help='Output directory')
|
| 254 |
+
parser.add_argument('--output-prefix', type=str, default='corruption_table',
|
| 255 |
+
help='Output file prefix')
|
| 256 |
+
args = parser.parse_args()
|
| 257 |
+
|
| 258 |
+
# 推断模型名称
|
| 259 |
+
if args.model_names is None:
|
| 260 |
+
args.model_names = [os.path.basename(d.rstrip('/')) for d in args.results_dirs]
|
| 261 |
+
|
| 262 |
+
if len(args.model_names) != len(args.results_dirs):
|
| 263 |
+
print("ERROR: Number of model names must match number of results directories")
|
| 264 |
+
return
|
| 265 |
+
|
| 266 |
+
# 生成所有模型的表格
|
| 267 |
+
all_tables = {}
|
| 268 |
+
for results_dir, model_name in zip(args.results_dirs, args.model_names):
|
| 269 |
+
print(f"Generating table for {model_name} from {results_dir}...")
|
| 270 |
+
result = generate_corruption_table(results_dir, model_name)
|
| 271 |
+
if result:
|
| 272 |
+
rows, p_clean = result
|
| 273 |
+
all_tables[model_name] = (rows, p_clean)
|
| 274 |
+
print_corruption_table(rows, model_name, p_clean)
|
| 275 |
+
|
| 276 |
+
if not all_tables:
|
| 277 |
+
print("ERROR: No valid results found!")
|
| 278 |
+
return
|
| 279 |
+
|
| 280 |
+
# 保存结果
|
| 281 |
+
os.makedirs(args.output_dir, exist_ok=True)
|
| 282 |
+
|
| 283 |
+
excel_path = os.path.join(args.output_dir, f'{args.output_prefix}.xlsx')
|
| 284 |
+
save_corruption_table_excel(all_tables, excel_path)
|
| 285 |
+
|
| 286 |
+
json_path = os.path.join(args.output_dir, f'{args.output_prefix}.json')
|
| 287 |
+
save_corruption_table_json(all_tables, json_path)
|
| 288 |
+
|
| 289 |
+
|
| 290 |
+
if __name__ == '__main__':
|
| 291 |
+
main()
|
analysis/robustness_eval/merge_robustness_results.py
ADDED
|
@@ -0,0 +1,605 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
合并 OV-COCO 鲁棒性测试结果
|
| 4 |
+
|
| 5 |
+
功能:
|
| 6 |
+
1. 加载所有单独的 pkl 结果文件
|
| 7 |
+
2. 提取 base_ap50, novel_ap50, all_ap50 以及标准 COCO 指标
|
| 8 |
+
3. 计算 P_clean、mPC、rPC 指标
|
| 9 |
+
4. 输出到控制台和 Excel 表格
|
| 10 |
+
|
| 11 |
+
输出格式示例:
|
| 12 |
+
P_clean mPC rPC (%)
|
| 13 |
+
novel_ap50 34.56 29.27 84.69
|
| 14 |
+
base_ap50 55.47 40.81 73.57
|
| 15 |
+
all_ap50 50.00 37.79 75.58
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
import os
|
| 19 |
+
import pickle
|
| 20 |
+
import argparse
|
| 21 |
+
import json
|
| 22 |
+
from collections import defaultdict
|
| 23 |
+
import numpy as np
|
| 24 |
+
|
| 25 |
+
try:
|
| 26 |
+
import pandas as pd
|
| 27 |
+
HAS_PANDAS = True
|
| 28 |
+
except ImportError:
|
| 29 |
+
HAS_PANDAS = False
|
| 30 |
+
print("Warning: pandas not installed, Excel output disabled")
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
# 15 种 benchmark 退化类型
|
| 34 |
+
BENCHMARK_CORRUPTIONS = [
|
| 35 |
+
'gaussian_noise', 'shot_noise', 'impulse_noise',
|
| 36 |
+
'defocus_blur', 'glass_blur', 'motion_blur', 'zoom_blur',
|
| 37 |
+
'snow', 'frost', 'fog', 'brightness',
|
| 38 |
+
'contrast', 'elastic_transform', 'pixelate', 'jpeg_compression'
|
| 39 |
+
]
|
| 40 |
+
|
| 41 |
+
# 退化类别
|
| 42 |
+
CORRUPTION_CATEGORIES = {
|
| 43 |
+
'noise': ['gaussian_noise', 'shot_noise', 'impulse_noise'],
|
| 44 |
+
'blur': ['defocus_blur', 'glass_blur', 'motion_blur', 'zoom_blur'],
|
| 45 |
+
'weather': ['snow', 'frost', 'fog', 'brightness'],
|
| 46 |
+
'digital': ['contrast', 'elastic_transform', 'pixelate', 'jpeg_compression']
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
# 要提取的指标
|
| 50 |
+
METRICS_TO_EXTRACT = [
|
| 51 |
+
'base_ap50', 'novel_ap50', 'all_ap50',
|
| 52 |
+
'bbox_mAP', 'bbox_mAP_50', 'bbox_mAP_75',
|
| 53 |
+
'bbox_mAP_s', 'bbox_mAP_m', 'bbox_mAP_l'
|
| 54 |
+
]
|
| 55 |
+
|
| 56 |
+
# 预定义的 Clean 数据性能 (P_clean)
|
| 57 |
+
# 来自 OV-COCO 标准测试 (无扰动)
|
| 58 |
+
PREDEFINED_CLEAN_METRICS = {
|
| 59 |
+
'clearclip': {
|
| 60 |
+
'base_ap50': 44.00,
|
| 61 |
+
'novel_ap50': 26.74,
|
| 62 |
+
'all_ap50': 39.49,
|
| 63 |
+
'bbox_mAP': 20.30,
|
| 64 |
+
'bbox_mAP_50': 39.50,
|
| 65 |
+
'bbox_mAP_75': 19.30,
|
| 66 |
+
},
|
| 67 |
+
'clipself': {
|
| 68 |
+
'base_ap50': 54.94,
|
| 69 |
+
'novel_ap50': 37.51,
|
| 70 |
+
'all_ap50': 50.38,
|
| 71 |
+
'bbox_mAP': 27.70,
|
| 72 |
+
'bbox_mAP_50': 50.00,
|
| 73 |
+
'bbox_mAP_75': 27.80,
|
| 74 |
+
}
|
| 75 |
+
}
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def load_results(results_dir):
|
| 79 |
+
"""加载所有单独的 pkl 结果文件"""
|
| 80 |
+
all_results = {}
|
| 81 |
+
|
| 82 |
+
for corr in BENCHMARK_CORRUPTIONS:
|
| 83 |
+
for sev in range(1, 6):
|
| 84 |
+
scenario = f"{corr}_{sev}"
|
| 85 |
+
|
| 86 |
+
# 尝试多种文件名格式
|
| 87 |
+
possible_files = [
|
| 88 |
+
f"{scenario}_results.pkl", # 新格式
|
| 89 |
+
f"{scenario}.pkl", # 旧格式
|
| 90 |
+
]
|
| 91 |
+
|
| 92 |
+
for fname in possible_files:
|
| 93 |
+
pkl_path = os.path.join(results_dir, fname)
|
| 94 |
+
if os.path.exists(pkl_path):
|
| 95 |
+
try:
|
| 96 |
+
with open(pkl_path, 'rb') as f:
|
| 97 |
+
data = pickle.load(f)
|
| 98 |
+
all_results[scenario] = data
|
| 99 |
+
print(f"Loaded: {scenario} from {fname}")
|
| 100 |
+
except Exception as e:
|
| 101 |
+
print(f"Error loading {pkl_path}: {e}")
|
| 102 |
+
break
|
| 103 |
+
else:
|
| 104 |
+
print(f"Missing: {scenario}")
|
| 105 |
+
|
| 106 |
+
return all_results
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def extract_metrics_from_result(result_data):
|
| 110 |
+
"""从单个结果中提取指标"""
|
| 111 |
+
metrics = {}
|
| 112 |
+
|
| 113 |
+
# 结果可能是嵌套的 dict (corruption -> severity -> metrics)
|
| 114 |
+
# 或者直接是 metrics dict
|
| 115 |
+
if isinstance(result_data, dict):
|
| 116 |
+
# 检查是否是嵌套格式 (来自 aggregated results)
|
| 117 |
+
first_key = next(iter(result_data.keys()), None)
|
| 118 |
+
if first_key and isinstance(result_data.get(first_key), dict):
|
| 119 |
+
# 可能是 {corruption: {severity: metrics}} 格式
|
| 120 |
+
# 或者是 {severity: metrics} 格式
|
| 121 |
+
first_val = result_data[first_key]
|
| 122 |
+
if isinstance(first_val, dict):
|
| 123 |
+
# 检查是否是 severity -> metrics
|
| 124 |
+
if isinstance(next(iter(first_val.values()), None), dict):
|
| 125 |
+
# {corruption: {severity: metrics}} 格式
|
| 126 |
+
# 取第一个 corruption 的第一个 severity
|
| 127 |
+
for corr_data in result_data.values():
|
| 128 |
+
for sev_data in corr_data.values():
|
| 129 |
+
if isinstance(sev_data, dict):
|
| 130 |
+
return extract_metrics_from_flat_dict(sev_data)
|
| 131 |
+
else:
|
| 132 |
+
# {severity: metrics} 或 {metric_name: value} 格式
|
| 133 |
+
return extract_metrics_from_flat_dict(result_data)
|
| 134 |
+
else:
|
| 135 |
+
# 直接是 metrics dict
|
| 136 |
+
return extract_metrics_from_flat_dict(result_data)
|
| 137 |
+
|
| 138 |
+
return metrics
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def extract_metrics_from_flat_dict(data):
|
| 142 |
+
"""从扁平的 metrics dict 中提取指标"""
|
| 143 |
+
metrics = {}
|
| 144 |
+
|
| 145 |
+
for metric_name in METRICS_TO_EXTRACT:
|
| 146 |
+
if metric_name in data:
|
| 147 |
+
val = data[metric_name]
|
| 148 |
+
# 转换为百分比(如果需要)
|
| 149 |
+
if metric_name in ['base_ap50', 'novel_ap50', 'all_ap50']:
|
| 150 |
+
# 这些已经是百分比格式
|
| 151 |
+
metrics[metric_name] = float(val)
|
| 152 |
+
elif 'mAP' in metric_name:
|
| 153 |
+
# mAP 是 0-1 格式,转为百分比
|
| 154 |
+
metrics[metric_name] = float(val) * 100
|
| 155 |
+
else:
|
| 156 |
+
metrics[metric_name] = float(val)
|
| 157 |
+
|
| 158 |
+
return metrics
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def load_and_extract_all_metrics(results_dir):
|
| 162 |
+
"""加载并提取所有结果的指标"""
|
| 163 |
+
all_metrics = {}
|
| 164 |
+
|
| 165 |
+
for corr in BENCHMARK_CORRUPTIONS:
|
| 166 |
+
all_metrics[corr] = {}
|
| 167 |
+
for sev in range(1, 6):
|
| 168 |
+
scenario = f"{corr}_{sev}"
|
| 169 |
+
|
| 170 |
+
# 尝试加载 _results.pkl 文件
|
| 171 |
+
results_pkl = os.path.join(results_dir, f"{scenario}_results.pkl")
|
| 172 |
+
if os.path.exists(results_pkl):
|
| 173 |
+
try:
|
| 174 |
+
with open(results_pkl, 'rb') as f:
|
| 175 |
+
data = pickle.load(f)
|
| 176 |
+
|
| 177 |
+
# 从 aggregated results 中提取
|
| 178 |
+
if corr in data and sev in data[corr]:
|
| 179 |
+
metrics = extract_metrics_from_flat_dict(data[corr][sev])
|
| 180 |
+
if metrics:
|
| 181 |
+
all_metrics[corr][sev] = metrics
|
| 182 |
+
print(f"Extracted from {scenario}_results.pkl: {list(metrics.keys())}")
|
| 183 |
+
continue
|
| 184 |
+
except Exception as e:
|
| 185 |
+
print(f"Error reading {results_pkl}: {e}")
|
| 186 |
+
|
| 187 |
+
# 尝试从单独的 pkl 文件加载(旧格式,可能只有 outputs)
|
| 188 |
+
pkl_path = os.path.join(results_dir, f"{scenario}.pkl")
|
| 189 |
+
if os.path.exists(pkl_path):
|
| 190 |
+
print(f"Note: {scenario}.pkl exists but needs re-evaluation for OV-COCO metrics")
|
| 191 |
+
|
| 192 |
+
return all_metrics
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
def compute_robustness_metrics(metrics_dict, clean_metrics=None):
|
| 196 |
+
"""
|
| 197 |
+
计算鲁棒性指标
|
| 198 |
+
|
| 199 |
+
Args:
|
| 200 |
+
metrics_dict: dict, {corruption: {severity: {metric: value}}}
|
| 201 |
+
clean_metrics: dict, 原始图像的指标 (P)
|
| 202 |
+
|
| 203 |
+
Returns:
|
| 204 |
+
dict with P, mPC, rPC for each metric
|
| 205 |
+
"""
|
| 206 |
+
results = {
|
| 207 |
+
'P': clean_metrics or {},
|
| 208 |
+
'mPC': {},
|
| 209 |
+
'rPC': {},
|
| 210 |
+
'corruption_avg': {},
|
| 211 |
+
'category_mPC': {},
|
| 212 |
+
'detailed': metrics_dict
|
| 213 |
+
}
|
| 214 |
+
|
| 215 |
+
# 收集每个指标在所有 corruption/severity 下的值
|
| 216 |
+
metric_values = defaultdict(list)
|
| 217 |
+
corruption_metric_values = defaultdict(lambda: defaultdict(list))
|
| 218 |
+
|
| 219 |
+
for corr in BENCHMARK_CORRUPTIONS:
|
| 220 |
+
if corr not in metrics_dict:
|
| 221 |
+
continue
|
| 222 |
+
for sev in range(1, 6):
|
| 223 |
+
if sev not in metrics_dict[corr]:
|
| 224 |
+
continue
|
| 225 |
+
for metric_name, value in metrics_dict[corr][sev].items():
|
| 226 |
+
if not np.isnan(value):
|
| 227 |
+
metric_values[metric_name].append(value)
|
| 228 |
+
corruption_metric_values[corr][metric_name].append(value)
|
| 229 |
+
|
| 230 |
+
# 计算 mPC (所有 corruption 的平均)
|
| 231 |
+
for metric_name, values in metric_values.items():
|
| 232 |
+
if values:
|
| 233 |
+
results['mPC'][metric_name] = np.mean(values)
|
| 234 |
+
|
| 235 |
+
# 计算每个 corruption 的平均
|
| 236 |
+
for corr in corruption_metric_values:
|
| 237 |
+
results['corruption_avg'][corr] = {}
|
| 238 |
+
for metric_name, values in corruption_metric_values[corr].items():
|
| 239 |
+
if values:
|
| 240 |
+
results['corruption_avg'][corr][metric_name] = np.mean(values)
|
| 241 |
+
|
| 242 |
+
# 计算每个类别的 mPC
|
| 243 |
+
for cat, corrs in CORRUPTION_CATEGORIES.items():
|
| 244 |
+
results['category_mPC'][cat] = {}
|
| 245 |
+
for metric_name in METRICS_TO_EXTRACT:
|
| 246 |
+
cat_values = []
|
| 247 |
+
for corr in corrs:
|
| 248 |
+
if corr in results['corruption_avg'] and metric_name in results['corruption_avg'][corr]:
|
| 249 |
+
cat_values.append(results['corruption_avg'][corr][metric_name])
|
| 250 |
+
if cat_values:
|
| 251 |
+
results['category_mPC'][cat][metric_name] = np.mean(cat_values)
|
| 252 |
+
|
| 253 |
+
# 计算 rPC (相对于 clean performance)
|
| 254 |
+
if clean_metrics:
|
| 255 |
+
for metric_name in results['mPC']:
|
| 256 |
+
if metric_name in clean_metrics and clean_metrics[metric_name] > 0:
|
| 257 |
+
results['rPC'][metric_name] = results['mPC'][metric_name] / clean_metrics[metric_name]
|
| 258 |
+
|
| 259 |
+
return results
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
def print_report(robustness_results, model_name="Model"):
|
| 263 |
+
"""打印鲁棒性报告"""
|
| 264 |
+
print("\n" + "=" * 80)
|
| 265 |
+
print(f"OV-COCO Robustness Evaluation Report: {model_name}")
|
| 266 |
+
print("=" * 80)
|
| 267 |
+
|
| 268 |
+
# ===== 核心汇总表 (用户期望的格式) =====
|
| 269 |
+
print("\n" + "-" * 50)
|
| 270 |
+
print("Core Summary (P_clean, mPC, rPC)")
|
| 271 |
+
print("-" * 50)
|
| 272 |
+
print(f"{'Metric':<15} {'P_clean':>10} {'mPC':>10} {'rPC (%)':>10}")
|
| 273 |
+
print("-" * 50)
|
| 274 |
+
|
| 275 |
+
core_metrics = ['novel_ap50', 'base_ap50', 'all_ap50']
|
| 276 |
+
for metric in core_metrics:
|
| 277 |
+
p_val = robustness_results['P'].get(metric, float('nan'))
|
| 278 |
+
mpc_val = robustness_results['mPC'].get(metric, float('nan'))
|
| 279 |
+
rpc_val = robustness_results['rPC'].get(metric, float('nan'))
|
| 280 |
+
|
| 281 |
+
p_str = f"{p_val:.2f}" if not np.isnan(p_val) else "N/A"
|
| 282 |
+
mpc_str = f"{mpc_val:.2f}" if not np.isnan(mpc_val) else "N/A"
|
| 283 |
+
rpc_str = f"{rpc_val*100:.2f}" if not np.isnan(rpc_val) else "N/A"
|
| 284 |
+
|
| 285 |
+
print(f"{metric:<15} {p_str:>10} {mpc_str:>10} {rpc_str:>10}")
|
| 286 |
+
print("-" * 50)
|
| 287 |
+
|
| 288 |
+
# ===== 扩展指标 =====
|
| 289 |
+
print("\nExtended Metrics:")
|
| 290 |
+
print(f"{'Metric':<15} {'P_clean':>10} {'mPC':>10} {'rPC (%)':>10}")
|
| 291 |
+
print("-" * 50)
|
| 292 |
+
|
| 293 |
+
extended_metrics = ['bbox_mAP', 'bbox_mAP_50', 'bbox_mAP_75']
|
| 294 |
+
for metric in extended_metrics:
|
| 295 |
+
p_val = robustness_results['P'].get(metric, float('nan'))
|
| 296 |
+
mpc_val = robustness_results['mPC'].get(metric, float('nan'))
|
| 297 |
+
rpc_val = robustness_results['rPC'].get(metric, float('nan'))
|
| 298 |
+
|
| 299 |
+
p_str = f"{p_val:.2f}" if not np.isnan(p_val) else "N/A"
|
| 300 |
+
mpc_str = f"{mpc_val:.2f}" if not np.isnan(mpc_val) else "N/A"
|
| 301 |
+
rpc_str = f"{rpc_val*100:.2f}" if not np.isnan(rpc_val) else "N/A"
|
| 302 |
+
|
| 303 |
+
print(f"{metric:<15} {p_str:>10} {mpc_str:>10} {rpc_str:>10}")
|
| 304 |
+
|
| 305 |
+
# ===== 按类别统计 =====
|
| 306 |
+
print("\n" + "-" * 60)
|
| 307 |
+
print("Category mPC Breakdown")
|
| 308 |
+
print("-" * 60)
|
| 309 |
+
print(f"{'Category':<12}", end="")
|
| 310 |
+
for metric in ['base_ap50', 'novel_ap50', 'all_ap50']:
|
| 311 |
+
print(f" {metric:>12}", end="")
|
| 312 |
+
print()
|
| 313 |
+
print("-" * 60)
|
| 314 |
+
|
| 315 |
+
for cat in ['noise', 'blur', 'weather', 'digital']:
|
| 316 |
+
print(f"{cat:<12}", end="")
|
| 317 |
+
for metric in ['base_ap50', 'novel_ap50', 'all_ap50']:
|
| 318 |
+
val = robustness_results['category_mPC'].get(cat, {}).get(metric, float('nan'))
|
| 319 |
+
val_str = f"{val:.2f}" if not np.isnan(val) else "N/A"
|
| 320 |
+
print(f" {val_str:>12}", end="")
|
| 321 |
+
print()
|
| 322 |
+
|
| 323 |
+
# ===== 详细结果(每个场景)=====
|
| 324 |
+
print("\n" + "-" * 70)
|
| 325 |
+
print("Detailed Results (per corruption & severity)")
|
| 326 |
+
print("-" * 70)
|
| 327 |
+
print(f"{'Corruption':<20} {'Sev':>4}", end="")
|
| 328 |
+
for metric in ['base_ap50', 'novel_ap50', 'all_ap50']:
|
| 329 |
+
print(f" {metric:>11}", end="")
|
| 330 |
+
print()
|
| 331 |
+
print("-" * 70)
|
| 332 |
+
|
| 333 |
+
detailed = robustness_results['detailed']
|
| 334 |
+
for corr in BENCHMARK_CORRUPTIONS:
|
| 335 |
+
if corr not in detailed:
|
| 336 |
+
continue
|
| 337 |
+
for sev in range(1, 6):
|
| 338 |
+
if sev not in detailed[corr]:
|
| 339 |
+
continue
|
| 340 |
+
print(f"{corr:<20} {sev:>4}", end="")
|
| 341 |
+
for metric in ['base_ap50', 'novel_ap50', 'all_ap50']:
|
| 342 |
+
val = detailed[corr][sev].get(metric, float('nan'))
|
| 343 |
+
val_str = f"{val:.2f}" if not np.isnan(val) else "N/A"
|
| 344 |
+
print(f" {val_str:>11}", end="")
|
| 345 |
+
print()
|
| 346 |
+
|
| 347 |
+
print("=" * 80)
|
| 348 |
+
|
| 349 |
+
|
| 350 |
+
def save_to_excel(robustness_results, output_path, model_name="Model"):
|
| 351 |
+
"""
|
| 352 |
+
将鲁棒性结果保存为 Excel 表格
|
| 353 |
+
|
| 354 |
+
Sheet 结构:
|
| 355 |
+
1. Core Summary - P_clean, mPC, rPC (%) 核心指标汇总
|
| 356 |
+
2. Category mPC - 按类别的 mPC 分解
|
| 357 |
+
3. Corruption Avg - 每种扰动的平均值
|
| 358 |
+
4-6. base_ap50/novel_ap50/all_ap50 详细结果
|
| 359 |
+
7. Full Matrix - 完整矩阵
|
| 360 |
+
"""
|
| 361 |
+
if not HAS_PANDAS:
|
| 362 |
+
print("ERROR: pandas not installed, cannot save Excel")
|
| 363 |
+
return
|
| 364 |
+
|
| 365 |
+
with pd.ExcelWriter(output_path, engine='openpyxl') as writer:
|
| 366 |
+
# ===== Sheet 1: Core Summary (用户期望的格式) =====
|
| 367 |
+
core_metrics = ['novel_ap50', 'base_ap50', 'all_ap50']
|
| 368 |
+
core_rows = []
|
| 369 |
+
for metric in core_metrics:
|
| 370 |
+
p_val = robustness_results['P'].get(metric, None)
|
| 371 |
+
mpc_val = robustness_results['mPC'].get(metric, None)
|
| 372 |
+
rpc_val = robustness_results['rPC'].get(metric, None)
|
| 373 |
+
core_rows.append({
|
| 374 |
+
'Metric': metric,
|
| 375 |
+
'P_clean': round(p_val, 2) if p_val is not None else None,
|
| 376 |
+
'mPC': round(mpc_val, 2) if mpc_val is not None else None,
|
| 377 |
+
'rPC (%)': round(rpc_val * 100, 2) if rpc_val is not None else None
|
| 378 |
+
})
|
| 379 |
+
df_core = pd.DataFrame(core_rows)
|
| 380 |
+
df_core.to_excel(writer, sheet_name='Core Summary', index=False)
|
| 381 |
+
|
| 382 |
+
# ===== Sheet 2: Extended Summary =====
|
| 383 |
+
key_metrics = ['base_ap50', 'novel_ap50', 'all_ap50', 'bbox_mAP', 'bbox_mAP_50', 'bbox_mAP_75']
|
| 384 |
+
summary_rows = []
|
| 385 |
+
for metric in key_metrics:
|
| 386 |
+
p_val = robustness_results['P'].get(metric, None)
|
| 387 |
+
mpc_val = robustness_results['mPC'].get(metric, None)
|
| 388 |
+
rpc_val = robustness_results['rPC'].get(metric, None)
|
| 389 |
+
summary_rows.append({
|
| 390 |
+
'Metric': metric,
|
| 391 |
+
'P_clean': round(p_val, 2) if p_val is not None else None,
|
| 392 |
+
'mPC': round(mpc_val, 2) if mpc_val is not None else None,
|
| 393 |
+
'rPC (%)': round(rpc_val * 100, 2) if rpc_val is not None else None
|
| 394 |
+
})
|
| 395 |
+
df_summary = pd.DataFrame(summary_rows)
|
| 396 |
+
df_summary.to_excel(writer, sheet_name='Extended Summary', index=False)
|
| 397 |
+
|
| 398 |
+
# ===== Sheet 3: Category mPC =====
|
| 399 |
+
category_rows = []
|
| 400 |
+
for cat in ['noise', 'blur', 'weather', 'digital']:
|
| 401 |
+
row = {'Category': cat}
|
| 402 |
+
for metric in key_metrics:
|
| 403 |
+
val = robustness_results['category_mPC'].get(cat, {}).get(metric, None)
|
| 404 |
+
row[metric] = round(val, 2) if val is not None else None
|
| 405 |
+
category_rows.append(row)
|
| 406 |
+
df_category = pd.DataFrame(category_rows)
|
| 407 |
+
df_category.to_excel(writer, sheet_name='Category mPC', index=False)
|
| 408 |
+
|
| 409 |
+
# ===== Sheet 4: Corruption Average =====
|
| 410 |
+
corr_rows = []
|
| 411 |
+
for corr in BENCHMARK_CORRUPTIONS:
|
| 412 |
+
if corr not in robustness_results['corruption_avg']:
|
| 413 |
+
continue
|
| 414 |
+
row = {'Corruption': corr}
|
| 415 |
+
for metric in key_metrics:
|
| 416 |
+
val = robustness_results['corruption_avg'][corr].get(metric, None)
|
| 417 |
+
row[metric] = round(val, 2) if val is not None else None
|
| 418 |
+
corr_rows.append(row)
|
| 419 |
+
df_corr = pd.DataFrame(corr_rows)
|
| 420 |
+
df_corr.to_excel(writer, sheet_name='Corruption Avg', index=False)
|
| 421 |
+
|
| 422 |
+
# ===== Sheet 5-7: Detailed results for base_ap50, novel_ap50, all_ap50 =====
|
| 423 |
+
for metric in ['base_ap50', 'novel_ap50', 'all_ap50']:
|
| 424 |
+
detailed_rows = []
|
| 425 |
+
for corr in BENCHMARK_CORRUPTIONS:
|
| 426 |
+
row = {'Corruption': corr}
|
| 427 |
+
if corr in robustness_results['detailed']:
|
| 428 |
+
for sev in range(1, 6):
|
| 429 |
+
if sev in robustness_results['detailed'][corr]:
|
| 430 |
+
val = robustness_results['detailed'][corr][sev].get(metric, None)
|
| 431 |
+
row[f'Sev {sev}'] = round(val, 2) if val is not None else None
|
| 432 |
+
else:
|
| 433 |
+
row[f'Sev {sev}'] = None
|
| 434 |
+
# Average
|
| 435 |
+
avg_val = robustness_results['corruption_avg'].get(corr, {}).get(metric, None)
|
| 436 |
+
row['Avg'] = round(avg_val, 2) if avg_val is not None else None
|
| 437 |
+
detailed_rows.append(row)
|
| 438 |
+
|
| 439 |
+
# 添加汇总行
|
| 440 |
+
detailed_rows.append({}) # 空行
|
| 441 |
+
mpc_row = {'Corruption': 'mPC'}
|
| 442 |
+
mpc_val = robustness_results['mPC'].get(metric, None)
|
| 443 |
+
mpc_row['Avg'] = round(mpc_val, 2) if mpc_val is not None else None
|
| 444 |
+
detailed_rows.append(mpc_row)
|
| 445 |
+
|
| 446 |
+
# 添加 rPC 行
|
| 447 |
+
rpc_row = {'Corruption': 'rPC (%)'}
|
| 448 |
+
rpc_val = robustness_results['rPC'].get(metric, None)
|
| 449 |
+
rpc_row['Avg'] = round(rpc_val * 100, 2) if rpc_val is not None else None
|
| 450 |
+
detailed_rows.append(rpc_row)
|
| 451 |
+
|
| 452 |
+
df_detailed = pd.DataFrame(detailed_rows)
|
| 453 |
+
sheet_name = metric.replace('_', ' ').title()
|
| 454 |
+
df_detailed.to_excel(writer, sheet_name=sheet_name, index=False)
|
| 455 |
+
|
| 456 |
+
# ===== Sheet 8: Full Matrix (all metrics, for paper) =====
|
| 457 |
+
matrix_rows = []
|
| 458 |
+
for corr in BENCHMARK_CORRUPTIONS:
|
| 459 |
+
if corr not in robustness_results['detailed']:
|
| 460 |
+
continue
|
| 461 |
+
for sev in range(1, 6):
|
| 462 |
+
if sev not in robustness_results['detailed'][corr]:
|
| 463 |
+
continue
|
| 464 |
+
row = {'Corruption': corr, 'Severity': sev}
|
| 465 |
+
for metric in key_metrics:
|
| 466 |
+
val = robustness_results['detailed'][corr][sev].get(metric, None)
|
| 467 |
+
row[metric] = round(val, 2) if val is not None else None
|
| 468 |
+
matrix_rows.append(row)
|
| 469 |
+
|
| 470 |
+
df_matrix = pd.DataFrame(matrix_rows)
|
| 471 |
+
df_matrix.to_excel(writer, sheet_name='Full Matrix', index=False)
|
| 472 |
+
|
| 473 |
+
print(f"Excel saved to: {output_path}")
|
| 474 |
+
|
| 475 |
+
|
| 476 |
+
def get_clean_metrics_for_model(model_name):
|
| 477 |
+
"""
|
| 478 |
+
根据模型名称获取预定义的 clean metrics
|
| 479 |
+
|
| 480 |
+
Args:
|
| 481 |
+
model_name: 模型名称 (e.g., 'clearclip', 'clipself', 'ClearCLIP', 'CLIPSelf')
|
| 482 |
+
|
| 483 |
+
Returns:
|
| 484 |
+
dict or None
|
| 485 |
+
"""
|
| 486 |
+
model_key = model_name.lower().replace('-', '').replace('_', '')
|
| 487 |
+
|
| 488 |
+
for key, metrics in PREDEFINED_CLEAN_METRICS.items():
|
| 489 |
+
if key in model_key or model_key in key:
|
| 490 |
+
return metrics.copy()
|
| 491 |
+
|
| 492 |
+
return None
|
| 493 |
+
|
| 494 |
+
|
| 495 |
+
def main():
|
| 496 |
+
parser = argparse.ArgumentParser(description='Merge OV-COCO robustness results')
|
| 497 |
+
parser.add_argument('--results-dir', type=str, required=True,
|
| 498 |
+
help='Directory containing individual pkl files')
|
| 499 |
+
parser.add_argument('--clean-results', type=str, default=None,
|
| 500 |
+
help='Path to clean (no corruption) results pkl file')
|
| 501 |
+
parser.add_argument('--output', type=str, default=None,
|
| 502 |
+
help='Output pkl file for merged results')
|
| 503 |
+
parser.add_argument('--excel', type=str, default=None,
|
| 504 |
+
help='Output Excel file path')
|
| 505 |
+
parser.add_argument('--json', type=str, default=None,
|
| 506 |
+
help='Output JSON file path for summary')
|
| 507 |
+
parser.add_argument('--model-name', type=str, default='Model',
|
| 508 |
+
help='Model name for report title (also used to auto-detect clean metrics)')
|
| 509 |
+
parser.add_argument('--clean-base-ap50', type=float, default=None,
|
| 510 |
+
help='Clean base_ap50 value (P_clean)')
|
| 511 |
+
parser.add_argument('--clean-novel-ap50', type=float, default=None,
|
| 512 |
+
help='Clean novel_ap50 value (P_clean)')
|
| 513 |
+
parser.add_argument('--clean-all-ap50', type=float, default=None,
|
| 514 |
+
help='Clean all_ap50 value (P_clean)')
|
| 515 |
+
args = parser.parse_args()
|
| 516 |
+
|
| 517 |
+
# 加载并提取所有指标
|
| 518 |
+
print("Loading and extracting metrics...")
|
| 519 |
+
all_metrics = load_and_extract_all_metrics(args.results_dir)
|
| 520 |
+
|
| 521 |
+
# 统计已加载的结果
|
| 522 |
+
loaded_count = sum(len(sev_dict) for sev_dict in all_metrics.values())
|
| 523 |
+
print(f"\nExtracted metrics from {loaded_count} / 75 scenarios")
|
| 524 |
+
|
| 525 |
+
if loaded_count == 0:
|
| 526 |
+
print("ERROR: No valid results found!")
|
| 527 |
+
print("Make sure you ran test_robustness_ovcoco.py to generate results with OV-COCO metrics.")
|
| 528 |
+
return
|
| 529 |
+
|
| 530 |
+
# 确定 clean metrics
|
| 531 |
+
clean_metrics = None
|
| 532 |
+
|
| 533 |
+
# 优先级 1: 从命令行参数
|
| 534 |
+
if args.clean_base_ap50 is not None or args.clean_novel_ap50 is not None or args.clean_all_ap50 is not None:
|
| 535 |
+
clean_metrics = {}
|
| 536 |
+
if args.clean_base_ap50 is not None:
|
| 537 |
+
clean_metrics['base_ap50'] = args.clean_base_ap50
|
| 538 |
+
if args.clean_novel_ap50 is not None:
|
| 539 |
+
clean_metrics['novel_ap50'] = args.clean_novel_ap50
|
| 540 |
+
if args.clean_all_ap50 is not None:
|
| 541 |
+
clean_metrics['all_ap50'] = args.clean_all_ap50
|
| 542 |
+
print(f"Using clean metrics from command line: {clean_metrics}")
|
| 543 |
+
|
| 544 |
+
# 优先级 2: 从 pkl 文件加载
|
| 545 |
+
elif args.clean_results and os.path.exists(args.clean_results):
|
| 546 |
+
try:
|
| 547 |
+
with open(args.clean_results, 'rb') as f:
|
| 548 |
+
clean_data = pickle.load(f)
|
| 549 |
+
clean_metrics = extract_metrics_from_result(clean_data)
|
| 550 |
+
print(f"Loaded clean results from file: {clean_metrics}")
|
| 551 |
+
except Exception as e:
|
| 552 |
+
print(f"Warning: Could not load clean results: {e}")
|
| 553 |
+
|
| 554 |
+
# 优先级 3: 使用预定义的 clean metrics (根据模型名称)
|
| 555 |
+
if clean_metrics is None:
|
| 556 |
+
clean_metrics = get_clean_metrics_for_model(args.model_name)
|
| 557 |
+
if clean_metrics:
|
| 558 |
+
print(f"Using predefined clean metrics for '{args.model_name}': {clean_metrics}")
|
| 559 |
+
else:
|
| 560 |
+
print(f"Warning: No clean metrics found for '{args.model_name}'")
|
| 561 |
+
print("Available models with predefined clean metrics:", list(PREDEFINED_CLEAN_METRICS.keys()))
|
| 562 |
+
print("You can specify clean metrics via --clean-base-ap50, --clean-novel-ap50, --clean-all-ap50")
|
| 563 |
+
|
| 564 |
+
# 计算鲁棒性指标
|
| 565 |
+
robustness_results = compute_robustness_metrics(all_metrics, clean_metrics)
|
| 566 |
+
|
| 567 |
+
# 打印报告
|
| 568 |
+
print_report(robustness_results, args.model_name)
|
| 569 |
+
|
| 570 |
+
# 保存合并结果 (pkl)
|
| 571 |
+
if args.output is None:
|
| 572 |
+
args.output = os.path.join(args.results_dir, 'merged_results.pkl')
|
| 573 |
+
|
| 574 |
+
with open(args.output, 'wb') as f:
|
| 575 |
+
pickle.dump({
|
| 576 |
+
'metrics': all_metrics,
|
| 577 |
+
'robustness_results': robustness_results
|
| 578 |
+
}, f)
|
| 579 |
+
print(f"\nMerged results saved to: {args.output}")
|
| 580 |
+
|
| 581 |
+
# 保存 Excel 报告
|
| 582 |
+
if args.excel is None:
|
| 583 |
+
args.excel = os.path.join(args.results_dir, 'robustness_report.xlsx')
|
| 584 |
+
|
| 585 |
+
save_to_excel(robustness_results, args.excel, args.model_name)
|
| 586 |
+
|
| 587 |
+
# 保存 JSON 汇总 (核心指标)
|
| 588 |
+
if args.json is None:
|
| 589 |
+
args.json = os.path.join(args.results_dir, 'robustness_summary.json')
|
| 590 |
+
|
| 591 |
+
summary_data = {
|
| 592 |
+
'model': args.model_name,
|
| 593 |
+
'P_clean': robustness_results['P'],
|
| 594 |
+
'mPC': {k: round(v, 2) for k, v in robustness_results['mPC'].items()},
|
| 595 |
+
'rPC': {k: round(v * 100, 2) for k, v in robustness_results['rPC'].items()},
|
| 596 |
+
'category_mPC': robustness_results['category_mPC']
|
| 597 |
+
}
|
| 598 |
+
|
| 599 |
+
with open(args.json, 'w') as f:
|
| 600 |
+
json.dump(summary_data, f, indent=2)
|
| 601 |
+
print(f"JSON summary saved to: {args.json}")
|
| 602 |
+
|
| 603 |
+
|
| 604 |
+
if __name__ == '__main__':
|
| 605 |
+
main()
|
analysis/robustness_eval/results/clearclip/robustness_report.xlsx
ADDED
|
Binary file (15.9 kB). View file
|
|
|
analysis/robustness_eval/results/clearclip/robustness_summary.json
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"model": "ClearCLIP",
|
| 3 |
+
"P_clean": {
|
| 4 |
+
"base_ap50": 44.0,
|
| 5 |
+
"novel_ap50": 26.74,
|
| 6 |
+
"all_ap50": 39.49,
|
| 7 |
+
"bbox_mAP": 20.3,
|
| 8 |
+
"bbox_mAP_50": 39.5,
|
| 9 |
+
"bbox_mAP_75": 19.3
|
| 10 |
+
},
|
| 11 |
+
"mPC": {
|
| 12 |
+
"base_ap50": 26.21,
|
| 13 |
+
"novel_ap50": 13.84,
|
| 14 |
+
"all_ap50": 22.97,
|
| 15 |
+
"bbox_mAP": 11.37,
|
| 16 |
+
"bbox_mAP_50": 22.98,
|
| 17 |
+
"bbox_mAP_75": 10.23,
|
| 18 |
+
"bbox_mAP_s": 3.9,
|
| 19 |
+
"bbox_mAP_m": 10.82,
|
| 20 |
+
"bbox_mAP_l": 19.85
|
| 21 |
+
},
|
| 22 |
+
"rPC": {
|
| 23 |
+
"base_ap50": 59.56,
|
| 24 |
+
"novel_ap50": 51.76,
|
| 25 |
+
"all_ap50": 58.17,
|
| 26 |
+
"bbox_mAP": 56.01,
|
| 27 |
+
"bbox_mAP_50": 58.17,
|
| 28 |
+
"bbox_mAP_75": 53.02
|
| 29 |
+
},
|
| 30 |
+
"category_mPC": {
|
| 31 |
+
"noise": {
|
| 32 |
+
"base_ap50": 19.19353333333333,
|
| 33 |
+
"novel_ap50": 9.077466666666666,
|
| 34 |
+
"all_ap50": 16.547866666666668,
|
| 35 |
+
"bbox_mAP": 8.18,
|
| 36 |
+
"bbox_mAP_50": 16.55333333333333,
|
| 37 |
+
"bbox_mAP_75": 7.333333333333333,
|
| 38 |
+
"bbox_mAP_s": 2.6733333333333333,
|
| 39 |
+
"bbox_mAP_m": 7.6000000000000005,
|
| 40 |
+
"bbox_mAP_l": 14.493333333333334
|
| 41 |
+
},
|
| 42 |
+
"blur": {
|
| 43 |
+
"base_ap50": 23.363400000000002,
|
| 44 |
+
"novel_ap50": 13.38795,
|
| 45 |
+
"all_ap50": 20.754600000000003,
|
| 46 |
+
"bbox_mAP": 9.975,
|
| 47 |
+
"bbox_mAP_50": 20.755,
|
| 48 |
+
"bbox_mAP_75": 8.635000000000002,
|
| 49 |
+
"bbox_mAP_s": 2.5549999999999997,
|
| 50 |
+
"bbox_mAP_m": 8.9,
|
| 51 |
+
"bbox_mAP_l": 18.85
|
| 52 |
+
},
|
| 53 |
+
"weather": {
|
| 54 |
+
"base_ap50": 28.861250000000002,
|
| 55 |
+
"novel_ap50": 14.41235,
|
| 56 |
+
"all_ap50": 25.082250000000002,
|
| 57 |
+
"bbox_mAP": 12.530000000000001,
|
| 58 |
+
"bbox_mAP_50": 25.08,
|
| 59 |
+
"bbox_mAP_75": 11.455000000000002,
|
| 60 |
+
"bbox_mAP_s": 5.09,
|
| 61 |
+
"bbox_mAP_m": 12.465,
|
| 62 |
+
"bbox_mAP_l": 20.595
|
| 63 |
+
},
|
| 64 |
+
"digital": {
|
| 65 |
+
"base_ap50": 31.6556,
|
| 66 |
+
"novel_ap50": 17.29665,
|
| 67 |
+
"all_ap50": 27.900150000000004,
|
| 68 |
+
"bbox_mAP": 13.999999999999998,
|
| 69 |
+
"bbox_mAP_50": 27.91,
|
| 70 |
+
"bbox_mAP_75": 12.785000000000002,
|
| 71 |
+
"bbox_mAP_s": 4.96,
|
| 72 |
+
"bbox_mAP_m": 13.495,
|
| 73 |
+
"bbox_mAP_l": 24.134999999999998
|
| 74 |
+
}
|
| 75 |
+
}
|
| 76 |
+
}
|
analysis/robustness_eval/results/clearclip/run_gpu0.sh
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
export CUDA_VISIBLE_DEVICES=0
|
| 3 |
+
|
| 4 |
+
# 切换到 F-ViT 目录(custom_imports 需要从这里找 datasets 和 models)
|
| 5 |
+
cd /mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/CLIPSelf/F-ViT
|
| 6 |
+
export PYTHONPATH=/mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/CLIPSelf/F-ViT:/opt/tiger/xiaomoguhzz/mmdetection:$PYTHONPATH
|
| 7 |
+
|
| 8 |
+
for scenario in gaussian_noise_1 gaussian_noise_2 gaussian_noise_3 gaussian_noise_4 gaussian_noise_5 shot_noise_1 shot_noise_2 shot_noise_3 shot_noise_4 shot_noise_5; do
|
| 9 |
+
# 解析 corruption 和 severity
|
| 10 |
+
corr=$(echo $scenario | rev | cut -d'_' -f2- | rev)
|
| 11 |
+
sev=$(echo $scenario | rev | cut -d'_' -f1 | rev)
|
| 12 |
+
|
| 13 |
+
output_pkl="/mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/robustness_eval/results/clearclip/${scenario}.pkl"
|
| 14 |
+
output_results_pkl="/mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/robustness_eval/results/clearclip/${scenario}_results.pkl"
|
| 15 |
+
|
| 16 |
+
# 检查 _results.pkl 是否存在(包含 OV-COCO 指标)
|
| 17 |
+
if [ -f "$output_results_pkl" ]; then
|
| 18 |
+
echo "[GPU 0] Skip existing: $scenario"
|
| 19 |
+
continue
|
| 20 |
+
fi
|
| 21 |
+
|
| 22 |
+
echo "[GPU 0] Running: $scenario (corruption=$corr, severity=$sev)"
|
| 23 |
+
|
| 24 |
+
# 使用自定义的 OV-COCO 鲁棒性测试脚本
|
| 25 |
+
python3 /mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/robustness_eval/test_robustness_ovcoco.py \
|
| 26 |
+
/mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/CLIPSelf/F-ViT/configs/declip/fvit_vitb16_upsample_fpn_bs64_3e_ovcoco_clearclip.py \
|
| 27 |
+
/mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/CLIPSelf/F-ViT/work_dirs/clearclip_ovcoco/epoch_3.pth \
|
| 28 |
+
--out $output_pkl \
|
| 29 |
+
--corruptions $corr \
|
| 30 |
+
--severities $sev \
|
| 31 |
+
--eval bbox \
|
| 32 |
+
--workers 8
|
| 33 |
+
done
|
| 34 |
+
|
| 35 |
+
echo "[GPU 0] Completed all scenarios"
|
analysis/robustness_eval/results/clearclip/run_gpu1.sh
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
export CUDA_VISIBLE_DEVICES=1
|
| 3 |
+
|
| 4 |
+
# 切换到 F-ViT 目录(custom_imports 需要从这里找 datasets 和 models)
|
| 5 |
+
cd /mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/CLIPSelf/F-ViT
|
| 6 |
+
export PYTHONPATH=/mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/CLIPSelf/F-ViT:/opt/tiger/xiaomoguhzz/mmdetection:$PYTHONPATH
|
| 7 |
+
|
| 8 |
+
for scenario in impulse_noise_1 impulse_noise_2 impulse_noise_3 impulse_noise_4 impulse_noise_5 defocus_blur_1 defocus_blur_2 defocus_blur_3 defocus_blur_4 defocus_blur_5; do
|
| 9 |
+
# 解析 corruption 和 severity
|
| 10 |
+
corr=$(echo $scenario | rev | cut -d'_' -f2- | rev)
|
| 11 |
+
sev=$(echo $scenario | rev | cut -d'_' -f1 | rev)
|
| 12 |
+
|
| 13 |
+
output_pkl="/mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/robustness_eval/results/clearclip/${scenario}.pkl"
|
| 14 |
+
output_results_pkl="/mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/robustness_eval/results/clearclip/${scenario}_results.pkl"
|
| 15 |
+
|
| 16 |
+
# 检查 _results.pkl 是否存在(包含 OV-COCO 指标)
|
| 17 |
+
if [ -f "$output_results_pkl" ]; then
|
| 18 |
+
echo "[GPU 1] Skip existing: $scenario"
|
| 19 |
+
continue
|
| 20 |
+
fi
|
| 21 |
+
|
| 22 |
+
echo "[GPU 1] Running: $scenario (corruption=$corr, severity=$sev)"
|
| 23 |
+
|
| 24 |
+
# 使用自定义的 OV-COCO 鲁棒性测试脚本
|
| 25 |
+
python3 /mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/robustness_eval/test_robustness_ovcoco.py \
|
| 26 |
+
/mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/CLIPSelf/F-ViT/configs/declip/fvit_vitb16_upsample_fpn_bs64_3e_ovcoco_clearclip.py \
|
| 27 |
+
/mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/CLIPSelf/F-ViT/work_dirs/clearclip_ovcoco/epoch_3.pth \
|
| 28 |
+
--out $output_pkl \
|
| 29 |
+
--corruptions $corr \
|
| 30 |
+
--severities $sev \
|
| 31 |
+
--eval bbox \
|
| 32 |
+
--workers 8
|
| 33 |
+
done
|
| 34 |
+
|
| 35 |
+
echo "[GPU 1] Completed all scenarios"
|
analysis/robustness_eval/results/clearclip/run_gpu2.sh
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
export CUDA_VISIBLE_DEVICES=2
|
| 3 |
+
|
| 4 |
+
# 切换到 F-ViT 目录(custom_imports 需要从这里找 datasets 和 models)
|
| 5 |
+
cd /mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/CLIPSelf/F-ViT
|
| 6 |
+
export PYTHONPATH=/mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/CLIPSelf/F-ViT:/opt/tiger/xiaomoguhzz/mmdetection:$PYTHONPATH
|
| 7 |
+
|
| 8 |
+
for scenario in glass_blur_1 glass_blur_2 glass_blur_3 glass_blur_4 glass_blur_5 motion_blur_1 motion_blur_2 motion_blur_3 motion_blur_4 motion_blur_5; do
|
| 9 |
+
# 解析 corruption 和 severity
|
| 10 |
+
corr=$(echo $scenario | rev | cut -d'_' -f2- | rev)
|
| 11 |
+
sev=$(echo $scenario | rev | cut -d'_' -f1 | rev)
|
| 12 |
+
|
| 13 |
+
output_pkl="/mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/robustness_eval/results/clearclip/${scenario}.pkl"
|
| 14 |
+
output_results_pkl="/mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/robustness_eval/results/clearclip/${scenario}_results.pkl"
|
| 15 |
+
|
| 16 |
+
# 检查 _results.pkl 是否存在(包含 OV-COCO 指标)
|
| 17 |
+
if [ -f "$output_results_pkl" ]; then
|
| 18 |
+
echo "[GPU 2] Skip existing: $scenario"
|
| 19 |
+
continue
|
| 20 |
+
fi
|
| 21 |
+
|
| 22 |
+
echo "[GPU 2] Running: $scenario (corruption=$corr, severity=$sev)"
|
| 23 |
+
|
| 24 |
+
# 使用自定义的 OV-COCO 鲁棒性测试脚本
|
| 25 |
+
python3 /mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/robustness_eval/test_robustness_ovcoco.py \
|
| 26 |
+
/mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/CLIPSelf/F-ViT/configs/declip/fvit_vitb16_upsample_fpn_bs64_3e_ovcoco_clearclip.py \
|
| 27 |
+
/mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/CLIPSelf/F-ViT/work_dirs/clearclip_ovcoco/epoch_3.pth \
|
| 28 |
+
--out $output_pkl \
|
| 29 |
+
--corruptions $corr \
|
| 30 |
+
--severities $sev \
|
| 31 |
+
--eval bbox \
|
| 32 |
+
--workers 8
|
| 33 |
+
done
|
| 34 |
+
|
| 35 |
+
echo "[GPU 2] Completed all scenarios"
|
analysis/robustness_eval/results/clearclip/run_gpu3.sh
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
export CUDA_VISIBLE_DEVICES=3
|
| 3 |
+
|
| 4 |
+
# 切换到 F-ViT 目录(custom_imports 需要从这里找 datasets 和 models)
|
| 5 |
+
cd /mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/CLIPSelf/F-ViT
|
| 6 |
+
export PYTHONPATH=/mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/CLIPSelf/F-ViT:/opt/tiger/xiaomoguhzz/mmdetection:$PYTHONPATH
|
| 7 |
+
|
| 8 |
+
for scenario in zoom_blur_1 zoom_blur_2 zoom_blur_3 zoom_blur_4 zoom_blur_5 snow_1 snow_2 snow_3 snow_4; do
|
| 9 |
+
# 解析 corruption 和 severity
|
| 10 |
+
corr=$(echo $scenario | rev | cut -d'_' -f2- | rev)
|
| 11 |
+
sev=$(echo $scenario | rev | cut -d'_' -f1 | rev)
|
| 12 |
+
|
| 13 |
+
output_pkl="/mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/robustness_eval/results/clearclip/${scenario}.pkl"
|
| 14 |
+
output_results_pkl="/mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/robustness_eval/results/clearclip/${scenario}_results.pkl"
|
| 15 |
+
|
| 16 |
+
# 检查 _results.pkl 是否存在(包含 OV-COCO 指标)
|
| 17 |
+
if [ -f "$output_results_pkl" ]; then
|
| 18 |
+
echo "[GPU 3] Skip existing: $scenario"
|
| 19 |
+
continue
|
| 20 |
+
fi
|
| 21 |
+
|
| 22 |
+
echo "[GPU 3] Running: $scenario (corruption=$corr, severity=$sev)"
|
| 23 |
+
|
| 24 |
+
# 使用自定义的 OV-COCO 鲁棒性测试脚本
|
| 25 |
+
python3 /mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/robustness_eval/test_robustness_ovcoco.py \
|
| 26 |
+
/mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/CLIPSelf/F-ViT/configs/declip/fvit_vitb16_upsample_fpn_bs64_3e_ovcoco_clearclip.py \
|
| 27 |
+
/mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/CLIPSelf/F-ViT/work_dirs/clearclip_ovcoco/epoch_3.pth \
|
| 28 |
+
--out $output_pkl \
|
| 29 |
+
--corruptions $corr \
|
| 30 |
+
--severities $sev \
|
| 31 |
+
--eval bbox \
|
| 32 |
+
--workers 8
|
| 33 |
+
done
|
| 34 |
+
|
| 35 |
+
echo "[GPU 3] Completed all scenarios"
|
analysis/robustness_eval/results/clearclip/run_gpu4.sh
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
export CUDA_VISIBLE_DEVICES=4
|
| 3 |
+
|
| 4 |
+
# 切换到 F-ViT 目录(custom_imports 需要从这里找 datasets 和 models)
|
| 5 |
+
cd /mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/CLIPSelf/F-ViT
|
| 6 |
+
export PYTHONPATH=/mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/CLIPSelf/F-ViT:/opt/tiger/xiaomoguhzz/mmdetection:$PYTHONPATH
|
| 7 |
+
|
| 8 |
+
for scenario in snow_5 frost_1 frost_2 frost_3 frost_4 frost_5 fog_1 fog_2 fog_3; do
|
| 9 |
+
# 解析 corruption 和 severity
|
| 10 |
+
corr=$(echo $scenario | rev | cut -d'_' -f2- | rev)
|
| 11 |
+
sev=$(echo $scenario | rev | cut -d'_' -f1 | rev)
|
| 12 |
+
|
| 13 |
+
output_pkl="/mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/robustness_eval/results/clearclip/${scenario}.pkl"
|
| 14 |
+
output_results_pkl="/mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/robustness_eval/results/clearclip/${scenario}_results.pkl"
|
| 15 |
+
|
| 16 |
+
# 检查 _results.pkl 是否存在(包含 OV-COCO 指标)
|
| 17 |
+
if [ -f "$output_results_pkl" ]; then
|
| 18 |
+
echo "[GPU 4] Skip existing: $scenario"
|
| 19 |
+
continue
|
| 20 |
+
fi
|
| 21 |
+
|
| 22 |
+
echo "[GPU 4] Running: $scenario (corruption=$corr, severity=$sev)"
|
| 23 |
+
|
| 24 |
+
# 使用自定义的 OV-COCO 鲁棒性测试脚本
|
| 25 |
+
python3 /mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/robustness_eval/test_robustness_ovcoco.py \
|
| 26 |
+
/mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/CLIPSelf/F-ViT/configs/declip/fvit_vitb16_upsample_fpn_bs64_3e_ovcoco_clearclip.py \
|
| 27 |
+
/mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/CLIPSelf/F-ViT/work_dirs/clearclip_ovcoco/epoch_3.pth \
|
| 28 |
+
--out $output_pkl \
|
| 29 |
+
--corruptions $corr \
|
| 30 |
+
--severities $sev \
|
| 31 |
+
--eval bbox \
|
| 32 |
+
--workers 8
|
| 33 |
+
done
|
| 34 |
+
|
| 35 |
+
echo "[GPU 4] Completed all scenarios"
|
analysis/robustness_eval/results/clearclip/run_gpu5.sh
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
export CUDA_VISIBLE_DEVICES=5
|
| 3 |
+
|
| 4 |
+
# 切换到 F-ViT 目录(custom_imports 需要从这里找 datasets 和 models)
|
| 5 |
+
cd /mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/CLIPSelf/F-ViT
|
| 6 |
+
export PYTHONPATH=/mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/CLIPSelf/F-ViT:/opt/tiger/xiaomoguhzz/mmdetection:$PYTHONPATH
|
| 7 |
+
|
| 8 |
+
for scenario in fog_4 fog_5 brightness_1 brightness_2 brightness_3 brightness_4 brightness_5 contrast_1 contrast_2; do
|
| 9 |
+
# 解析 corruption 和 severity
|
| 10 |
+
corr=$(echo $scenario | rev | cut -d'_' -f2- | rev)
|
| 11 |
+
sev=$(echo $scenario | rev | cut -d'_' -f1 | rev)
|
| 12 |
+
|
| 13 |
+
output_pkl="/mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/robustness_eval/results/clearclip/${scenario}.pkl"
|
| 14 |
+
output_results_pkl="/mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/robustness_eval/results/clearclip/${scenario}_results.pkl"
|
| 15 |
+
|
| 16 |
+
# 检查 _results.pkl 是否存在(包含 OV-COCO 指标)
|
| 17 |
+
if [ -f "$output_results_pkl" ]; then
|
| 18 |
+
echo "[GPU 5] Skip existing: $scenario"
|
| 19 |
+
continue
|
| 20 |
+
fi
|
| 21 |
+
|
| 22 |
+
echo "[GPU 5] Running: $scenario (corruption=$corr, severity=$sev)"
|
| 23 |
+
|
| 24 |
+
# 使用自定义的 OV-COCO 鲁棒性测试脚本
|
| 25 |
+
python3 /mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/robustness_eval/test_robustness_ovcoco.py \
|
| 26 |
+
/mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/CLIPSelf/F-ViT/configs/declip/fvit_vitb16_upsample_fpn_bs64_3e_ovcoco_clearclip.py \
|
| 27 |
+
/mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/CLIPSelf/F-ViT/work_dirs/clearclip_ovcoco/epoch_3.pth \
|
| 28 |
+
--out $output_pkl \
|
| 29 |
+
--corruptions $corr \
|
| 30 |
+
--severities $sev \
|
| 31 |
+
--eval bbox \
|
| 32 |
+
--workers 8
|
| 33 |
+
done
|
| 34 |
+
|
| 35 |
+
echo "[GPU 5] Completed all scenarios"
|
analysis/robustness_eval/results/clearclip/run_gpu6.sh
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
export CUDA_VISIBLE_DEVICES=6
|
| 3 |
+
|
| 4 |
+
# 切换到 F-ViT 目录(custom_imports 需要从这里找 datasets 和 models)
|
| 5 |
+
cd /mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/CLIPSelf/F-ViT
|
| 6 |
+
export PYTHONPATH=/mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/CLIPSelf/F-ViT:/opt/tiger/xiaomoguhzz/mmdetection:$PYTHONPATH
|
| 7 |
+
|
| 8 |
+
for scenario in contrast_3 contrast_4 contrast_5 elastic_transform_1 elastic_transform_2 elastic_transform_3 elastic_transform_4 elastic_transform_5 pixelate_1; do
|
| 9 |
+
# 解析 corruption 和 severity
|
| 10 |
+
corr=$(echo $scenario | rev | cut -d'_' -f2- | rev)
|
| 11 |
+
sev=$(echo $scenario | rev | cut -d'_' -f1 | rev)
|
| 12 |
+
|
| 13 |
+
output_pkl="/mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/robustness_eval/results/clearclip/${scenario}.pkl"
|
| 14 |
+
output_results_pkl="/mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/robustness_eval/results/clearclip/${scenario}_results.pkl"
|
| 15 |
+
|
| 16 |
+
# 检查 _results.pkl 是否存在(包含 OV-COCO 指标)
|
| 17 |
+
if [ -f "$output_results_pkl" ]; then
|
| 18 |
+
echo "[GPU 6] Skip existing: $scenario"
|
| 19 |
+
continue
|
| 20 |
+
fi
|
| 21 |
+
|
| 22 |
+
echo "[GPU 6] Running: $scenario (corruption=$corr, severity=$sev)"
|
| 23 |
+
|
| 24 |
+
# 使用自定义的 OV-COCO 鲁棒性测试脚本
|
| 25 |
+
python3 /mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/robustness_eval/test_robustness_ovcoco.py \
|
| 26 |
+
/mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/CLIPSelf/F-ViT/configs/declip/fvit_vitb16_upsample_fpn_bs64_3e_ovcoco_clearclip.py \
|
| 27 |
+
/mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/CLIPSelf/F-ViT/work_dirs/clearclip_ovcoco/epoch_3.pth \
|
| 28 |
+
--out $output_pkl \
|
| 29 |
+
--corruptions $corr \
|
| 30 |
+
--severities $sev \
|
| 31 |
+
--eval bbox \
|
| 32 |
+
--workers 8
|
| 33 |
+
done
|
| 34 |
+
|
| 35 |
+
echo "[GPU 6] Completed all scenarios"
|
analysis/robustness_eval/results/clearclip/run_gpu7.sh
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
export CUDA_VISIBLE_DEVICES=7
|
| 3 |
+
|
| 4 |
+
# 切换到 F-ViT 目录(custom_imports 需要从这里找 datasets 和 models)
|
| 5 |
+
cd /mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/CLIPSelf/F-ViT
|
| 6 |
+
export PYTHONPATH=/mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/CLIPSelf/F-ViT:/opt/tiger/xiaomoguhzz/mmdetection:$PYTHONPATH
|
| 7 |
+
|
| 8 |
+
for scenario in pixelate_2 pixelate_3 pixelate_4 pixelate_5 jpeg_compression_1 jpeg_compression_2 jpeg_compression_3 jpeg_compression_4 jpeg_compression_5; do
|
| 9 |
+
# 解析 corruption 和 severity
|
| 10 |
+
corr=$(echo $scenario | rev | cut -d'_' -f2- | rev)
|
| 11 |
+
sev=$(echo $scenario | rev | cut -d'_' -f1 | rev)
|
| 12 |
+
|
| 13 |
+
output_pkl="/mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/robustness_eval/results/clearclip/${scenario}.pkl"
|
| 14 |
+
output_results_pkl="/mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/robustness_eval/results/clearclip/${scenario}_results.pkl"
|
| 15 |
+
|
| 16 |
+
# 检查 _results.pkl 是否存在(包含 OV-COCO 指标)
|
| 17 |
+
if [ -f "$output_results_pkl" ]; then
|
| 18 |
+
echo "[GPU 7] Skip existing: $scenario"
|
| 19 |
+
continue
|
| 20 |
+
fi
|
| 21 |
+
|
| 22 |
+
echo "[GPU 7] Running: $scenario (corruption=$corr, severity=$sev)"
|
| 23 |
+
|
| 24 |
+
# 使用自定义的 OV-COCO 鲁棒性测试脚本
|
| 25 |
+
python3 /mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/robustness_eval/test_robustness_ovcoco.py \
|
| 26 |
+
/mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/CLIPSelf/F-ViT/configs/declip/fvit_vitb16_upsample_fpn_bs64_3e_ovcoco_clearclip.py \
|
| 27 |
+
/mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/CLIPSelf/F-ViT/work_dirs/clearclip_ovcoco/epoch_3.pth \
|
| 28 |
+
--out $output_pkl \
|
| 29 |
+
--corruptions $corr \
|
| 30 |
+
--severities $sev \
|
| 31 |
+
--eval bbox \
|
| 32 |
+
--workers 8
|
| 33 |
+
done
|
| 34 |
+
|
| 35 |
+
echo "[GPU 7] Completed all scenarios"
|
analysis/robustness_eval/results/clipself/robustness_report.xlsx
ADDED
|
Binary file (15.9 kB). View file
|
|
|
analysis/robustness_eval/results/clipself/robustness_summary.json
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"model": "CLIPSelf",
|
| 3 |
+
"P_clean": {
|
| 4 |
+
"base_ap50": 54.94,
|
| 5 |
+
"novel_ap50": 37.51,
|
| 6 |
+
"all_ap50": 50.38,
|
| 7 |
+
"bbox_mAP": 27.7,
|
| 8 |
+
"bbox_mAP_50": 50.0,
|
| 9 |
+
"bbox_mAP_75": 27.8
|
| 10 |
+
},
|
| 11 |
+
"mPC": {
|
| 12 |
+
"base_ap50": 40.81,
|
| 13 |
+
"novel_ap50": 29.27,
|
| 14 |
+
"all_ap50": 37.79,
|
| 15 |
+
"bbox_mAP": 19.27,
|
| 16 |
+
"bbox_mAP_50": 37.79,
|
| 17 |
+
"bbox_mAP_75": 17.99,
|
| 18 |
+
"bbox_mAP_s": 7.29,
|
| 19 |
+
"bbox_mAP_m": 19.82,
|
| 20 |
+
"bbox_mAP_l": 31.79
|
| 21 |
+
},
|
| 22 |
+
"rPC": {
|
| 23 |
+
"base_ap50": 74.29,
|
| 24 |
+
"novel_ap50": 78.02,
|
| 25 |
+
"all_ap50": 75.02,
|
| 26 |
+
"bbox_mAP": 69.58,
|
| 27 |
+
"bbox_mAP_50": 75.59,
|
| 28 |
+
"bbox_mAP_75": 64.72
|
| 29 |
+
},
|
| 30 |
+
"category_mPC": {
|
| 31 |
+
"noise": {
|
| 32 |
+
"base_ap50": 37.54313333333334,
|
| 33 |
+
"novel_ap50": 27.0374,
|
| 34 |
+
"all_ap50": 34.79533333333333,
|
| 35 |
+
"bbox_mAP": 17.753333333333334,
|
| 36 |
+
"bbox_mAP_50": 34.800000000000004,
|
| 37 |
+
"bbox_mAP_75": 16.513333333333332,
|
| 38 |
+
"bbox_mAP_s": 5.933333333333333,
|
| 39 |
+
"bbox_mAP_m": 17.906666666666666,
|
| 40 |
+
"bbox_mAP_l": 29.933333333333337
|
| 41 |
+
},
|
| 42 |
+
"blur": {
|
| 43 |
+
"base_ap50": 35.2237,
|
| 44 |
+
"novel_ap50": 26.4242,
|
| 45 |
+
"all_ap50": 32.92235,
|
| 46 |
+
"bbox_mAP": 16.23,
|
| 47 |
+
"bbox_mAP_50": 32.915000000000006,
|
| 48 |
+
"bbox_mAP_75": 14.58,
|
| 49 |
+
"bbox_mAP_s": 4.420000000000001,
|
| 50 |
+
"bbox_mAP_m": 15.530000000000001,
|
| 51 |
+
"bbox_mAP_l": 29.595
|
| 52 |
+
},
|
| 53 |
+
"weather": {
|
| 54 |
+
"base_ap50": 44.5319,
|
| 55 |
+
"novel_ap50": 31.022299999999998,
|
| 56 |
+
"all_ap50": 40.998850000000004,
|
| 57 |
+
"bbox_mAP": 21.240000000000002,
|
| 58 |
+
"bbox_mAP_50": 41.0,
|
| 59 |
+
"bbox_mAP_75": 20.175,
|
| 60 |
+
"bbox_mAP_s": 9.690000000000001,
|
| 61 |
+
"bbox_mAP_m": 22.71,
|
| 62 |
+
"bbox_mAP_l": 32.735
|
| 63 |
+
},
|
| 64 |
+
"digital": {
|
| 65 |
+
"base_ap50": 45.1416,
|
| 66 |
+
"novel_ap50": 32.0268,
|
| 67 |
+
"all_ap50": 41.711650000000006,
|
| 68 |
+
"bbox_mAP": 21.495,
|
| 69 |
+
"bbox_mAP_50": 41.715,
|
| 70 |
+
"bbox_mAP_75": 20.33,
|
| 71 |
+
"bbox_mAP_s": 8.775,
|
| 72 |
+
"bbox_mAP_m": 22.655,
|
| 73 |
+
"bbox_mAP_l": 34.43
|
| 74 |
+
}
|
| 75 |
+
}
|
| 76 |
+
}
|
analysis/robustness_eval/results/clipself/run_gpu0.sh
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
export CUDA_VISIBLE_DEVICES=0
|
| 3 |
+
|
| 4 |
+
# 切换到 F-ViT 目录(custom_imports 需要从这里找 datasets 和 models)
|
| 5 |
+
cd /mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/CLIPSelf/F-ViT
|
| 6 |
+
export PYTHONPATH=/mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/CLIPSelf/F-ViT:/opt/tiger/xiaomoguhzz/mmdetection:$PYTHONPATH
|
| 7 |
+
|
| 8 |
+
for scenario in gaussian_noise_1 gaussian_noise_2 gaussian_noise_3 gaussian_noise_4 gaussian_noise_5 shot_noise_1 shot_noise_2 shot_noise_3 shot_noise_4 shot_noise_5; do
|
| 9 |
+
# 解析 corruption 和 severity
|
| 10 |
+
corr=$(echo $scenario | rev | cut -d'_' -f2- | rev)
|
| 11 |
+
sev=$(echo $scenario | rev | cut -d'_' -f1 | rev)
|
| 12 |
+
|
| 13 |
+
output_pkl="/mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/robustness_eval/results/clipself/${scenario}.pkl"
|
| 14 |
+
output_results_pkl="/mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/robustness_eval/results/clipself/${scenario}_results.pkl"
|
| 15 |
+
|
| 16 |
+
# 检查 _results.pkl 是否存在(包含 OV-COCO 指标)
|
| 17 |
+
if [ -f "$output_results_pkl" ]; then
|
| 18 |
+
echo "[GPU 0] Skip existing: $scenario"
|
| 19 |
+
continue
|
| 20 |
+
fi
|
| 21 |
+
|
| 22 |
+
echo "[GPU 0] Running: $scenario (corruption=$corr, severity=$sev)"
|
| 23 |
+
|
| 24 |
+
# 使用自定义的 OV-COCO 鲁棒性测试脚本
|
| 25 |
+
python3 /mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/robustness_eval/test_robustness_ovcoco.py \
|
| 26 |
+
/mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/CLIPSelf/F-ViT/configs/ov_coco/fvit_vitb16_upsample_fpn_bs64_3e_ovcoco_eva_clipself_proposals.py \
|
| 27 |
+
/opt/tiger/xiaomoguhzz/fvit_eva_vitb16_ovcoco_clipself_proposals.pth \
|
| 28 |
+
--out $output_pkl \
|
| 29 |
+
--corruptions $corr \
|
| 30 |
+
--severities $sev \
|
| 31 |
+
--eval bbox \
|
| 32 |
+
--workers 8
|
| 33 |
+
done
|
| 34 |
+
|
| 35 |
+
echo "[GPU 0] Completed all scenarios"
|
analysis/robustness_eval/results/clipself/run_gpu1.sh
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
export CUDA_VISIBLE_DEVICES=1
|
| 3 |
+
|
| 4 |
+
# 切换到 F-ViT 目录(custom_imports 需要从这里找 datasets 和 models)
|
| 5 |
+
cd /mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/CLIPSelf/F-ViT
|
| 6 |
+
export PYTHONPATH=/mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/CLIPSelf/F-ViT:/opt/tiger/xiaomoguhzz/mmdetection:$PYTHONPATH
|
| 7 |
+
|
| 8 |
+
for scenario in impulse_noise_1 impulse_noise_2 impulse_noise_3 impulse_noise_4 impulse_noise_5 defocus_blur_1 defocus_blur_2 defocus_blur_3 defocus_blur_4 defocus_blur_5; do
|
| 9 |
+
# 解析 corruption 和 severity
|
| 10 |
+
corr=$(echo $scenario | rev | cut -d'_' -f2- | rev)
|
| 11 |
+
sev=$(echo $scenario | rev | cut -d'_' -f1 | rev)
|
| 12 |
+
|
| 13 |
+
output_pkl="/mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/robustness_eval/results/clipself/${scenario}.pkl"
|
| 14 |
+
output_results_pkl="/mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/robustness_eval/results/clipself/${scenario}_results.pkl"
|
| 15 |
+
|
| 16 |
+
# 检查 _results.pkl 是否存在(包含 OV-COCO 指标)
|
| 17 |
+
if [ -f "$output_results_pkl" ]; then
|
| 18 |
+
echo "[GPU 1] Skip existing: $scenario"
|
| 19 |
+
continue
|
| 20 |
+
fi
|
| 21 |
+
|
| 22 |
+
echo "[GPU 1] Running: $scenario (corruption=$corr, severity=$sev)"
|
| 23 |
+
|
| 24 |
+
# 使用自定义的 OV-COCO 鲁棒性测试脚本
|
| 25 |
+
python3 /mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/robustness_eval/test_robustness_ovcoco.py \
|
| 26 |
+
/mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/CLIPSelf/F-ViT/configs/ov_coco/fvit_vitb16_upsample_fpn_bs64_3e_ovcoco_eva_clipself_proposals.py \
|
| 27 |
+
/opt/tiger/xiaomoguhzz/fvit_eva_vitb16_ovcoco_clipself_proposals.pth \
|
| 28 |
+
--out $output_pkl \
|
| 29 |
+
--corruptions $corr \
|
| 30 |
+
--severities $sev \
|
| 31 |
+
--eval bbox \
|
| 32 |
+
--workers 8
|
| 33 |
+
done
|
| 34 |
+
|
| 35 |
+
echo "[GPU 1] Completed all scenarios"
|
analysis/robustness_eval/results/clipself/run_gpu2.sh
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
export CUDA_VISIBLE_DEVICES=2
|
| 3 |
+
|
| 4 |
+
# 切换到 F-ViT 目录(custom_imports 需要从这里找 datasets 和 models)
|
| 5 |
+
cd /mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/CLIPSelf/F-ViT
|
| 6 |
+
export PYTHONPATH=/mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/CLIPSelf/F-ViT:/opt/tiger/xiaomoguhzz/mmdetection:$PYTHONPATH
|
| 7 |
+
|
| 8 |
+
for scenario in glass_blur_1 glass_blur_2 glass_blur_3 glass_blur_4 glass_blur_5 motion_blur_1 motion_blur_2 motion_blur_3 motion_blur_4 motion_blur_5; do
|
| 9 |
+
# 解析 corruption 和 severity
|
| 10 |
+
corr=$(echo $scenario | rev | cut -d'_' -f2- | rev)
|
| 11 |
+
sev=$(echo $scenario | rev | cut -d'_' -f1 | rev)
|
| 12 |
+
|
| 13 |
+
output_pkl="/mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/robustness_eval/results/clipself/${scenario}.pkl"
|
| 14 |
+
output_results_pkl="/mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/robustness_eval/results/clipself/${scenario}_results.pkl"
|
| 15 |
+
|
| 16 |
+
# 检查 _results.pkl 是否存在(包含 OV-COCO 指标)
|
| 17 |
+
if [ -f "$output_results_pkl" ]; then
|
| 18 |
+
echo "[GPU 2] Skip existing: $scenario"
|
| 19 |
+
continue
|
| 20 |
+
fi
|
| 21 |
+
|
| 22 |
+
echo "[GPU 2] Running: $scenario (corruption=$corr, severity=$sev)"
|
| 23 |
+
|
| 24 |
+
# 使用自定义的 OV-COCO 鲁棒性测试脚本
|
| 25 |
+
python3 /mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/robustness_eval/test_robustness_ovcoco.py \
|
| 26 |
+
/mnt/bn/strategy-mllm-train/user/wangjunjie/code/xiaomoguhzz/DeCLIP_private/CLIPSelf/F-ViT/configs/ov_coco/fvit_vitb16_upsample_fpn_bs64_3e_ovcoco_eva_clipself_proposals.py \
|
| 27 |
+
/opt/tiger/xiaomoguhzz/fvit_eva_vitb16_ovcoco_clipself_proposals.pth \
|
| 28 |
+
--out $output_pkl \
|
| 29 |
+
--corruptions $corr \
|
| 30 |
+
--severities $sev \
|
| 31 |
+
--eval bbox \
|
| 32 |
+
--workers 8
|
| 33 |
+
done
|
| 34 |
+
|
| 35 |
+
echo "[GPU 2] Completed all scenarios"
|