Views
No views yet

1import os
2os.environ["CUDA_VISIBLE_DEVICES"] = "0"
3
4from transformers import AutoModel, AutoConfig, AutoTokenizer
5from eva_clip import create_model_and_transforms
6from llm2vec import LLM2Vec
7from PIL import Image
8import torch
9
10
11model, _, preprocess_val = create_model_and_transforms('EVA02-CLIP-L-14-336', force_custom_clip=True)
12ckpt = torch.load('LLM2CLIP-EVA02-L-14-336.pt')
13model.load_state_dict(ckpt)
14model = model.cuda().eval()
15
16llm_model_name = 'microsoft/LLM2CLIP-Llama-3-8B-Instruct-CC-Finetuned'
17config = AutoConfig.from_pretrained(
18 llm_model_name, trust_remote_code=True
19)
20llm_model = AutoModel.from_pretrained(llm_model_name, torch_dtype=torch.bfloat16, config=config, trust_remote_code=True)
21tokenizer = AutoTokenizer.from_pretrained(llm_model_name)
22llm_model.config._name_or_path = 'meta-llama/Meta-Llama-3-8B-Instruct' # Workaround for LLM2VEC
23l2v = LLM2Vec(llm_model, tokenizer, pooling_mode="mean", max_length=512, doc_max_length=512)
24
25image_path = "CLIP.png"
26captions = ["a diagram", "a dog", "a cat"]
27
28image = preprocess_val(Image.open(image_path)).cuda().unsqueeze(dim=0)
29text_features = l2v.encode(captions, convert_to_tensor=True).to('cuda')
30
31with torch.no_grad(), torch.cuda.amp.autocast():
32 image_features = model.encode_image(image)
33 text_features = model.encode_text(text_features)
34
35 image_features /= image_features.norm(dim=-1, keepdim=True)
36 text_features /= text_features.norm(dim=-1, keepdim=True)
37
38 text_probs = (100.0 * image_features @ text_features.T).softmax(dim=-1)
39
40print("Label probs:", text_probs)@misc{huang2024llm2clippowerfullanguagemodel,
title={LLM2CLIP: Powerful Language Model Unlock Richer Visual Representation},
author={Weiquan Huang and Aoqi Wu and Yifan Yang and Xufang Luo and Yuqing Yang and Liang Hu and Qi Dai and Xiyang Dai and Dongdong Chen and Chong Luo and Lili Qiu},
year={2024},
eprint={2411.04997},
archivePrefix={arXiv},
primaryClass={cs.CV},
url={https://arxiv.org/abs/2411.04997},
}