Spaces:
Paused
Paused
add reference code from vllm
Browse files
app.py
CHANGED
@@ -11,100 +11,192 @@ from mistral_common.protocol.instruct.messages import UserMessage, TextChunk, Im
|
|
11 |
from mistral_common.protocol.instruct.request import ChatCompletionRequest
|
12 |
from mistral_common.tokens.tokenizers.mistral import MistralTokenizer
|
13 |
import spaces
|
|
|
|
|
14 |
|
15 |
-
title = "#
|
16 |
description = """
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
### How it works:
|
22 |
-
1. Upload two images
|
23 |
-
2. The Pixtral vision encoder processes both images
|
24 |
-
3. The cosine similarity between the embeddings is calculated
|
25 |
-
4. The similarity score is displayed (1.0 means identical, 0.0 means completely different)
|
26 |
-
|
27 |
-
### Note:
|
28 |
-
This is a demonstration of the vision encoder capabilities and does not use the full Pixtral model for text generation.
|
29 |
|
30 |
### Join us :
|
31 |
🌟TeamTonic🌟 is always making cool demos! Join our active builder's 🛠️community 👻 [![Join us on Discord](https://img.shields.io/discord/1109943800132010065?label=Discord&logo=discord&style=flat-square)](https://discord.gg/qdfnvSPcqP) On 🤗Huggingface:[MultiTransformer](https://huggingface.co/MultiTransformer) On 🌐Github: [Tonic-AI](https://github.com/tonic-ai) & contribute to🌟 [Build Tonic](https://git.tonic-ai.com/contribute)🤗Big thanks to Yuvi Sharma and all the folks at huggingface for the community grant 🤗
|
32 |
"""
|
33 |
|
34 |
-
|
35 |
-
model_path = snapshot_download(repo_id="mistral-community/pixtral-12b-240910")
|
36 |
-
|
37 |
-
# Load model parameters and tokenizer configuration
|
38 |
with open(f'{model_path}/params.json', 'r') as f:
|
39 |
params = json.load(f)
|
40 |
-
|
41 |
with open(f'{model_path}/tekken.json', 'r') as f:
|
42 |
tokenizer_config = json.load(f)
|
43 |
|
44 |
-
class
|
45 |
-
def __init__(self,
|
46 |
super().__init__()
|
47 |
-
self.
|
48 |
-
self.
|
49 |
-
|
50 |
-
def forward(self, x):
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
|
|
|
|
58 |
h = torch.arange(height, device=freqs.device)
|
59 |
w = torch.arange(width, device=freqs.device)
|
60 |
|
61 |
freqs_h = torch.outer(h, freqs[::2]).float()
|
62 |
freqs_w = torch.outer(w, freqs[1::2]).float()
|
63 |
-
freqs_2d = torch.cat(
|
64 |
-
|
65 |
-
|
66 |
-
|
|
|
|
|
|
|
67 |
return torch.polar(torch.ones_like(freqs_2d), freqs_2d)
|
68 |
|
69 |
-
|
70 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
71 |
super().__init__()
|
72 |
-
self.
|
73 |
-
self.
|
74 |
-
self.
|
75 |
|
76 |
-
def forward(self, x
|
77 |
-
|
78 |
-
return freqs_cis.to(x.device)
|
79 |
|
80 |
-
class
|
81 |
-
def __init__(self,
|
82 |
super().__init__()
|
83 |
-
self.
|
84 |
-
self.
|
85 |
-
self.
|
86 |
-
self.
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
93 |
x = x.flatten(2).transpose(1, 2)
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
|
|
99 |
return x
|
100 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
101 |
class PixtralModel(nn.Module):
|
102 |
def __init__(self, params):
|
103 |
super().__init__()
|
104 |
-
self.vision_encoder =
|
105 |
-
|
106 |
-
|
107 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
108 |
|
109 |
def load_model(params, model_path):
|
110 |
model = PixtralModel(params)
|
@@ -117,8 +209,8 @@ def load_model(params, model_path):
|
|
117 |
model.eval()
|
118 |
return model
|
119 |
|
120 |
-
# Initialize the model
|
121 |
model = load_model(params, model_path)
|
|
|
122 |
|
123 |
def preprocess_image(image):
|
124 |
image = image.convert('RGB')
|
@@ -126,6 +218,41 @@ def preprocess_image(image):
|
|
126 |
image_tensor = torch.tensor(np.array(image)).permute(2, 0, 1).unsqueeze(0).float() / 255.0
|
127 |
return image_tensor
|
128 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
129 |
@spaces.GPU
|
130 |
def calculate_similarity(image1, image2):
|
131 |
# Preprocess images
|
@@ -144,8 +271,7 @@ def calculate_similarity(image1, image2):
|
|
144 |
|
145 |
return similarity
|
146 |
|
147 |
-
|
148 |
-
with gr.Blocks() as demo:
|
149 |
gr.Markdown(title)
|
150 |
gr.Markdown("## Model Details")
|
151 |
gr.Markdown(f"- Vision Encoder Hidden Size: {params['vision_encoder']['hidden_size']}")
|
@@ -155,135 +281,43 @@ with gr.Blocks() as demo:
|
|
155 |
gr.Markdown(f"- Patch Size: {params['vision_encoder']['patch_size']}x{params['vision_encoder']['patch_size']}")
|
156 |
gr.Markdown("## How it works")
|
157 |
gr.Markdown("1. The image is processed by a Vision Encoder using 2D ROPE (Rotary Position Embedding).")
|
158 |
-
gr.Markdown("2. The encoder uses
|
159 |
-
gr.Markdown("3. The encoded image
|
160 |
|
161 |
gr.Markdown(description)
|
162 |
|
163 |
-
with gr.
|
164 |
-
|
165 |
-
|
166 |
-
|
167 |
-
|
168 |
-
|
169 |
-
|
170 |
-
|
171 |
-
|
172 |
-
|
173 |
-
|
174 |
-
|
175 |
-
|
176 |
-
|
177 |
-
|
178 |
-
|
179 |
-
|
180 |
-
|
181 |
-
# import torch.nn.functional as F
|
182 |
-
# from safetensors import safe_open
|
183 |
-
# import json
|
184 |
-
# import gradio as gr
|
185 |
-
# from PIL import Image
|
186 |
-
# import numpy as np
|
187 |
-
# from huggingface_hub import snapshot_download
|
188 |
-
# from mistral_common.protocol.instruct.messages import UserMessage, TextChunk, ImageChunk
|
189 |
-
# from mistral_common.protocol.instruct.request import ChatCompletionRequest
|
190 |
-
# from mistral_common.tokens.tokenizers.mistral import MistralTokenizer
|
191 |
-
# import spaces
|
192 |
-
|
193 |
-
# title = "# **WIP / DEMO** 🙋🏻♂️Welcome to Tonic's Pixtral Image-to-Text Model Demo"
|
194 |
-
|
195 |
-
|
196 |
-
# # Download model files
|
197 |
-
# model_path = snapshot_download(repo_id="mistral-community/pixtral-12b-240910")
|
198 |
-
|
199 |
-
# # Load model parameters and tokenizer configuration
|
200 |
-
# with open(f'{model_path}/params.json', 'r') as f:
|
201 |
-
# params = json.load(f)
|
202 |
-
|
203 |
-
# with open(f'{model_path}/tekken.json', 'r') as f:
|
204 |
-
# tokenizer_config = json.load(f)
|
205 |
-
|
206 |
-
# class PixtralModel(nn.Module):
|
207 |
-
# def __init__(self, params):
|
208 |
-
# super().__init__()
|
209 |
-
# self.vision_encoder = VisionEncoder(params['vision_encoder'])
|
210 |
-
# # Add text generation components here
|
211 |
-
|
212 |
-
# def forward(self, image):
|
213 |
-
# vision_output = self.vision_encoder(image)
|
214 |
-
# # Add text generation logic here
|
215 |
-
# return vision_output
|
216 |
-
|
217 |
-
# def load_model(params, model_path):
|
218 |
-
# model = PixtralModel(params)
|
219 |
-
|
220 |
-
# with safe_open(f'{model_path}/consolidated.safetensors', framework="pt", device="cpu") as f:
|
221 |
-
# for name, param in model.named_parameters():
|
222 |
-
# if name in f.keys():
|
223 |
-
# param.data = f.get_tensor(name)
|
224 |
-
|
225 |
-
# model.eval()
|
226 |
-
# return model
|
227 |
-
|
228 |
-
# # Initialize the model
|
229 |
-
# model = load_model(params, model_path)
|
230 |
-
# tokenizer = MistralTokenizer.from_model("pixtral")
|
231 |
-
|
232 |
-
# @spaces.GPU
|
233 |
-
# def process_image_and_text(image, prompt):
|
234 |
-
# # Prepare the image
|
235 |
-
# image = image.convert('RGB')
|
236 |
-
# image = image.resize((params['vision_encoder']['image_size'], params['vision_encoder']['image_size']))
|
237 |
-
# image_tensor = torch.tensor(np.array(image)).permute(2, 0, 1).unsqueeze(0).float() / 255.0
|
238 |
-
# image_tensor = image_tensor.cuda()
|
239 |
-
|
240 |
-
# # Tokenize the input
|
241 |
-
# tokenized = tokenizer.encode_chat_completion(
|
242 |
-
# ChatCompletionRequest(
|
243 |
-
# messages=[
|
244 |
-
# UserMessage(
|
245 |
-
# content=[
|
246 |
-
# TextChunk(text=prompt),
|
247 |
-
# ImageChunk(image=image),
|
248 |
-
# ]
|
249 |
-
# )
|
250 |
-
# ],
|
251 |
-
# model="pixtral",
|
252 |
-
# )
|
253 |
-
# )
|
254 |
-
# tokens, text, images = tokenized.tokens, tokenized.text, tokenized.images
|
255 |
-
|
256 |
-
# # Process the image and generate text
|
257 |
-
# with torch.no_grad():
|
258 |
-
# model.cuda()
|
259 |
-
# vision_output = model(image_tensor)
|
260 |
-
# model.cpu()
|
261 |
-
# generated_text = f"Generated text based on the image and prompt: {prompt}"
|
262 |
-
|
263 |
-
# return generated_text, len(tokens), len(images)
|
264 |
-
|
265 |
-
# # Gradio interface
|
266 |
-
# with gr.Blocks() as demo:
|
267 |
-
# gr.Markdown(title)
|
268 |
-
|
269 |
-
|
270 |
-
# gr.Markdown(description)
|
271 |
-
# with gr.Row():
|
272 |
-
# with gr.Column(scale=1):
|
273 |
-
# input_image = gr.Image(type="pil")
|
274 |
-
# input_prompt = gr.Textbox(label="Prompt")
|
275 |
-
# submit_btn = gr.Button("Generate Text")
|
276 |
|
277 |
-
|
278 |
-
|
279 |
-
|
280 |
-
|
281 |
-
|
282 |
-
|
283 |
-
|
284 |
-
|
285 |
-
|
286 |
-
|
287 |
-
|
288 |
-
|
289 |
-
|
|
|
|
|
|
|
|
11 |
from mistral_common.protocol.instruct.request import ChatCompletionRequest
|
12 |
from mistral_common.tokens.tokenizers.mistral import MistralTokenizer
|
13 |
import spaces
|
14 |
+
import math
|
15 |
+
from typing import List, Optional, Tuple
|
16 |
|
17 |
+
title = "# 🙋🏻♂️Welcome to Tonic's Pixtral Model Demo"
|
18 |
description = """
|
19 |
+
This demo showcases two capabilities of the Pixtral model:
|
20 |
+
1. Image-to-Text Generation
|
21 |
+
2. Image Similarity Comparison
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
22 |
|
23 |
### Join us :
|
24 |
🌟TeamTonic🌟 is always making cool demos! Join our active builder's 🛠️community 👻 [![Join us on Discord](https://img.shields.io/discord/1109943800132010065?label=Discord&logo=discord&style=flat-square)](https://discord.gg/qdfnvSPcqP) On 🤗Huggingface:[MultiTransformer](https://huggingface.co/MultiTransformer) On 🌐Github: [Tonic-AI](https://github.com/tonic-ai) & contribute to🌟 [Build Tonic](https://git.tonic-ai.com/contribute)🤗Big thanks to Yuvi Sharma and all the folks at huggingface for the community grant 🤗
|
25 |
"""
|
26 |
|
27 |
+
model_path = snapshot_download(repo_id="mistralai/Pixtral-12B-2409")
|
|
|
|
|
|
|
28 |
with open(f'{model_path}/params.json', 'r') as f:
|
29 |
params = json.load(f)
|
|
|
30 |
with open(f'{model_path}/tekken.json', 'r') as f:
|
31 |
tokenizer_config = json.load(f)
|
32 |
|
33 |
+
class RMSNorm(nn.Module):
|
34 |
+
def __init__(self, dim: int, eps: float = 1e-5):
|
35 |
super().__init__()
|
36 |
+
self.eps = eps
|
37 |
+
self.weight = nn.Parameter(torch.ones(dim))
|
38 |
+
|
39 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
40 |
+
return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps) * self.weight
|
41 |
+
|
42 |
+
def precompute_freqs_cis_2d(
|
43 |
+
dim: int,
|
44 |
+
height: int,
|
45 |
+
width: int,
|
46 |
+
theta: float,
|
47 |
+
) -> torch.Tensor:
|
48 |
+
freqs = 1.0 / (theta**(torch.arange(0, dim, 2).float() / dim))
|
49 |
h = torch.arange(height, device=freqs.device)
|
50 |
w = torch.arange(width, device=freqs.device)
|
51 |
|
52 |
freqs_h = torch.outer(h, freqs[::2]).float()
|
53 |
freqs_w = torch.outer(w, freqs[1::2]).float()
|
54 |
+
freqs_2d = torch.cat(
|
55 |
+
[
|
56 |
+
freqs_h[:, None, :].repeat(1, width, 1),
|
57 |
+
freqs_w[None, :, :].repeat(height, 1, 1),
|
58 |
+
],
|
59 |
+
dim=-1,
|
60 |
+
)
|
61 |
return torch.polar(torch.ones_like(freqs_2d), freqs_2d)
|
62 |
|
63 |
+
def apply_rotary_emb_vit(
|
64 |
+
xq: torch.Tensor,
|
65 |
+
xk: torch.Tensor,
|
66 |
+
freqs_cis: torch.Tensor,
|
67 |
+
) -> Tuple[torch.Tensor, torch.Tensor]:
|
68 |
+
xq_ = torch.view_as_complex(xq.float().reshape(*xq.shape[:-1], -1, 2))
|
69 |
+
xk_ = torch.view_as_complex(xk.float().reshape(*xk.shape[:-1], -1, 2))
|
70 |
+
freqs_cis = freqs_cis.view(*freqs_cis.shape[:2], 1, freqs_cis.shape[-1])
|
71 |
+
xq_out = torch.view_as_real(xq_ * freqs_cis).flatten(3)
|
72 |
+
xk_out = torch.view_as_real(xk_ * freqs_cis).flatten(3)
|
73 |
+
return xq_out.type_as(xq), xk_out.type_as(xk)
|
74 |
+
|
75 |
+
class Attention(nn.Module):
|
76 |
+
def __init__(self, args):
|
77 |
+
super().__init__()
|
78 |
+
self.n_heads = args['num_attention_heads']
|
79 |
+
self.head_dim = args['hidden_size'] // args['num_attention_heads']
|
80 |
+
|
81 |
+
self.wq = nn.Linear(args['hidden_size'], args['hidden_size'], bias=False)
|
82 |
+
self.wk = nn.Linear(args['hidden_size'], args['hidden_size'], bias=False)
|
83 |
+
self.wv = nn.Linear(args['hidden_size'], args['hidden_size'], bias=False)
|
84 |
+
self.wo = nn.Linear(args['hidden_size'], args['hidden_size'], bias=False)
|
85 |
+
|
86 |
+
def forward(self, x: torch.Tensor, freqs_cis: torch.Tensor) -> torch.Tensor:
|
87 |
+
batch, patches, _ = x.shape
|
88 |
+
|
89 |
+
q, k, v = self.wq(x), self.wk(x), self.wv(x)
|
90 |
+
q = q.reshape(batch, patches, self.n_heads, self.head_dim)
|
91 |
+
k = k.reshape(batch, patches, self.n_heads, self.head_dim)
|
92 |
+
v = v.reshape(batch, patches, self.n_heads, self.head_dim)
|
93 |
+
|
94 |
+
q, k = apply_rotary_emb_vit(q, k, freqs_cis=freqs_cis)
|
95 |
+
|
96 |
+
scores = torch.matmul(q, k.transpose(-1, -2)) / math.sqrt(self.head_dim)
|
97 |
+
attn = F.softmax(scores, dim=-1)
|
98 |
+
out = torch.matmul(attn, v)
|
99 |
+
out = out.reshape(batch, patches, self.n_heads * self.head_dim)
|
100 |
+
return self.wo(out)
|
101 |
+
|
102 |
+
class FeedForward(nn.Module):
|
103 |
+
def __init__(self, args):
|
104 |
super().__init__()
|
105 |
+
self.w1 = nn.Linear(args['hidden_size'], args['intermediate_size'], bias=False)
|
106 |
+
self.w2 = nn.Linear(args['intermediate_size'], args['hidden_size'], bias=False)
|
107 |
+
self.w3 = nn.Linear(args['hidden_size'], args['intermediate_size'], bias=False)
|
108 |
|
109 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
110 |
+
return self.w2(F.silu(self.w1(x)) * self.w3(x))
|
|
|
111 |
|
112 |
+
class TransformerBlock(nn.Module):
|
113 |
+
def __init__(self, args):
|
114 |
super().__init__()
|
115 |
+
self.attention = Attention(args)
|
116 |
+
self.feed_forward = FeedForward(args)
|
117 |
+
self.attention_norm = RMSNorm(args['hidden_size'], eps=1e-5)
|
118 |
+
self.ffn_norm = RMSNorm(args['hidden_size'], eps=1e-5)
|
119 |
+
|
120 |
+
def forward(self, x: torch.Tensor, freqs_cis: torch.Tensor) -> torch.Tensor:
|
121 |
+
r = self.attention.forward(self.attention_norm(x), freqs_cis=freqs_cis)
|
122 |
+
h = x + r
|
123 |
+
r = self.feed_forward.forward(self.ffn_norm(h))
|
124 |
+
out = h + r
|
125 |
+
return out
|
126 |
+
|
127 |
+
class VisionTransformer(nn.Module):
|
128 |
+
def __init__(self, args):
|
129 |
+
super().__init__()
|
130 |
+
self.args = args
|
131 |
+
self.patch_conv = nn.Conv2d(
|
132 |
+
in_channels=args['num_channels'],
|
133 |
+
out_channels=args['hidden_size'],
|
134 |
+
kernel_size=args['patch_size'],
|
135 |
+
stride=args['patch_size'],
|
136 |
+
bias=False,
|
137 |
+
)
|
138 |
+
self.ln_pre = RMSNorm(args['hidden_size'], eps=1e-5)
|
139 |
+
self.transformer = nn.ModuleList([TransformerBlock(args) for _ in range(args['num_hidden_layers'])])
|
140 |
+
|
141 |
+
self.max_patches_per_side = args['image_size'] // args['patch_size']
|
142 |
+
self._freqs_cis = None
|
143 |
+
|
144 |
+
@property
|
145 |
+
def freqs_cis(self) -> torch.Tensor:
|
146 |
+
if self._freqs_cis is None:
|
147 |
+
self._freqs_cis = precompute_freqs_cis_2d(
|
148 |
+
dim=self.args['hidden_size'] // self.args['num_attention_heads'],
|
149 |
+
height=self.max_patches_per_side,
|
150 |
+
width=self.max_patches_per_side,
|
151 |
+
theta=self.args['rope_theta'],
|
152 |
+
)
|
153 |
+
return self._freqs_cis.to(self.patch_conv.weight.device)
|
154 |
+
|
155 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
156 |
+
x = self.patch_conv(x)
|
157 |
x = x.flatten(2).transpose(1, 2)
|
158 |
+
x = self.ln_pre(x)
|
159 |
+
|
160 |
+
freqs_cis = self.freqs_cis
|
161 |
+
for layer in self.transformer:
|
162 |
+
x = layer(x, freqs_cis=freqs_cis)
|
163 |
+
|
164 |
return x
|
165 |
|
166 |
+
class VisionLanguageAdapter(nn.Module):
|
167 |
+
def __init__(self, args, dim: int):
|
168 |
+
super().__init__()
|
169 |
+
self.w_in = nn.Linear(args['hidden_size'], dim, bias=True)
|
170 |
+
self.gelu = nn.GELU()
|
171 |
+
self.w_out = nn.Linear(dim, dim, bias=True)
|
172 |
+
|
173 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
174 |
+
return self.w_out(self.gelu(self.w_in(x)))
|
175 |
+
|
176 |
class PixtralModel(nn.Module):
|
177 |
def __init__(self, params):
|
178 |
super().__init__()
|
179 |
+
self.vision_encoder = VisionTransformer(params['vision_encoder'])
|
180 |
+
self.vision_language_adapter = VisionLanguageAdapter(params['vision_encoder'], params['text_config']['hidden_size'])
|
181 |
+
self.language_model = nn.TransformerDecoder(
|
182 |
+
nn.TransformerDecoderLayer(d_model=params['text_config']['hidden_size'],
|
183 |
+
nhead=params['text_config']['num_attention_heads'],
|
184 |
+
dim_feedforward=params['text_config']['intermediate_size']),
|
185 |
+
num_layers=params['text_config']['num_hidden_layers']
|
186 |
+
)
|
187 |
+
self.lm_head = nn.Linear(params['text_config']['hidden_size'], params['text_config']['vocab_size'], bias=False)
|
188 |
+
|
189 |
+
def forward(self, image, input_ids=None):
|
190 |
+
vision_output = self.vision_encoder(image)
|
191 |
+
vision_output = self.vision_language_adapter(vision_output)
|
192 |
+
|
193 |
+
if input_ids is not None:
|
194 |
+
tgt = self.lm_head.weight[input_ids].transpose(0, 1)
|
195 |
+
output = self.language_model(tgt, vision_output)
|
196 |
+
logits = self.lm_head(output)
|
197 |
+
return logits
|
198 |
+
else:
|
199 |
+
return vision_output
|
200 |
|
201 |
def load_model(params, model_path):
|
202 |
model = PixtralModel(params)
|
|
|
209 |
model.eval()
|
210 |
return model
|
211 |
|
|
|
212 |
model = load_model(params, model_path)
|
213 |
+
tokenizer = MistralTokenizer.from_model("pixtral")
|
214 |
|
215 |
def preprocess_image(image):
|
216 |
image = image.convert('RGB')
|
|
|
218 |
image_tensor = torch.tensor(np.array(image)).permute(2, 0, 1).unsqueeze(0).float() / 255.0
|
219 |
return image_tensor
|
220 |
|
221 |
+
@spaces.GPU
|
222 |
+
def generate_text(image, prompt):
|
223 |
+
image_tensor = preprocess_image(image).cuda()
|
224 |
+
|
225 |
+
tokenized = tokenizer.encode_chat_completion(
|
226 |
+
ChatCompletionRequest(
|
227 |
+
messages=[
|
228 |
+
UserMessage(
|
229 |
+
content=[
|
230 |
+
TextChunk(text=prompt),
|
231 |
+
ImageChunk(image=image),
|
232 |
+
]
|
233 |
+
)
|
234 |
+
],
|
235 |
+
model="pixtral",
|
236 |
+
)
|
237 |
+
)
|
238 |
+
input_ids = torch.tensor(tokenized.tokens).unsqueeze(0).cuda()
|
239 |
+
|
240 |
+
# Generate text
|
241 |
+
with torch.no_grad():
|
242 |
+
model.cuda()
|
243 |
+
max_length = 100 # add slider
|
244 |
+
for _ in range(max_length):
|
245 |
+
logits = model(image_tensor, input_ids)
|
246 |
+
next_token_logits = logits[0, -1, :]
|
247 |
+
next_token = torch.argmax(next_token_logits, dim=-1)
|
248 |
+
input_ids = torch.cat([input_ids, next_token.unsqueeze(0).unsqueeze(0)], dim=-1)
|
249 |
+
if next_token.item() == tokenizer.eos_token_id:
|
250 |
+
break
|
251 |
+
model.cpu()
|
252 |
+
|
253 |
+
generated_text = tokenizer.decode(input_ids[0].tolist())
|
254 |
+
return generated_text, len(input_ids[0]), 1 # 1 image processed
|
255 |
+
|
256 |
@spaces.GPU
|
257 |
def calculate_similarity(image1, image2):
|
258 |
# Preprocess images
|
|
|
271 |
|
272 |
return similarity
|
273 |
|
274 |
+
with gr.Blocks(theme=gr.themes.Base()) as demo:
|
|
|
275 |
gr.Markdown(title)
|
276 |
gr.Markdown("## Model Details")
|
277 |
gr.Markdown(f"- Vision Encoder Hidden Size: {params['vision_encoder']['hidden_size']}")
|
|
|
281 |
gr.Markdown(f"- Patch Size: {params['vision_encoder']['patch_size']}x{params['vision_encoder']['patch_size']}")
|
282 |
gr.Markdown("## How it works")
|
283 |
gr.Markdown("1. The image is processed by a Vision Encoder using 2D ROPE (Rotary Position Embedding).")
|
284 |
+
gr.Markdown("2. The encoder uses SiLU activation in its feed-forward layers.")
|
285 |
+
gr.Markdown("3. The encoded image is used for text generation or similarity comparison.")
|
286 |
|
287 |
gr.Markdown(description)
|
288 |
|
289 |
+
with gr.Tabs():
|
290 |
+
with gr.TabItem("Image-to-Text Generation"):
|
291 |
+
with gr.Row():
|
292 |
+
with gr.Column():
|
293 |
+
input_image = gr.Image(type="pil", label="Input Image")
|
294 |
+
input_prompt = gr.Textbox(label="Prompt")
|
295 |
+
submit_btn = gr.Button("Generate Text")
|
296 |
+
|
297 |
+
with gr.Column():
|
298 |
+
output_text = gr.Textbox(label="Generated Text")
|
299 |
+
token_count = gr.Number(label="Number of Tokens")
|
300 |
+
image_count = gr.Number(label="Number of Images Processed")
|
301 |
+
|
302 |
+
submit_btn.click(
|
303 |
+
fn=generate_text,
|
304 |
+
inputs=[input_image, input_prompt],
|
305 |
+
outputs=[output_text, token_count, image_count]
|
306 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
307 |
|
308 |
+
with gr.TabItem("Image Similarity Comparison"):
|
309 |
+
with gr.Row():
|
310 |
+
image1_input = gr.Image(type="pil", label="Image 1")
|
311 |
+
image2_input = gr.Image(type="pil", label="Image 2")
|
312 |
+
|
313 |
+
similarity_btn = gr.Button("📸🌬️Calculate Similarity")
|
314 |
+
similarity_output = gr.Number(label="Similarity Score (0.0 to 1.0)")
|
315 |
+
|
316 |
+
similarity_btn.click(
|
317 |
+
fn=calculate_similarity,
|
318 |
+
inputs=[image1_input, image2_input],
|
319 |
+
outputs=[similarity_output]
|
320 |
+
)
|
321 |
+
|
322 |
+
if __name__ == "__main__":
|
323 |
+
demo.launch()
|