forked from WalBouss/LeGrad
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathplayground_cogvlm.py
211 lines (140 loc) · 7.22 KB
/
playground_cogvlm.py
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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
import requests
from PIL import Image
import torch
import pdb
import sys
import inspect
import pdb
from transformers import AutoModelForCausalLM, LlamaTokenizer
from torchvision.transforms import Resize, Compose, ToTensor, Normalize
from legrad import LeWrapper, LePreprocess, visualize, visualize_save
# def _get_text_embedding(model, tokenizer, query, device, image):
# # # Prepare inputs using the custom build_conversation_input_ids method
# # inputs = model.build_conversation_input_ids(tokenizer, query=query, history=[], images=[image]) # chat mode
# history = []
# print("query: ", query)
# print("tokenizer: ", tokenizer)
# print("history: ", history)
# print("images: ", image)
# input_by_model = model.build_conversation_input_ids(tokenizer, query=query, history=history, images=[image])
# # if image is None:
# # inputs = model.build_conversation_input_ids(tokenizer, query=query, history=history, template_version='base')
# # else:
# # inputs = model.build_conversation_input_ids(tokenizer, query=query, history=history, images=[image])
# inputs = {
# 'input_ids': input_by_model['input_ids'].unsqueeze(0).to(DEVICE),
# 'token_type_ids': input_by_model['token_type_ids'].unsqueeze(0).to(DEVICE),
# 'attention_mask': input_by_model['attention_mask'].unsqueeze(0).to(DEVICE),
# 'images': [[input_by_model['images'][0].to(DEVICE).to(torch_type)]] if image is not None else None,
# }
# if 'cross_images' in inputs and inputs['cross_images']:
# inputs['cross_images'] = [[inputs['cross_images'][0].to(DEVICE).to(torch.bfloat16)]]
# gen_kwargs = {"max_length": 2048, "do_sample": False}
# with torch.no_grad():
# outputs = model.generate(**inputs, **gen_kwargs)
# outputs = outputs[:, inputs['input_ids'].shape[1]:]
# return outputs
# Define the preprocessing steps
# def create_cogvlm_preprocess(image_size=448):
# from torchvision import transforms
# preprocess_pipeline = transforms.Compose([
# transforms.Resize((image_size, image_size)),
# transforms.ToTensor(),
# transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
# ])
# return preprocess_pipeline
# preprocess_pipeline = create_cogvlm_preprocess()
def _get_text_embedding(model, tokenizer, query, device, image):
# Prepare inputs using the custom build_conversation_input_ids method
if image is None:
inputs = model.build_conversation_input_ids(tokenizer, query=query, history=[],
template_version='base') # chat mode
else:
inputs = model.build_conversation_input_ids(tokenizer, query=query, history=[], images=[image])
# try:
# source_code = inspect.getsource(model.build_conversation_input_ids)
# print("Source Code:\n", source_code)
# except TypeError:
# print("Couldn't retrieve source code. Function may be built-in or compiled.")
inputs = {
'input_ids': inputs['input_ids'].unsqueeze(0).to(device),
'token_type_ids': inputs['token_type_ids'].unsqueeze(0).to(device),
'attention_mask': inputs['attention_mask'].unsqueeze(0).to(device),
'images': [[inputs['images'][0].to(device).to(torch.bfloat16)]] if image is not None else None,
}
# if inputs['images'] is None or not inputs['images'][0]:
# raise ValueError("The image input is not properly initialized or is None")
gen_kwargs = {"max_length": 2048, "do_sample": False}
with torch.no_grad():
token_ids = model.generate(**inputs, **gen_kwargs)
token_ids = token_ids[:, inputs['input_ids'].shape[1]:]
print(tokenizer.decode(token_ids[0][19]))
#output = tokenizer.decode(token_ids[0])
# TODO: Obtain token_ids for all the objects in the output and embed those
# token_id_list =
# Do it for the different tokens
text_embedding = model.model.embed_tokens(token_ids[0,19])
# text_embedding = model.model.embed_tokens(token_ids[0,0])
# THIS TTEXT_EMBEDDING SHOULD THEN BE PASSED TO THE
# print("token_ids shape: ",token_ids)
# print("text_embedding shape: ",text_embedding.shape)
# output = tokenizer.decode(token_ids[0])
# breakpoint()
# print(inspect.getsource(model.model.embed_tokens))
# print("text embeddings: ", output)
# print("inputs images len:", len(inputs['images']))
# print("inputs images shape: ", inputs['images'][0][0].shape)
processed_image = inputs['images'][0][0]
return text_embedding, processed_image
def apply_transforms(image):
# Define the image size expected by the model
image_size = 224 # This size should be confirmed from the model specifications
resize_transform = Resize((image_size, image_size))
to_tensor_transform = ToTensor()
normalize_transform = Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
transform = Compose([
resize_transform,
to_tensor_transform,
normalize_transform
])
processed_image = transform(image)
return processed_image
# ------- model's paramters -------
MODEL_PATH = "THUDM/cogvlm-chat-hf"
DEVICE = 'cuda' if torch.cuda.is_available() else 'cpu'
torch_type = torch.bfloat16
# Obtain COGVLM model from HF
print("Loading Model")
model = AutoModelForCausalLM.from_pretrained(
MODEL_PATH,
torch_dtype=torch_type,
low_cpu_mem_usage=True,
trust_remote_code=True
).to(DEVICE).eval()
tokenizer = LlamaTokenizer.from_pretrained("lmsys/vicuna-7b-v1.5")
# PROCESS IMAGE
# image_path = '/home/jwiers/POPE/data/val2014/COCO_val2014_000000000042.jpg'
image = Image.open(
requests.get('http://images.cocodataset.org/val2014/COCO_val2014_000000000042.jpg', stream=True).raw).convert('RGB')
# image = Image.open(image_url)
# image_tensor = preprocess_pipeline(image).unsqueeze(0).to(DEVICE)
# text_emb, processed_image = _get_text_embedding(model, tokenizer, "a photo of a cat", DEVICE, None)
text_emb, processed_image = _get_text_embedding(model, tokenizer, "What is in the image", DEVICE, image)
print(f"Text Embeddings: {text_emb}")
processed_image = processed_image.unsqueeze(0)
print("obtained output embedding")
print("text embedding shape: ", text_emb.shape)
print("processed image shape: ", processed_image.shape)
model = LeWrapper(model)
explainability_map = model.compute_legrad_cogvlm(image=processed_image, text_embedding=text_emb)
explainability_map = explainability_map.to(torch.float32)
print("explainability_map shape: ", explainability_map.shape)
breakpoint()
# # data_config = timm.data.resolve_model_data_config(model)
# # processed_image = apply_transforms(image)
# # processed_image = processed_image.unsqueeze(0).to(dtype=torch.bfloat16).to(DEVICE)
# print("processed_image shape: ", processed_image.shape)
# #explainability_map = model.compute_legrad_vmap_clip(image=image, text_embedding=text_embedding)
# # ___ (Optional): Visualize overlay of the image + heatmap ___
visualize_save(heatmaps=explainability_map, image=image, save_path='output.png')
# visualize(heatmaps=explainability_map, image=image, save_path='output.png')