Narayana02 commited on
Commit
8de60e6
·
verified ·
1 Parent(s): f7fb976

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +207 -210
app.py CHANGED
@@ -1,211 +1,208 @@
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)
 
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
+
29
+ special_image_token_mask = input_ids == special_image_token_id
30
+ num_special_image_tokens = np.sum(special_image_token_mask, axis=-1)
31
+
32
+ max_embed_dim = (num_special_image_tokens.max() * (num_image_patches - 1)) + sequence_length
33
+ batch_indices, non_image_indices = np.where(input_ids != special_image_token_id)
34
+
35
+ new_token_positions = np.cumsum((special_image_token_mask * (num_image_patches - 1) + 1), -1) - 1
36
+ nb_image_pad = max_embed_dim - 1 - new_token_positions[:, -1]
37
+ new_token_positions += nb_image_pad[:, None]
38
+
39
+ text_to_overwrite = new_token_positions[batch_indices, non_image_indices]
40
+
41
+ final_embedding = np.zeros((batch_size, max_embed_dim, embed_dim), dtype=np.float32)
42
+ final_attention_mask = np.zeros((batch_size, max_embed_dim), dtype=np.int64)
43
+
44
+ final_embedding[batch_indices, text_to_overwrite] = inputs_embeds[batch_indices, non_image_indices]
45
+ final_attention_mask[batch_indices, text_to_overwrite] = attention_mask[batch_indices, non_image_indices]
46
+
47
+ image_to_overwrite = np.full((batch_size, max_embed_dim), False)
48
+ image_to_overwrite[batch_indices, text_to_overwrite] = False
49
+ image_positions = np.where(np.logical_not(image_to_overwrite))
50
+
51
+ # Ensure proper reshaping
52
+ num_image_positions = len(image_positions[0])
53
+ assert num_image_positions <= image_features.size, "Mismatch in image feature positions and available features."
54
+
55
+ # Assign reshaped image features
56
+ reshaped_image_features = image_features.reshape(-1, embed_dim)[:num_image_positions]
57
+ final_embedding[image_positions] = reshaped_image_features
58
+ final_attention_mask = np.logical_or(final_attention_mask, image_to_overwrite).astype(final_attention_mask.dtype)
59
+
60
+ position_ids = final_attention_mask.cumsum(axis=-1) - 1
61
+ position_ids = np.where(final_attention_mask == 0, 1, position_ids)
62
+
63
+ batch_indices, pad_indices = np.where(input_ids == pad_token_id)
64
+ indices_to_mask = new_token_positions[batch_indices, pad_indices]
65
+ final_embedding[batch_indices, indices_to_mask] = 0
66
+
67
+ return final_embedding, final_attention_mask, position_ids
68
+
69
+ # Load model and processor
70
+
71
+ def describe_image(image):
72
+ if(image.mode != 'RGB'):
73
+ image = image.convert('RGB')
74
+ conversation = [
75
+ {
76
+ "role": "system",
77
+ "content": "You are a helpful assistant who describes image."
78
+ },
79
+ {
80
+ "role": "user",
81
+ "content": [
82
+ {"type": "text", "text": "Describe this image in about 200 words and explain each and every element in full detail"},
83
+ {"type": "image"},
84
+ ],
85
+ },
86
+ ]
87
+
88
+ # Apply chat template
89
+ prompt = processor.apply_chat_template(conversation, add_generation_prompt=True)
90
+
91
+ # Preprocess the image and text
92
+ inputs = processor(images=image, text=prompt, return_tensors="np")
93
+ vision_input_name = vision_encoder_session.get_inputs()[0].name
94
+ vision_output_name = vision_encoder_session.get_outputs()[0].name
95
+ vision_features = vision_encoder_session.run([vision_output_name], {vision_input_name: inputs["pixel_values"]})[0]
96
+
97
+ # print('Total Time for Image Features Making ', time.time() - start)
98
+
99
+ # Tokens for the prompt
100
+ input_ids, attention_mask = inputs["input_ids"], inputs["attention_mask"]
101
+
102
+ # Prepare inputs
103
+ sequence_length = input_ids.shape[1]
104
+ batch_size = 1
105
+ num_layers = 24
106
+ head_dim = 64
107
+ num_heads = 16
108
+ pad_token_id = tokenizer.pad_token_id
109
+ past_sequence_length = 0 # Set to 0 for the initial pass
110
+ special_image_token_id = 151646
111
+
112
+ # Position IDs
113
+ position_ids = np.arange(sequence_length, dtype=np.int64).reshape(1, -1)
114
+
115
+ # Past Key Values
116
+ past_key_values = {
117
+ f"past_key_values.{i}.key": np.zeros((batch_size, num_heads, past_sequence_length, head_dim), dtype=np.float32)
118
+ for i in range(num_layers)
119
+ }
120
+ past_key_values.update({
121
+ f"past_key_values.{i}.value": np.zeros((batch_size, num_heads, past_sequence_length, head_dim), dtype=np.float32)
122
+ for i in range(num_layers)
123
+ })
124
+
125
+ # Run embed tokens
126
+ embed_input_name = embed_tokens_session.get_inputs()[0].name
127
+ embed_output_name = embed_tokens_session.get_outputs()[0].name
128
+ token_embeddings = embed_tokens_session.run([embed_output_name], {embed_input_name: input_ids})[0]
129
+
130
+ # Combine token embeddings and vision features
131
+ 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)
132
+ combined_len = combined_embeddings.shape[1]
133
+
134
+ # Combine all inputs
135
+ decoder_inputs = {
136
+ "attention_mask": attention_mask,
137
+ "position_ids": position_ids,
138
+ "inputs_embeds": combined_embeddings,
139
+ **past_key_values
140
+ }
141
+
142
+ # Print input shapes
143
+ for name, value in decoder_inputs.items():
144
+ print(f"{name} shape: {value.shape} dtype {value.dtype}")
145
+
146
+ # Run the decoder
147
+ decoder_input_names = [input.name for input in decoder_session.get_inputs()]
148
+ decoder_output_name = decoder_session.get_outputs()[0].name
149
+ names = [n.name for n in decoder_session.get_outputs()]
150
+ outputs = decoder_session.run(names, {name: decoder_inputs[name] for name in decoder_input_names if name in decoder_inputs})
151
+
152
+ # ... (previous code remains the same until after the decoder run)
153
+ # print(f"Outputs shape: {outputs[0].shape}")
154
+ # print(f"Outputs type: {outputs[0].dtype}")
155
+
156
+ # Process outputs (decode tokens to text)
157
+ generated_tokens = []
158
+ eos_token_id = tokenizer.eos_token_id
159
+ max_new_tokens = 2048
160
+
161
+ for i in range(max_new_tokens):
162
+ logits = outputs[0]
163
+ past_kv = outputs[1:]
164
+ logits_next_token = logits[:, -1]
165
+ token_id = np.argmax(logits_next_token)
166
+
167
+ if token_id == eos_token_id:
168
+ break
169
+
170
+ generated_tokens.append(token_id)
171
+
172
+ # Prepare input for next token generation
173
+ new_input_embeds = embed_tokens_session.run([embed_output_name], {embed_input_name: np.array([[token_id]])})[0]
174
+
175
+ past_key_values = {name.replace("present", "past_key_values"): value for name, value in zip(names[1:], outputs[1:])}
176
+
177
+ attention_mask = np.ones((1, combined_len + i + 1), dtype=np.int64)
178
+ position_ids = np.arange(combined_len + i + 1, dtype=np.int64).reshape(1, -1)[:, -1:]
179
+
180
+ decoder_inputs = {
181
+ "attention_mask": attention_mask,
182
+ "position_ids": position_ids,
183
+ "inputs_embeds": new_input_embeds,
184
+ **past_key_values
185
+ }
186
+
187
+ outputs = decoder_session.run(names, {name: decoder_inputs[name] for name in decoder_input_names if name in decoder_inputs})
188
+
189
+ # Convert to list of integers
190
+ token_ids = [int(token) for token in generated_tokens]
191
+
192
+ print(f"Generated token IDs: {token_ids}")
193
+
194
+ # Decode tokens one by one
195
+ decoded_tokens = [tokenizer.decode([token]) for token in token_ids]
196
+ print(f"Decoded tokens: {decoded_tokens}")
197
+
198
+ # Full decoded output
199
+ decoded_output = tokenizer.decode(token_ids, skip_special_tokens=True)
200
+ return decoded_output
201
+
202
+ # Streamlit app
203
+ st.title("Image Description Generator")
204
+ uploaded_image = st.file_uploader("Upload an image", type=["jpg", "jpeg", "png"])
205
+ if uploaded_image is not None:
206
+ image = Image.open(uploaded_image)
207
+ description = describe_image(image)
 
 
 
208
  st.text_area("Description", description, height=300)