File size: 6,301 Bytes
7e3773e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 | # Modified from [ViLD](https://github.com/tensorflow/tpu/tree/master/models/official/detection/projects/vild)
# TinyCLIP version for generating text embeddings
import numpy as np
import torch
import torch.nn.functional as F
from tqdm import tqdm
import sys
import os
# Add src to path
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', 'src'))
import open_clip
def article(name):
return 'an' if name[0] in 'aeiou' else 'a'
def processed_name(name, rm_dot=False):
# _ for lvis
# / for obj365
res = name.replace('_', ' ').replace('/', ' or ').lower()
if rm_dot:
res = res.rstrip('.')
return res
single_template = [
'a photo of {article} {}.'
]
multiple_templates = [
'There is {article} {} in the scene.',
'There is the {} in the scene.',
'a photo of {article} {} in the scene.',
'a photo of the {} in the scene.',
'a photo of one {} in the scene.',
'itap of {article} {}.',
'itap of my {}.', # itap: I took a picture of
'itap of the {}.',
'a photo of {article} {}.',
'a photo of my {}.',
'a photo of the {}.',
'a photo of one {}.',
'a photo of many {}.',
'a good photo of {article} {}.',
'a good photo of the {}.',
'a bad photo of {article} {}.',
'a bad photo of the {}.',
'a photo of a nice {}.',
'a photo of the nice {}.',
'a photo of a cool {}.',
'a photo of the cool {}.',
'a photo of a weird {}.',
'a photo of the weird {}.',
'a photo of a small {}.',
'a photo of the small {}.',
'a photo of a large {}.',
'a photo of the large {}.',
'a photo of a clean {}.',
'a photo of the clean {}.',
'a photo of a dirty {}.',
'a photo of the dirty {}.',
'a bright photo of {article} {}.',
'a bright photo of the {}.',
'a dark photo of {article} {}.',
'a dark photo of the {}.',
'a photo of a hard to see {}.',
'a photo of the hard to see {}.',
'a low resolution photo of {article} {}.',
'a low resolution photo of the {}.',
'a cropped photo of {article} {}.',
'a cropped photo of the {}.',
'a close-up photo of {article} {}.',
'a close-up photo of the {}.',
'a jpeg corrupted photo of {article} {}.',
'a jpeg corrupted photo of the {}.',
'a blurry photo of {article} {}.',
'a blurry photo of the {}.',
'a pixelated photo of {article} {}.',
'a pixelated photo of the {}.',
'a black and white photo of the {}.',
'a black and white photo of {article} {}.',
'a plastic {}.',
'the plastic {}.',
'a toy {}.',
'the toy {}.',
'a plushie {}.',
'the plushie {}.',
'a cartoon {}.',
'the cartoon {}.',
'an embroidered {}.',
'the embroidered {}.',
'a painting of the {}.',
'a painting of a {}.',
]
def build_text_embedding_lvis(categories, model, tokenizer):
"""Build text embeddings for categories using TinyCLIP"""
templates = multiple_templates
with torch.no_grad():
all_text_embeddings = []
for category in tqdm(categories, desc="Generating embeddings"):
texts = [
template.format(
processed_name(category, rm_dot=True), article=article(category)
)
for template in templates
]
texts = [
"This is " + text if text.startswith("a") or text.startswith("the") else text
for text in texts
]
# Tokenize texts - tokenizer returns tensor (same as inference.py)
text_tokens = tokenizer(texts).cuda()
text_embeddings = model.encode_text(text_tokens, normalized=True)
# Average over all templates
text_embedding = text_embeddings.mean(dim=0)
text_embedding /= text_embedding.norm()
all_text_embeddings.append(text_embedding)
all_text_embeddings = torch.stack(all_text_embeddings, dim=0)
return all_text_embeddings
import argparse
import json
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Generate text embeddings for TinyCLIP models')
parser.add_argument('--model_version',
default='TinyCLIP-auto-ViT-63M-32-Text-31M',
help='TinyCLIP model name')
parser.add_argument('--ann',
default='dataset/coco/annotations/panoptic_val2017.json',
help='Path to COCO panoptic annotation file')
parser.add_argument('--out_path',
default=None,
help='Output path for embeddings (auto-generated if not specified)')
parser.add_argument('--pretrained',
default='',
help='Path to pretrained checkpoint or pretrained tag')
parser.add_argument('--cache_dir',
default='checkpoints',
help='Cache directory for pretrained models')
args = parser.parse_args()
# Auto-generate output path if not specified
if args.out_path is None:
model_name_safe = args.model_version.replace('/', '-').replace(' ', '_')
args.out_path = f'metadata/coco_panoptic_clip_hand_craft_{model_name_safe}.npy'
print(f'Loading TinyCLIP model: {args.model_version}')
print(f'Pretrained: {args.pretrained if args.pretrained else "None"}')
# Create model and tokenizer using tiny_clip module directly
from open_clip import tiny_clip
model, _, _ = tiny_clip.create_model_and_transforms(
args.model_version,
pretrained=args.pretrained if args.pretrained else None,
cache_dir=args.cache_dir
)
tokenizer = tiny_clip.get_tokenizer(args.model_version)
model.cuda()
model.eval()
print('Loading', args.ann)
data = json.load(open(args.ann, 'r'))
cat_names = [x['name'] for x in
sorted(data['categories'], key=lambda x: x['id'])]
print(f'Found {len(cat_names)} categories')
print(f'Generating embeddings...')
text_embeddings = build_text_embedding_lvis(cat_names, model, tokenizer)
print(f'Saving embeddings to {args.out_path}')
np.save(args.out_path, text_embeddings.cpu().numpy())
print(f'Done! Embeddings shape: {text_embeddings.shape}')
|