1: import os
2: import numpy as np
3: import torch
4: import clip
5: from PIL import Image
6: from tqdm import tqdm
7: import argparse
8: 
9: 
10: @torch.no_grad()
11: def calc_class_protos(img_dir):
12:     all_images = os.listdir(img_dir)
13:     all_images = [fn for fn in all_images if fn.endswith('.png')]
14:     cls_protos = {}
15:     for fn in tqdm(all_images):
16:         if not fn.endswith('.png'):
17:             continue
18:         info = fn[:-4]
19:         idx, cls = info.split('-')
20:         idx, cls = int(idx), int(cls)
21:         img = preprocess(Image.open(os.path.join(img_dir, fn))).unsqueeze(0).to(device)
22:         f_img = model.encode_image(img)
23:         if cls_protos.get(cls) is None:
24:             cls_protos[cls] = []
25:         cls_protos[cls].append(f_img)
26: 
27:     cls_protos_list = [None] * len(cls_protos)
28:     for cls in cls_protos:
29:         cls_protos_list[cls] = torch.mean(torch.cat(cls_protos[cls], dim=0), keepdim=True).to(device)
30:     cat_cls_protos = torch.cat(cls_protos_list, dim=0)
31:     print('Class prototypes: \n', cat_cls_protos)
32:     return cat_cls_protos
33: 
34: 
35: @torch.no_grad()
36: def main():
37:     parser = argparse.ArgumentParser(description='CSM')
38:     parser.add_argument('--dset_name', type=str, default='c10', help='Dataset label')  # c10/c100/tiny
39:     parser.add_argument('--clip_path', type=str, default='./your/path/to/CLIP', help='CLIP download path')
40:     parser.add_argument('--train_path', type=str, default='./your/path/to/train/set', help='Path to the training images')
41:     parser.add_argument('--mix_path', type=str, default='./your/path/to/generated/samples', help='Path to the generated samples')
42:     args = parser.parse_args()
43: 
44:     # model
45:     device = "cuda" if torch.cuda.is_available() else "cpu"
46:     model, preprocess = clip.load("ViT-B/32", device=device, download_root=args.clip_path)
47:     dset_root = args.train_path
48:     cls_protos = calc_class_protos(dset_root)
49: 
50:     root = args.mix_path
51:     all_images_in_root = os.listdir(root)
52:     all_keys = []
53:     for fn in tqdm(all_images_in_root):
54:         if not fn.endswith('.png'):
55:             continue
56:         info = fn[:-4]
57:         gen_seed, c1, c2, gen_lam = info.split('_')
58:         all_keys.append(f'{gen_seed}_{c1}_{c2}')
59: 
60:     lams_all = []
61:     lam_dict_to_save = {}
62: 
63:     for fn_pref in tqdm(all_keys):
64:         all_fns = [fn for fn in all_images_in_root if fn.startswith(fn_pref)]
65:         group_images = []
66: 
67:         for fn in all_fns:
68:             info = fn[:-4]
69:             gen_seed, c1, c2, gen_lam = info.split('_')
70:             gen_seed, c1, c2, gen_lam = int(gen_seed), int(c1), int(c2), float(gen_lam)
71:             img = preprocess(Image.open(os.path.join(root, fn))).unsqueeze(0).to(device)
72:             group_images.append(img)
73:         group_images = torch.cat(group_images, dim=0)
74:         in_img_features = model.encode_image(group_images)
75:         src_feature = cls_protos[c1]
76:         tgt_feature = cls_protos[c2]
77:         delta_x = src_feature - tgt_feature
78:         delta_x_2 = delta_x @ delta_x.t()
79:         lams = []
80:         for in_img_feature in in_img_features:
81:             lam_by_x = ((in_img_feature - tgt_feature) @ delta_x.t() / delta_x_2).item()
82:             lams.append(lam_by_x)
83:             lams_all.append(lam_by_x)
84:             lam_dict_to_save[fn] = lam_by_x
85:     torch.save(lam_dict_to_save, f'./annotations/clip_lam_anno_edm_{args.dset_name}.pth')