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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import argparse
|
| 3 |
+
import random
|
| 4 |
+
import numpy as np
|
| 5 |
+
import torch
|
| 6 |
+
from torch.nn import functional as F
|
| 7 |
+
from tqdm import tqdm
|
| 8 |
+
from CLIP.clip import create_model
|
| 9 |
+
from CLIP.adapter import CLIPAD
|
| 10 |
+
from sklearn.metrics import roc_auc_score, average_precision_score
|
| 11 |
+
from dataset.continual import ImageDataset
|
| 12 |
+
import csv
|
| 13 |
+
import logging
|
| 14 |
+
from CoOp import PromptMaker
|
| 15 |
+
import json
|
| 16 |
+
from safetensors.torch import load_file
|
| 17 |
+
|
| 18 |
+
os.environ["TOKENIZERS_PARALLELISM"] = "false"
|
| 19 |
+
|
| 20 |
+
import warnings
|
| 21 |
+
warnings.filterwarnings("ignore")
|
| 22 |
+
|
| 23 |
+
def setup_seed(seed):
|
| 24 |
+
os.environ['PYTHONHASHSEED'] = str(seed)
|
| 25 |
+
torch.manual_seed(seed)
|
| 26 |
+
torch.cuda.manual_seed_all(seed)
|
| 27 |
+
np.random.seed(seed)
|
| 28 |
+
random.seed(seed)
|
| 29 |
+
|
| 30 |
+
def get_logger(output_dir):
|
| 31 |
+
# set log file
|
| 32 |
+
log_file = f"{output_dir}/log.log"
|
| 33 |
+
head = '%(asctime)-15s %(message)s'
|
| 34 |
+
logging.basicConfig(filename=log_file,
|
| 35 |
+
format=head)
|
| 36 |
+
logger = logging.getLogger()
|
| 37 |
+
logger.setLevel(logging.INFO)
|
| 38 |
+
console = logging.StreamHandler()
|
| 39 |
+
logging.getLogger('').addHandler(console)
|
| 40 |
+
|
| 41 |
+
return logger
|
| 42 |
+
|
| 43 |
+
def main():
|
| 44 |
+
parser = argparse.ArgumentParser(description='Evaluation')
|
| 45 |
+
parser.add_argument('--model_name', type=str, default='ViT-L-14-336', help="ViT-B-16-plus-240, ViT-L-14-336")
|
| 46 |
+
parser.add_argument('--pretrain', type=str, default='openai', help="laion400m, openai")
|
| 47 |
+
parser.add_argument('--img_size', type=int, default=336)
|
| 48 |
+
parser.add_argument("--features_list", type=int, nargs="+", default=[6, 12, 18, 24], help="features used")
|
| 49 |
+
parser.add_argument('--seed', type=int, default=111)
|
| 50 |
+
parser.add_argument('--gpu', type=str, default="0")
|
| 51 |
+
parser.add_argument("--meta_file", type=str, default="meta_files/meta_mvtec.json")
|
| 52 |
+
parser.add_argument("--n_learnable_token", type=int, default=8, help="number of learnable token")
|
| 53 |
+
parser.add_argument("--adapter_ckpt", type=str, default="scenario2/30classes/adapters_sc2_task2.safetensors", help="adapter checkpoint path")
|
| 54 |
+
parser.add_argument("--prompt_makder_ckpt", type=str, default="scenario2/30classes/prompt_maker_sc2.safetensors", help="prompt maker checkpoint path")
|
| 55 |
+
parser.add_argument("--save_path", type=str, default="results_zero")
|
| 56 |
+
parser.add_argument("--data_root", type=str, default="data/mvtec_anomaly_detection")
|
| 57 |
+
|
| 58 |
+
args = parser.parse_args()
|
| 59 |
+
|
| 60 |
+
setup_seed(args.seed)
|
| 61 |
+
|
| 62 |
+
use_cuda = torch.cuda.is_available()
|
| 63 |
+
device = torch.device("cuda:{}".format(args.gpu) if use_cuda else "cpu")
|
| 64 |
+
|
| 65 |
+
save_path = args.save_path
|
| 66 |
+
if not os.path.isdir(save_path):
|
| 67 |
+
os.makedirs(save_path)
|
| 68 |
+
|
| 69 |
+
# for logging
|
| 70 |
+
logger = get_logger(save_path)
|
| 71 |
+
logger.info(args)
|
| 72 |
+
|
| 73 |
+
# fixed feature extractor
|
| 74 |
+
clip_model = create_model(model_name=args.model_name, img_size=args.img_size, device=device, pretrained=args.pretrain, require_pretrained=True)
|
| 75 |
+
|
| 76 |
+
# prompt learner
|
| 77 |
+
prompts = {
|
| 78 |
+
"normal": [
|
| 79 |
+
"This is an example of a normal object",
|
| 80 |
+
"This is a typical appearance of the object",
|
| 81 |
+
"This is what a normal object looks like",
|
| 82 |
+
"A photo of a normal object",
|
| 83 |
+
"This is not an anomaly",
|
| 84 |
+
"This is an example of a standard object.",
|
| 85 |
+
"This is the standard appearance of the object.",
|
| 86 |
+
"This is what a standard object looks like.",
|
| 87 |
+
"A photo of a standard object.",
|
| 88 |
+
"This object meets standard characteristics."
|
| 89 |
+
],
|
| 90 |
+
"abnormal": [
|
| 91 |
+
"This is an example of an anomalous object",
|
| 92 |
+
"This is not the typical appearance of the object",
|
| 93 |
+
"This is what an anomaly looks like",
|
| 94 |
+
"A photo of an anomalous object",
|
| 95 |
+
"An anomaly detected in this object",
|
| 96 |
+
"This is an example of an abnormal object.",
|
| 97 |
+
"This is not the usual appearance of the object.",
|
| 98 |
+
"This is what an abnormal object looks like.",
|
| 99 |
+
"A photo of an abnormal object.",
|
| 100 |
+
"An abnormality detected in this object."
|
| 101 |
+
]
|
| 102 |
+
}
|
| 103 |
+
|
| 104 |
+
clip_model.device = device
|
| 105 |
+
clip_model.to(device)
|
| 106 |
+
|
| 107 |
+
prompt_maker = PromptMaker(
|
| 108 |
+
prompts=prompts,
|
| 109 |
+
clip_model=clip_model,
|
| 110 |
+
n_ctx= args.n_learnable_token,
|
| 111 |
+
CSC = True,
|
| 112 |
+
class_token_position=['end'],
|
| 113 |
+
).to(device)
|
| 114 |
+
|
| 115 |
+
model = CLIPAD(clip_model=clip_model, features=args.features_list)
|
| 116 |
+
model.to(device)
|
| 117 |
+
model.eval()
|
| 118 |
+
|
| 119 |
+
# load checkpoint
|
| 120 |
+
adpater_state_dict = load_file(args.adapter_ckpt)
|
| 121 |
+
model.adapters.load_state_dict(adpater_state_dict)
|
| 122 |
+
logger.info(f"load adapter from {args.adapter_ckpt}")
|
| 123 |
+
prompt_state_dict = load_file(args.prompt_makder_ckpt)
|
| 124 |
+
prompt_maker.prompt_learner.load_state_dict(prompt_state_dict)
|
| 125 |
+
logger.info(f"load prompt maker from {args.prompt_makder_ckpt}")
|
| 126 |
+
|
| 127 |
+
kwargs = {'num_workers': 4, 'pin_memory': True} if use_cuda else {}
|
| 128 |
+
|
| 129 |
+
prompt_maker.eval()
|
| 130 |
+
model.eval()
|
| 131 |
+
|
| 132 |
+
logging.info(f"start zero shot {args.meta_file} test")
|
| 133 |
+
task_meta = json.load(open(args.meta_file, 'r'))
|
| 134 |
+
|
| 135 |
+
class_name_list = list(task_meta["test"].keys())
|
| 136 |
+
test_dataset_list = [ImageDataset(data_root=args.data_root, meta_file=task_meta, resize=args.img_size, mode="test", test_class=class_name) for class_name in class_name_list]
|
| 137 |
+
test_loader_list = [torch.utils.data.DataLoader(test_dataset, batch_size=1, shuffle=False, **kwargs) for test_dataset in test_dataset_list]
|
| 138 |
+
|
| 139 |
+
with torch.cuda.amp.autocast(), torch.no_grad():
|
| 140 |
+
# test all class
|
| 141 |
+
seg_ap_list = []
|
| 142 |
+
img_auc_list = []
|
| 143 |
+
prompt_maker.eval()
|
| 144 |
+
model.eval()
|
| 145 |
+
text_features = prompt_maker()
|
| 146 |
+
|
| 147 |
+
for test_loader, class_name in zip(test_loader_list, class_name_list):
|
| 148 |
+
logger.info(f"start test {class_name}")
|
| 149 |
+
roc_auc_im, seg_ap = test(args, model, test_loader, text_features, device)
|
| 150 |
+
logger.info(f'{class_name} P-AP : {round(seg_ap,4)}')
|
| 151 |
+
logger.info(f'{class_name} I-AUC : {round(roc_auc_im, 4)}')
|
| 152 |
+
seg_ap_list.append(seg_ap)
|
| 153 |
+
img_auc_list.append(roc_auc_im)
|
| 154 |
+
|
| 155 |
+
seg_ap_mean = np.mean(seg_ap_list)
|
| 156 |
+
img_auc_mean = np.mean(img_auc_list)
|
| 157 |
+
|
| 158 |
+
logger.info(f'Average P-AP : {round(seg_ap_mean,4)}')
|
| 159 |
+
logger.info(f'Average I-AUC : {round(img_auc_mean, 4)}')
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def test(args, model, test_loader, text_features, device):
|
| 163 |
+
gt_list = []
|
| 164 |
+
gt_mask_list = []
|
| 165 |
+
|
| 166 |
+
seg_score_map_zero = []
|
| 167 |
+
image_scores = []
|
| 168 |
+
for data in tqdm(test_loader):
|
| 169 |
+
image, mask, cls_name, label = data['image'], data['mask'], data['cls_name'], data['anomaly']
|
| 170 |
+
image = image.to(device)
|
| 171 |
+
mask[mask > 0.5], mask[mask <= 0.5] = 1, 0
|
| 172 |
+
|
| 173 |
+
with torch.no_grad(), torch.cuda.amp.autocast():
|
| 174 |
+
_, ada_patch_tokens = model(image)
|
| 175 |
+
ada_patch_tokens = [p[0, 1:, :] for p in ada_patch_tokens]
|
| 176 |
+
|
| 177 |
+
anomaly_maps = []
|
| 178 |
+
image_score = 0
|
| 179 |
+
for layer in range(len(ada_patch_tokens)):
|
| 180 |
+
ada_patch_tokens[layer] /= ada_patch_tokens[layer].norm(dim=-1, keepdim=True)
|
| 181 |
+
anomaly_map = (100.0 * ada_patch_tokens[layer] @ text_features).unsqueeze(0)
|
| 182 |
+
B, L, C = anomaly_map.shape
|
| 183 |
+
H = int(np.sqrt(L))
|
| 184 |
+
|
| 185 |
+
# image
|
| 186 |
+
anomaly_score = torch.softmax(anomaly_map, dim=-1)[:, :, 1]
|
| 187 |
+
image_score += anomaly_score.max()
|
| 188 |
+
|
| 189 |
+
anomaly_maps.append(anomaly_map)
|
| 190 |
+
|
| 191 |
+
score_map = torch.mean(torch.stack(anomaly_maps, dim=1), dim=1)
|
| 192 |
+
score_map = F.interpolate(score_map.permute(0, 2, 1).view(B, 2, H, H),
|
| 193 |
+
size=args.img_size, mode='bilinear', align_corners=True)
|
| 194 |
+
score_map = torch.softmax(score_map, dim=1)[:, 1, :, :]
|
| 195 |
+
score_map = score_map.squeeze(0).cpu().numpy()
|
| 196 |
+
seg_score_map_zero.append(score_map)
|
| 197 |
+
image_scores.append(image_score.cpu() / len(ada_patch_tokens))
|
| 198 |
+
|
| 199 |
+
gt_mask_list.append(mask.squeeze().cpu().detach().numpy())
|
| 200 |
+
gt_list.extend(label.cpu().detach().numpy())
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
gt_list = np.array(gt_list)
|
| 204 |
+
gt_mask_list = np.asarray(gt_mask_list)
|
| 205 |
+
gt_mask_list = (gt_mask_list>0).astype(np.int_)
|
| 206 |
+
|
| 207 |
+
segment_scores = np.array(seg_score_map_zero)
|
| 208 |
+
image_scores = np.array(image_scores)
|
| 209 |
+
|
| 210 |
+
roc_auc_im = roc_auc_score(gt_list, image_scores)
|
| 211 |
+
|
| 212 |
+
seg_pr = average_precision_score(gt_mask_list.flatten(), segment_scores.flatten())
|
| 213 |
+
|
| 214 |
+
return roc_auc_im, seg_pr
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
if __name__ == '__main__':
|
| 218 |
+
main()
|
| 219 |
+
|
| 220 |
+
|