Spaces:
Sleeping
Sleeping
Narayana02
commited on
Commit
•
f7fb976
1
Parent(s):
5bde38f
Upload 3 files
Browse files- app.py +211 -0
- packages.txt +1 -0
- requirements.txt +9 -0
app.py
ADDED
@@ -0,0 +1,211 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
import torch
|
3 |
+
import onnxruntime as ort
|
4 |
+
from PIL import Image
|
5 |
+
import requests
|
6 |
+
import numpy as np
|
7 |
+
from transformers import AutoTokenizer, AutoProcessor
|
8 |
+
import os
|
9 |
+
|
10 |
+
if not os.path.exists("vision_encoder_q4f16.onnx"):
|
11 |
+
os.system('wget https://huggingface.co/llava-hf/llava-interleave-qwen-0.5b-hf/resolve/main/onnx/vision_encoder_q4f16.onnx')
|
12 |
+
if not os.path.exists("decoder_model_merged_q4f16.onnx"):
|
13 |
+
os.system('wget https://huggingface.co/llava-hf/llava-interleave-qwen-0.5b-hf/resolve/main/onnx/decoder_model_merged_q4f16.onnx')
|
14 |
+
if not os.path.exists("embed_tokens_q4f16.onnx"):
|
15 |
+
os.system('wget https://huggingface.co/llava-hf/llava-interleave-qwen-0.5b-hf/resolve/main/onnx/embed_tokens_q4f16.onnx')
|
16 |
+
|
17 |
+
# Load the tokenizer and processor
|
18 |
+
tokenizer = AutoTokenizer.from_pretrained("llava-hf/llava-interleave-qwen-0.5b-hf")
|
19 |
+
processor = AutoProcessor.from_pretrained("llava-hf/llava-interleave-qwen-0.5b-hf")
|
20 |
+
|
21 |
+
vision_encoder_session = ort.InferenceSession("vision_encoder_q4f16.onnx")
|
22 |
+
decoder_session = ort.InferenceSession("decoder_model_merged_q4f16.onnx")
|
23 |
+
embed_tokens_session = ort.InferenceSession("embed_tokens_q4f16.onnx")
|
24 |
+
|
25 |
+
def merge_input_ids_with_image_features(image_features, inputs_embeds, input_ids, attention_mask,pad_token_id,special_image_token_id):
|
26 |
+
num_images, num_image_patches, embed_dim = image_features.shape
|
27 |
+
batch_size, sequence_length = input_ids.shape
|
28 |
+
left_padding = not np.sum(input_ids[:, -1] == pad_token_id)
|
29 |
+
# 1. Create a mask to know where special image tokens are
|
30 |
+
special_image_token_mask = input_ids == special_image_token_id
|
31 |
+
num_special_image_tokens = np.sum(special_image_token_mask, axis=-1)
|
32 |
+
# Compute the maximum embed dimension
|
33 |
+
max_embed_dim = (num_special_image_tokens.max() * (num_image_patches - 1)) + sequence_length
|
34 |
+
batch_indices, non_image_indices = np.where(input_ids != special_image_token_id)
|
35 |
+
|
36 |
+
# 2. Compute the positions where text should be written
|
37 |
+
# Calculate new positions for text tokens in merged image-text sequence.
|
38 |
+
# `special_image_token_mask` identifies image tokens. Each image token will be replaced by `nb_text_tokens_per_images - 1` text tokens.
|
39 |
+
# `np.cumsum` computes how each image token shifts subsequent text token positions.
|
40 |
+
# - 1 to adjust for zero-based indexing, as `cumsum` inherently increases indices by one.
|
41 |
+
new_token_positions = np.cumsum((special_image_token_mask * (num_image_patches - 1) + 1), -1) - 1
|
42 |
+
nb_image_pad = max_embed_dim - 1 - new_token_positions[:, -1]
|
43 |
+
if left_padding:
|
44 |
+
new_token_positions += nb_image_pad[:, None] # offset for left padding
|
45 |
+
text_to_overwrite = new_token_positions[batch_indices, non_image_indices]
|
46 |
+
|
47 |
+
# 3. Create the full embedding, already padded to the maximum position
|
48 |
+
final_embedding = np.zeros((batch_size, max_embed_dim, embed_dim), dtype=np.float32)
|
49 |
+
final_attention_mask = np.zeros((batch_size, max_embed_dim), dtype=np.int64)
|
50 |
+
|
51 |
+
# 4. Fill the embeddings based on the mask. If we have ["hey" "<image>", "how", "are"]
|
52 |
+
# we need to index copy on [0, 577, 578, 579] for the text and [1:576] for the image features
|
53 |
+
final_embedding[batch_indices, text_to_overwrite] = inputs_embeds[batch_indices, non_image_indices]
|
54 |
+
final_attention_mask[batch_indices, text_to_overwrite] = attention_mask[batch_indices, non_image_indices]
|
55 |
+
# 5. Fill the embeddings corresponding to the images. Anything that is not `text_positions` needs filling (#29835)
|
56 |
+
image_to_overwrite = np.full((batch_size, max_embed_dim), True)
|
57 |
+
image_to_overwrite[batch_indices, text_to_overwrite] = False
|
58 |
+
image_to_overwrite &= image_to_overwrite.cumsum(-1) - 1 >= nb_image_pad[:, None]
|
59 |
+
|
60 |
+
final_embedding[image_to_overwrite] = image_features.reshape(-1, embed_dim)
|
61 |
+
final_attention_mask = np.logical_or(final_attention_mask, image_to_overwrite).astype(final_attention_mask.dtype)
|
62 |
+
position_ids = final_attention_mask.cumsum(axis=-1) - 1
|
63 |
+
position_ids = np.where(final_attention_mask == 0, 1, position_ids)
|
64 |
+
|
65 |
+
# 6. Mask out the embedding at padding positions, as we later use the past_key_value value to determine the non-attended tokens.
|
66 |
+
batch_indices, pad_indices = np.where(input_ids == pad_token_id)
|
67 |
+
indices_to_mask = new_token_positions[batch_indices, pad_indices]
|
68 |
+
final_embedding[batch_indices, indices_to_mask] = 0
|
69 |
+
|
70 |
+
return final_embedding, final_attention_mask, position_ids
|
71 |
+
|
72 |
+
# Load model and processor
|
73 |
+
|
74 |
+
def describe_image(image):
|
75 |
+
if(image.mode != 'RGB'):
|
76 |
+
image = image.convert('RGB')
|
77 |
+
conversation = [
|
78 |
+
{
|
79 |
+
"role": "system",
|
80 |
+
"content": "You are a helpful assistant who describes image."
|
81 |
+
},
|
82 |
+
{
|
83 |
+
"role": "user",
|
84 |
+
"content": [
|
85 |
+
{"type": "text", "text": "Describe this image in about 200 words and explain each and every element in full detail"},
|
86 |
+
{"type": "image"},
|
87 |
+
],
|
88 |
+
},
|
89 |
+
]
|
90 |
+
|
91 |
+
# Apply chat template
|
92 |
+
prompt = processor.apply_chat_template(conversation, add_generation_prompt=True)
|
93 |
+
|
94 |
+
# Preprocess the image and text
|
95 |
+
inputs = processor(images=image, text=prompt, return_tensors="np")
|
96 |
+
vision_input_name = vision_encoder_session.get_inputs()[0].name
|
97 |
+
vision_output_name = vision_encoder_session.get_outputs()[0].name
|
98 |
+
vision_features = vision_encoder_session.run([vision_output_name], {vision_input_name: inputs["pixel_values"]})[0]
|
99 |
+
|
100 |
+
# print('Total Time for Image Features Making ', time.time() - start)
|
101 |
+
|
102 |
+
# Tokens for the prompt
|
103 |
+
input_ids, attention_mask = inputs["input_ids"], inputs["attention_mask"]
|
104 |
+
|
105 |
+
# Prepare inputs
|
106 |
+
sequence_length = input_ids.shape[1]
|
107 |
+
batch_size = 1
|
108 |
+
num_layers = 24
|
109 |
+
head_dim = 64
|
110 |
+
num_heads = 16
|
111 |
+
pad_token_id = tokenizer.pad_token_id
|
112 |
+
past_sequence_length = 0 # Set to 0 for the initial pass
|
113 |
+
special_image_token_id = 151646
|
114 |
+
|
115 |
+
# Position IDs
|
116 |
+
position_ids = np.arange(sequence_length, dtype=np.int64).reshape(1, -1)
|
117 |
+
|
118 |
+
# Past Key Values
|
119 |
+
past_key_values = {
|
120 |
+
f"past_key_values.{i}.key": np.zeros((batch_size, num_heads, past_sequence_length, head_dim), dtype=np.float32)
|
121 |
+
for i in range(num_layers)
|
122 |
+
}
|
123 |
+
past_key_values.update({
|
124 |
+
f"past_key_values.{i}.value": np.zeros((batch_size, num_heads, past_sequence_length, head_dim), dtype=np.float32)
|
125 |
+
for i in range(num_layers)
|
126 |
+
})
|
127 |
+
|
128 |
+
# Run embed tokens
|
129 |
+
embed_input_name = embed_tokens_session.get_inputs()[0].name
|
130 |
+
embed_output_name = embed_tokens_session.get_outputs()[0].name
|
131 |
+
token_embeddings = embed_tokens_session.run([embed_output_name], {embed_input_name: input_ids})[0]
|
132 |
+
|
133 |
+
# Combine token embeddings and vision features
|
134 |
+
combined_embeddings, attention_mask, position_ids = merge_input_ids_with_image_features(vision_features, token_embeddings, input_ids, attention_mask,pad_token_id,special_image_token_id)
|
135 |
+
combined_len = combined_embeddings.shape[1]
|
136 |
+
|
137 |
+
# Combine all inputs
|
138 |
+
decoder_inputs = {
|
139 |
+
"attention_mask": attention_mask,
|
140 |
+
"position_ids": position_ids,
|
141 |
+
"inputs_embeds": combined_embeddings,
|
142 |
+
**past_key_values
|
143 |
+
}
|
144 |
+
|
145 |
+
# Print input shapes
|
146 |
+
for name, value in decoder_inputs.items():
|
147 |
+
print(f"{name} shape: {value.shape} dtype {value.dtype}")
|
148 |
+
|
149 |
+
# Run the decoder
|
150 |
+
decoder_input_names = [input.name for input in decoder_session.get_inputs()]
|
151 |
+
decoder_output_name = decoder_session.get_outputs()[0].name
|
152 |
+
names = [n.name for n in decoder_session.get_outputs()]
|
153 |
+
outputs = decoder_session.run(names, {name: decoder_inputs[name] for name in decoder_input_names if name in decoder_inputs})
|
154 |
+
|
155 |
+
# ... (previous code remains the same until after the decoder run)
|
156 |
+
# print(f"Outputs shape: {outputs[0].shape}")
|
157 |
+
# print(f"Outputs type: {outputs[0].dtype}")
|
158 |
+
|
159 |
+
# Process outputs (decode tokens to text)
|
160 |
+
generated_tokens = []
|
161 |
+
eos_token_id = tokenizer.eos_token_id
|
162 |
+
max_new_tokens = 2048
|
163 |
+
|
164 |
+
for i in range(max_new_tokens):
|
165 |
+
logits = outputs[0]
|
166 |
+
past_kv = outputs[1:]
|
167 |
+
logits_next_token = logits[:, -1]
|
168 |
+
token_id = np.argmax(logits_next_token)
|
169 |
+
|
170 |
+
if token_id == eos_token_id:
|
171 |
+
break
|
172 |
+
|
173 |
+
generated_tokens.append(token_id)
|
174 |
+
|
175 |
+
# Prepare input for next token generation
|
176 |
+
new_input_embeds = embed_tokens_session.run([embed_output_name], {embed_input_name: np.array([[token_id]])})[0]
|
177 |
+
|
178 |
+
past_key_values = {name.replace("present", "past_key_values"): value for name, value in zip(names[1:], outputs[1:])}
|
179 |
+
|
180 |
+
attention_mask = np.ones((1, combined_len + i + 1), dtype=np.int64)
|
181 |
+
position_ids = np.arange(combined_len + i + 1, dtype=np.int64).reshape(1, -1)[:, -1:]
|
182 |
+
|
183 |
+
decoder_inputs = {
|
184 |
+
"attention_mask": attention_mask,
|
185 |
+
"position_ids": position_ids,
|
186 |
+
"inputs_embeds": new_input_embeds,
|
187 |
+
**past_key_values
|
188 |
+
}
|
189 |
+
|
190 |
+
outputs = decoder_session.run(names, {name: decoder_inputs[name] for name in decoder_input_names if name in decoder_inputs})
|
191 |
+
|
192 |
+
# Convert to list of integers
|
193 |
+
token_ids = [int(token) for token in generated_tokens]
|
194 |
+
|
195 |
+
print(f"Generated token IDs: {token_ids}")
|
196 |
+
|
197 |
+
# Decode tokens one by one
|
198 |
+
decoded_tokens = [tokenizer.decode([token]) for token in token_ids]
|
199 |
+
print(f"Decoded tokens: {decoded_tokens}")
|
200 |
+
|
201 |
+
# Full decoded output
|
202 |
+
decoded_output = tokenizer.decode(token_ids, skip_special_tokens=True)
|
203 |
+
return decoded_output
|
204 |
+
|
205 |
+
# Streamlit app
|
206 |
+
st.title("Image Description Generator")
|
207 |
+
uploaded_image = st.file_uploader("Upload an image", type=["jpg", "jpeg", "png"])
|
208 |
+
if uploaded_image is not None:
|
209 |
+
image = Image.open(uploaded_image)
|
210 |
+
description = describe_image(image)
|
211 |
+
st.text_area("Description", description, height=300)
|
packages.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
wget
|
requirements.txt
ADDED
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
onnxruntime
|
2 |
+
onnx
|
3 |
+
gradio
|
4 |
+
Pillow
|
5 |
+
torch
|
6 |
+
transformers
|
7 |
+
numpy
|
8 |
+
flask
|
9 |
+
streamlit
|