|
import gradio as gr |
|
import os |
|
import torch |
|
from transformers import AutoProcessor, MllamaForConditionalGeneration |
|
from PIL import Image |
|
import spaces |
|
|
|
|
|
IS_SPACES_ZERO = os.environ.get("SPACES_ZERO_GPU", "0") == "1" |
|
IS_SPACE = os.environ.get("SPACE_ID", None) is not None |
|
|
|
|
|
device = "cuda" if torch.cuda.is_available() else "cpu" |
|
LOW_MEMORY = os.getenv("LOW_MEMORY", "0") == "1" |
|
|
|
print(f"Using device: {device}") |
|
print(f"Low memory mode: {LOW_MEMORY}") |
|
|
|
|
|
HF_TOKEN = os.environ.get('HF_TOKEN') |
|
|
|
|
|
model_name = "ruslanmv/Llama-3.2-11B-Vision-Instruct" |
|
model = MllamaForConditionalGeneration.from_pretrained( |
|
model_name, |
|
use_auth_token=HF_TOKEN, |
|
torch_dtype=torch.bfloat16 if device == "cuda" else torch.float32, |
|
device_map="auto" if device == "cuda" else None, |
|
) |
|
|
|
|
|
model.to(device) |
|
processor = AutoProcessor.from_pretrained(model_name, use_auth_token=HF_TOKEN) |
|
|
|
@spaces.GPU |
|
def predict(image, text): |
|
|
|
messages = [ |
|
{"role": "user", "content": [ |
|
{"type": "image"}, |
|
{"type": "text", "text": text} |
|
]} |
|
] |
|
|
|
|
|
input_text = processor.apply_chat_template(messages, add_generation_prompt=True) |
|
|
|
|
|
inputs = processor(image, input_text, return_tensors="pt").to(device) |
|
|
|
|
|
outputs = model.generate(**inputs, max_new_tokens=100) |
|
|
|
|
|
response = processor.decode(outputs[0], skip_special_tokens=True) |
|
return response |
|
|
|
|
|
interface = gr.Interface( |
|
fn=predict, |
|
inputs=[ |
|
gr.Image(type="pil", label="Image Input"), |
|
gr.Textbox(label="Text Input") |
|
], |
|
outputs=gr.Textbox(label="Generated Response"), |
|
title="Llama 3.2 11B Vision Instruct Demo", |
|
description="This demo uses Meta's Llama 3.2 11B Vision model to generate responses based on an image and text input.", |
|
theme="compact" |
|
) |
|
|
|
|
|
interface.launch(debug=True) |
|
|