Tonic commited on
Commit
6408837
·
unverified ·
1 Parent(s): cbd9440

add reference code from vllm

Browse files
Files changed (1) hide show
  1. app.py +229 -195
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 = "# **WIP / DEMO** 🙋🏻‍♂️Welcome to Tonic's Pixtral Image-Similarity Model Demo"
16
  description = """
17
- Upload two images to compare their similarity based on the embeddings produced by the Pixtral model.
18
- This demo uses the vision encoder part of the Pixtral model to generate embeddings and then calculates
19
- the cosine similarity between them.
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
- # Download model files
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 GELU(nn.Module):
45
- def __init__(self, dim_in, dim_out, approximate='none', bias=True):
46
  super().__init__()
47
- self.linear = nn.Linear(dim_in, dim_out, bias=bias)
48
- self.approximate = approximate
49
-
50
- def forward(self, x):
51
- if self.approximate == 'tanh':
52
- return 0.5 * x * (1 + torch.tanh(np.sqrt(2 / np.pi) * (x + 0.044715 * torch.pow(x, 3))))
53
- else:
54
- return F.gelu(self.linear(x))
55
-
56
- def precompute_freqs_cis_2d(dim: int, height: int, width: int, theta: float) -> torch.Tensor:
57
- freqs = 1.0 / (theta ** (torch.arange(0, dim, 2).float() / dim))
 
 
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
- freqs_h[:, None, :].repeat(1, width, 1),
65
- freqs_w[None, :, :].repeat(height, 1, 1),
66
- ], dim=-1)
 
 
 
67
  return torch.polar(torch.ones_like(freqs_2d), freqs_2d)
68
 
69
- class Rope2D(nn.Module):
70
- def __init__(self, dim, max_position_embeddings=1024, base=10000):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
71
  super().__init__()
72
- self.dim = dim
73
- self.max_position_embeddings = max_position_embeddings
74
- self.base = base
75
 
76
- def forward(self, x, height, width):
77
- freqs_cis = precompute_freqs_cis_2d(self.dim, height, width, self.base)
78
- return freqs_cis.to(x.device)
79
 
80
- class VisionEncoder(nn.Module):
81
- def __init__(self, config):
82
  super().__init__()
83
- self.config = config
84
- self.embed = nn.Conv2d(config['num_channels'], config['hidden_size'], kernel_size=config['patch_size'], stride=config['patch_size'])
85
- self.rope = Rope2D(config['hidden_size'] // config['num_attention_heads'], base=config['rope_theta'])
86
- self.layers = nn.ModuleList([nn.TransformerEncoderLayer(d_model=config['hidden_size'], nhead=config['num_attention_heads'], dim_feedforward=config['intermediate_size']) for _ in range(config['num_hidden_layers'])])
87
- self.norm = nn.LayerNorm(config['hidden_size'])
88
- self.gelu = GELU(config['hidden_size'], config['hidden_size'])
89
-
90
- def forward(self, pixel_values):
91
- x = self.embed(pixel_values)
92
- b, c, h, w = x.shape
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93
  x = x.flatten(2).transpose(1, 2)
94
- freqs_cis = self.rope(x, h, w)
95
- for layer in self.layers:
96
- x = layer(x)
97
- x = self.norm(x)
98
- x = self.gelu(x)
 
99
  return x
100
 
 
 
 
 
 
 
 
 
 
 
101
  class PixtralModel(nn.Module):
102
  def __init__(self, params):
103
  super().__init__()
104
- self.vision_encoder = VisionEncoder(params['vision_encoder'])
105
-
106
- def forward(self, image):
107
- return self.vision_encoder(image)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
- # Gradio interface
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 GELU activation in its layers.")
159
- gr.Markdown("3. The encoded image and the prompt are used to generate descriptive text.")
160
 
161
  gr.Markdown(description)
162
 
163
- with gr.Row():
164
- image1_input = gr.Image(type="pil", label="Image 1")
165
- image2_input = gr.Image(type="pil", label="Image 2")
166
-
167
- submit_btn = gr.Button("📸🌬️Calculate Similarity")
168
- similarity_output = gr.Number(label="Similarity Score (0.0 to 1.0)")
169
-
170
- submit_btn.click(
171
- fn=calculate_similarity,
172
- inputs=[image1_input, image2_input],
173
- outputs=[similarity_output]
174
- )
175
-
176
- if __name__ == "__main__":
177
- demo.launch()
178
-
179
- # import torch
180
- # import torch.nn as nn
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
- # with gr.Column(scale=1):
278
- # output_text = gr.Textbox(label="Generated Text")
279
- # token_count = gr.Number(label="Number of Tokens")
280
- # image_count = gr.Number(label="Number of Images")
281
-
282
- # submit_btn.click(
283
- # fn=process_image_and_text,
284
- # inputs=[input_image, input_prompt],
285
- # outputs=[output_text, token_count, image_count]
286
- # )
287
-
288
- # if __name__ == "__main__":
289
- # demo.launch()
 
 
 
 
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()