DeCLIP-TPAMI / tools /generate_text_embeddings_tinyclip.py
xiaomoguhzz's picture
Add files using upload-large-folder tool
7e3773e verified
# 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}')