Spaces:
Paused
Paused
add Pixtral
Browse files- .gitattributes +35 -0
- .gitignore +1 -0
- README.md +13 -0
- app.py +205 -0
- requirements.txt +7 -0
.gitattributes
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
*.7z filter=lfs diff=lfs merge=lfs -text
|
| 2 |
+
*.arrow filter=lfs diff=lfs merge=lfs -text
|
| 3 |
+
*.bin filter=lfs diff=lfs merge=lfs -text
|
| 4 |
+
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
| 5 |
+
*.ckpt filter=lfs diff=lfs merge=lfs -text
|
| 6 |
+
*.ftz filter=lfs diff=lfs merge=lfs -text
|
| 7 |
+
*.gz filter=lfs diff=lfs merge=lfs -text
|
| 8 |
+
*.h5 filter=lfs diff=lfs merge=lfs -text
|
| 9 |
+
*.joblib filter=lfs diff=lfs merge=lfs -text
|
| 10 |
+
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
| 11 |
+
*.mlmodel filter=lfs diff=lfs merge=lfs -text
|
| 12 |
+
*.model filter=lfs diff=lfs merge=lfs -text
|
| 13 |
+
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
| 14 |
+
*.npy filter=lfs diff=lfs merge=lfs -text
|
| 15 |
+
*.npz filter=lfs diff=lfs merge=lfs -text
|
| 16 |
+
*.onnx filter=lfs diff=lfs merge=lfs -text
|
| 17 |
+
*.ot filter=lfs diff=lfs merge=lfs -text
|
| 18 |
+
*.parquet filter=lfs diff=lfs merge=lfs -text
|
| 19 |
+
*.pb filter=lfs diff=lfs merge=lfs -text
|
| 20 |
+
*.pickle filter=lfs diff=lfs merge=lfs -text
|
| 21 |
+
*.pkl filter=lfs diff=lfs merge=lfs -text
|
| 22 |
+
*.pt filter=lfs diff=lfs merge=lfs -text
|
| 23 |
+
*.pth filter=lfs diff=lfs merge=lfs -text
|
| 24 |
+
*.rar filter=lfs diff=lfs merge=lfs -text
|
| 25 |
+
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
| 26 |
+
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
| 27 |
+
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
| 28 |
+
*.tar filter=lfs diff=lfs merge=lfs -text
|
| 29 |
+
*.tflite filter=lfs diff=lfs merge=lfs -text
|
| 30 |
+
*.tgz filter=lfs diff=lfs merge=lfs -text
|
| 31 |
+
*.wasm filter=lfs diff=lfs merge=lfs -text
|
| 32 |
+
*.xz filter=lfs diff=lfs merge=lfs -text
|
| 33 |
+
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
+
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
+
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
.gitignore
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
notes.py
|
README.md
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
title: Tonic's Pixtral
|
| 3 |
+
emoji: 📸🌬️
|
| 4 |
+
colorFrom: blue
|
| 5 |
+
colorTo: red
|
| 6 |
+
sdk: gradio
|
| 7 |
+
sdk_version: 4.44.0
|
| 8 |
+
app_file: app.py
|
| 9 |
+
pinned: true
|
| 10 |
+
license: mit
|
| 11 |
+
---
|
| 12 |
+
|
| 13 |
+
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
app.py
ADDED
|
@@ -0,0 +1,205 @@
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import gradio as gr
|
| 3 |
+
from vllm import LLM, SamplingParams
|
| 4 |
+
from PIL import Image
|
| 5 |
+
from io import BytesIO
|
| 6 |
+
import base64
|
| 7 |
+
import requests
|
| 8 |
+
from huggingface_hub import login
|
| 9 |
+
import torch
|
| 10 |
+
import torch.nn.functional as F
|
| 11 |
+
import spaces
|
| 12 |
+
import json
|
| 13 |
+
import gradio as gr
|
| 14 |
+
from huggingface_hub import snapshot_download
|
| 15 |
+
import os
|
| 16 |
+
# from loadimg import load_img
|
| 17 |
+
import traceback
|
| 18 |
+
|
| 19 |
+
login(os.environ.get("HUGGINGFACE_TOKEN"))
|
| 20 |
+
|
| 21 |
+
repo_id = "mistralai/Pixtral-12B-2409"
|
| 22 |
+
sampling_params = SamplingParams(max_tokens=8192, temperature=0.7)
|
| 23 |
+
max_tokens_per_img = 4096
|
| 24 |
+
max_img_per_msg = 5
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
title = "# **WIP / DEMO** 🙋🏻♂️Welcome to Tonic's Pixtral Model Demo"
|
| 28 |
+
description = """
|
| 29 |
+
### Join us :
|
| 30 |
+
🌟TeamTonic🌟 is always making cool demos! Join our active builder's 🛠️community 👻 [](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 🤗
|
| 31 |
+
"""
|
| 32 |
+
HUGGINGFACE_TOKEN = os.environ.get("HUGGINGFACE_TOKEN")
|
| 33 |
+
model_path = snapshot_download(repo_id="mistralai/Pixtral-12B-2409", token=HUGGINGFACE_TOKEN)
|
| 34 |
+
|
| 35 |
+
with open(f'{model_path}/params.json', 'r') as f:
|
| 36 |
+
params = json.load(f)
|
| 37 |
+
|
| 38 |
+
with open(f'{model_path}/tekken.json', 'r') as f:
|
| 39 |
+
tokenizer_config = json.load(f)
|
| 40 |
+
|
| 41 |
+
@spaces.GPU()
|
| 42 |
+
def initialize_llm():
|
| 43 |
+
try:
|
| 44 |
+
llm = LLM(
|
| 45 |
+
model=repo_id,
|
| 46 |
+
tokenizer_mode="mistral",
|
| 47 |
+
max_model_len=65536,
|
| 48 |
+
max_num_batched_tokens=max_img_per_msg * max_tokens_per_img,
|
| 49 |
+
limit_mm_per_prompt={"image": max_img_per_msg}
|
| 50 |
+
)
|
| 51 |
+
return llm
|
| 52 |
+
except Exception as e:
|
| 53 |
+
print("LLM initialization failed:", e)
|
| 54 |
+
return None
|
| 55 |
+
|
| 56 |
+
sampling_params = SamplingParams(max_tokens=8192)
|
| 57 |
+
llm = initialize_llm()
|
| 58 |
+
|
| 59 |
+
def encode_image(image: Image.Image, image_format="PNG") -> str:
|
| 60 |
+
im_file = BytesIO()
|
| 61 |
+
image.save(im_file, format=image_format)
|
| 62 |
+
im_bytes = im_file.getvalue()
|
| 63 |
+
im_64 = base64.b64encode(im_bytes).decode("utf-8")
|
| 64 |
+
return im_64
|
| 65 |
+
|
| 66 |
+
@spaces.GPU()
|
| 67 |
+
def infer(image_url, prompt, progress=gr.Progress(track_tqdm=True)):
|
| 68 |
+
if llm is None:
|
| 69 |
+
return "Error: LLM initialization failed. Please try again later."
|
| 70 |
+
|
| 71 |
+
try:
|
| 72 |
+
image = Image.open(BytesIO(requests.get(image_url).content))
|
| 73 |
+
image = image.resize((3844, 2408))
|
| 74 |
+
new_image_url = f"data:image/png;base64,{encode_image(image, image_format='PNG')}"
|
| 75 |
+
|
| 76 |
+
messages = [
|
| 77 |
+
{
|
| 78 |
+
"role": "user",
|
| 79 |
+
"content": [{"type": "text", "text": prompt}, {"type": "image_url", "image_url": {"url": new_image_url}}]
|
| 80 |
+
},
|
| 81 |
+
]
|
| 82 |
+
|
| 83 |
+
outputs = llm.chat(messages, sampling_params=sampling_params)
|
| 84 |
+
|
| 85 |
+
return outputs[0].outputs[0].text
|
| 86 |
+
except Exception as e:
|
| 87 |
+
return f"Error during inference: {e}"
|
| 88 |
+
|
| 89 |
+
@spaces.GPU()
|
| 90 |
+
def compare_images(image1_url, image2_url, prompt, progress=gr.Progress(track_tqdm=True)):
|
| 91 |
+
if llm is None:
|
| 92 |
+
return "Error: LLM initialization failed. Please try again later."
|
| 93 |
+
|
| 94 |
+
try:
|
| 95 |
+
image1 = Image.open(BytesIO(requests.get(image1_url).content))
|
| 96 |
+
image2 = Image.open(BytesIO(requests.get(image2_url).content))
|
| 97 |
+
image1 = image1.resize((3844, 2408))
|
| 98 |
+
image2 = image2.resize((3844, 2408))
|
| 99 |
+
new_image1_url = f"data:image/png;base64,{encode_image(image1, image_format='PNG')}"
|
| 100 |
+
new_image2_url = f"data:image/png;base64,{encode_image(image2, image_format='PNG')}"
|
| 101 |
+
|
| 102 |
+
messages = [
|
| 103 |
+
{
|
| 104 |
+
"role": "user",
|
| 105 |
+
"content": [
|
| 106 |
+
{"type": "text", "text": prompt},
|
| 107 |
+
{"type": "image_url", "image_url": {"url": new_image1_url}},
|
| 108 |
+
{"type": "image_url", "image_url": {"url": new_image2_url}}
|
| 109 |
+
]
|
| 110 |
+
},
|
| 111 |
+
]
|
| 112 |
+
|
| 113 |
+
outputs = llm.chat(messages, sampling_params=sampling_params)
|
| 114 |
+
|
| 115 |
+
return outputs[0].outputs[0].text
|
| 116 |
+
except Exception as e:
|
| 117 |
+
return f"Error during image comparison: {e}"
|
| 118 |
+
|
| 119 |
+
@spaces.GPU()
|
| 120 |
+
def calculate_image_similarity(image1_url, image2_url):
|
| 121 |
+
if llm is None:
|
| 122 |
+
return "Error: LLM initialization failed. Please try again later."
|
| 123 |
+
|
| 124 |
+
try:
|
| 125 |
+
image1 = Image.open(BytesIO(requests.get(image1_url).content)).convert('RGB')
|
| 126 |
+
image2 = Image.open(BytesIO(requests.get(image2_url).content)).convert('RGB')
|
| 127 |
+
image1 = image1.resize((224, 224)) # Resize to match model input size
|
| 128 |
+
image2 = image2.resize((224, 224))
|
| 129 |
+
|
| 130 |
+
image1_tensor = torch.tensor(list(image1.getdata())).view(1, 3, 224, 224).float() / 255.0
|
| 131 |
+
image2_tensor = torch.tensor(list(image2.getdata())).view(1, 3, 224, 224).float() / 255.0
|
| 132 |
+
|
| 133 |
+
with torch.no_grad():
|
| 134 |
+
embedding1 = llm.model.vision_encoder([image1_tensor])
|
| 135 |
+
embedding2 = llm.model.vision_encoder([image2_tensor])
|
| 136 |
+
|
| 137 |
+
similarity = F.cosine_similarity(embedding1.mean(dim=0), embedding2.mean(dim=0), dim=0).item()
|
| 138 |
+
|
| 139 |
+
return similarity
|
| 140 |
+
except Exception as e:
|
| 141 |
+
return f"Error during image similarity calculation: {e}"
|
| 142 |
+
|
| 143 |
+
with gr.Blocks() as demo:
|
| 144 |
+
gr.Markdown(title)
|
| 145 |
+
gr.Markdown("## How it works")
|
| 146 |
+
gr.Markdown("1. The image is processed by a Vision Encoder using 2D ROPE (Rotary Position Embedding).")
|
| 147 |
+
gr.Markdown("2. The encoder uses SiLU activation in its feed-forward layers.")
|
| 148 |
+
gr.Markdown("3. The encoded image is used for text generation or similarity comparison.")
|
| 149 |
+
gr.Markdown(
|
| 150 |
+
"""
|
| 151 |
+
## How to use
|
| 152 |
+
1. For Image-to-Text Generation:
|
| 153 |
+
- Enter the URL of an image
|
| 154 |
+
- Provide a prompt describing what you want to know about the image
|
| 155 |
+
- Click "Generate" to get the model's response
|
| 156 |
+
2. For Image Comparison:
|
| 157 |
+
- Enter URLs for two images you want to compare
|
| 158 |
+
- Provide a prompt asking about the comparison
|
| 159 |
+
- Click "Compare" to get the model's analysis
|
| 160 |
+
3. For Image Similarity:
|
| 161 |
+
- Enter URLs for two images you want to compare
|
| 162 |
+
- Click "Calculate Similarity" to get a similarity score between 0 and 1
|
| 163 |
+
"""
|
| 164 |
+
)
|
| 165 |
+
gr.Markdown(description)
|
| 166 |
+
with gr.Tabs():
|
| 167 |
+
with gr.TabItem("Image-to-Text Generation"):
|
| 168 |
+
with gr.Row():
|
| 169 |
+
image_url = gr.Text(label="Image URL")
|
| 170 |
+
prompt = gr.Text(label="Prompt")
|
| 171 |
+
generate_button = gr.Button("Generate")
|
| 172 |
+
output = gr.Text(label="Generated Text")
|
| 173 |
+
|
| 174 |
+
generate_button.click(infer, inputs=[image_url, prompt], outputs=output)
|
| 175 |
+
|
| 176 |
+
with gr.TabItem("Image Comparison"):
|
| 177 |
+
with gr.Row():
|
| 178 |
+
image1_url = gr.Text(label="Image 1 URL")
|
| 179 |
+
image2_url = gr.Text(label="Image 2 URL")
|
| 180 |
+
comparison_prompt = gr.Text(label="Comparison Prompt")
|
| 181 |
+
compare_button = gr.Button("Compare")
|
| 182 |
+
comparison_output = gr.Text(label="Comparison Result")
|
| 183 |
+
|
| 184 |
+
compare_button.click(compare_images, inputs=[image1_url, image2_url, comparison_prompt], outputs=comparison_output)
|
| 185 |
+
|
| 186 |
+
with gr.TabItem("Image Similarity"):
|
| 187 |
+
with gr.Row():
|
| 188 |
+
sim_image1_url = gr.Text(label="Image 1 URL")
|
| 189 |
+
sim_image2_url = gr.Text(label="Image 2 URL")
|
| 190 |
+
similarity_button = gr.Button("Calculate Similarity")
|
| 191 |
+
similarity_output = gr.Number(label="Similarity Score")
|
| 192 |
+
|
| 193 |
+
similarity_button.click(calculate_image_similarity, inputs=[sim_image1_url, sim_image2_url], outputs=similarity_output)
|
| 194 |
+
gr.Markdown("## Model Details")
|
| 195 |
+
gr.Markdown(f"- Model Dimension: {params['dim']}")
|
| 196 |
+
gr.Markdown(f"- Number of Layers: {params['n_layers']}")
|
| 197 |
+
gr.Markdown(f"- Number of Attention Heads: {params['n_heads']}")
|
| 198 |
+
gr.Markdown(f"- Vision Encoder Hidden Size: {params['vision_encoder']['hidden_size']}")
|
| 199 |
+
gr.Markdown(f"- Number of Vision Encoder Layers: {params['vision_encoder']['num_hidden_layers']}")
|
| 200 |
+
gr.Markdown(f"- Number of Vision Encoder Attention Heads: {params['vision_encoder']['num_attention_heads']}")
|
| 201 |
+
gr.Markdown(f"- Image Size: {params['vision_encoder']['image_size']}x{params['vision_encoder']['image_size']}")
|
| 202 |
+
gr.Markdown(f"- Patch Size: {params['vision_encoder']['patch_size']}x{params['vision_encoder']['patch_size']}")
|
| 203 |
+
|
| 204 |
+
if __name__ == "__main__":
|
| 205 |
+
demo.launch()
|
requirements.txt
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
torch>=1.9.0
|
| 2 |
+
safetensors>=0.3.1
|
| 3 |
+
Pillow>=9.0.0
|
| 4 |
+
numpy>=1.21.0
|
| 5 |
+
mistral_common
|
| 6 |
+
loadimg
|
| 7 |
+
vllm==0.6.1
|