Spaces:
Sleeping
Sleeping
Update app.py
Browse files12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879diff --git a/app.py b/app.pyindex 0000000..1111111 100644--- a/app.py+++ b/app.py@@ -1,16 +1,28 @@import gradio as grimport torchfrom PIL import Imagefrom transformers import AutoTokenizer, AutoModelForCausalLM-import spaces# Model configurationMID = "apple/FastVLM-0.5B"IMAGE_TOKEN_INDEX = -200# Load model and tokenizer (will be loaded on first GPU allocation)tok = Nonemodel = Nonedef load_model():global tok, modelif tok is None or model is None:print("Loading model...")tok = AutoTokenizer.from_pretrained(MID, trust_remote_code=True)- model = AutoModelForCausalLM.from_pretrained(- MID,- torch_dtype=torch.float16,- device_map="cuda",- trust_remote_code=True,- )+ # ---- CPU-first, with dynamic fallback if CUDA exists ----+ use_cuda = torch.cuda.is_available()+ device_map = "cuda" if use_cuda else "cpu"+ # float16 is great on GPU, but unsafe on CPU; use float32 on CPU+ dtype = torch.float16 if use_cuda else torch.float32++ model = AutoModelForCausalLM.from_pretrained(+ MID,+ torch_dtype=dtype,+ device_map=device_map,+ trust_remote_code=True,+ )print("Model loaded successfully!")return tok, model--@spaces.GPU(duration=60)++# Removed GPU decorator so CPU Spaces don't request a GPUdef caption_image(image, custom_prompt=None):@@ -66,16 +78,23 @@ def caption_image(image, custom_prompt=None):# Insert IMAGE token id at placeholder position- img_tok = torch.tensor([[IMAGE_TOKEN_INDEX]], dtype=pre_ids.dtype)- input_ids = torch.cat([pre_ids, img_tok, post_ids], dim=1).to(model.device)- attention_mask = torch.ones_like(input_ids, device=model.device)+ # Derive device/dtype from model parameters (robust on CPU or GPU)+ model_device = next(model.parameters()).device+ model_dtype = next(model.parameters()).dtype++ img_tok = torch.tensor([[IMAGE_TOKEN_INDEX]], dtype=pre_ids.dtype, device=model_device)+ input_ids = torch.cat([pre_ids.to(model_device), img_tok, post_ids.to(model_device)], dim=1)+ attention_mask = torch.ones_like(input_ids, device=model_device)# Preprocess image using model's vision towerpx = model.get_vision_tower().image_processor(images=image, return_tensors="pt")["pixel_values"]- px = px.to(model.device, dtype=model.dtype)+ px = px.to(model_device, dtype=model_dtype)# Generate captionwith torch.no_grad():out = model.generate(inputs=input_ids,attention_mask=attention_mask,images=px,max_new_tokens=128,do_sample=False, # Deterministic generation- temperature=1.0,+ # temperature is ignored when do_sample=False)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173import gradio as grimport torchfrom PIL import Imagefrom transformers import AutoTokenizer, AutoModelForCausalLMimport spaces# Model configurationMID = "apple/FastVLM-0.5B"IMAGE_TOKEN_INDEX = -200# Load model and tokenizer (will be loaded on first GPU allocation)tok = Nonemodel = Nonedef load_model():global tok, modelif tok is None or model is None:print("Loading model...")tok = AutoTokenizer.from_pretrained(MID, trust_remote_code=True)model = AutoModelForCausalLM.from_pretrained(MID,torch_dtype=torch.float16,device_map="cuda",trust_remote_code=True,)print("Model loaded successfully!")return tok, model@spaces.GPU(duration=60)def caption_image(image, custom_prompt=None):"""Generate a caption for the input image.Args:image: PIL Image from Gradiocustom_prompt: Optional custom prompt to use instead of defaultReturns:Generated caption text"""if image is None:return "Please upload an image first."try:# Load model if not already loadedtok, model = load_model()# Convert image to RGB if neededif image.mode != "RGB":image = image.convert("RGB")# Use custom prompt or defaultprompt = custom_prompt if custom_prompt else "Describe this image in detail."# Build chat messagemessages = [{"role": "user", "content": f"<image>\n{prompt}"}]# Render to string to place <image> token correctlyrendered = tok.apply_chat_template(messages, add_generation_prompt=True, tokenize=False)# Split at image tokenpre, post = rendered.split("<image>", 1)# Tokenize text around the image tokenpre_ids = tok(pre, return_tensors="pt", add_special_tokens=False).input_idspost_ids = tok(post, return_tensors="pt", add_special_tokens=False).input_ids# Insert IMAGE token id at placeholder positionimg_tok = torch.tensor([[IMAGE_TOKEN_INDEX]], dtype=pre_ids.dtype)input_ids = torch.cat([pre_ids, img_tok, post_ids], dim=1).to(model.device)attention_mask = torch.ones_like(input_ids, device=model.device)# Preprocess image using model's vision towerpx = model.get_vision_tower().image_processor(images=image, return_tensors="pt")["pixel_values"]px = px.to(model.device, dtype=model.dtype)# Generate captionwith torch.no_grad():out = model.generate(inputs=input_ids,attention_mask=attention_mask,images=px,max_new_tokens=128,do_sample=False, # Deterministic generationtemperature=1.0,)# Decode and return the generated textgenerated_text = tok.decode(out[0], skip_special_tokens=True)# Extract only the assistant's responseif "assistant" in generated_text:response = generated_text.split("assistant")[-1].strip()else:response = generated_textreturn responseexcept Exception as e:return f"Error generating caption: {str(e)}"# Create Gradio interfacewith gr.Blocks(title="FastVLM Image Captioning") as demo:gr.Markdown("""# 🖼️ FastVLM Image CaptioningUpload an image to generate a detailed caption using Apple's FastVLM-0.5B model.You can use the default prompt or provide your own custom prompt.""")with gr.Row():with gr.Column():image_input = gr.Image(type="pil",label="Upload Image",elem_id="image-upload")custom_prompt = gr.Textbox(label="Custom Prompt (Optional)",placeholder="Leave empty for default: 'Describe this image in detail.'",lines=2)with gr.Row():clear_btn = gr.ClearButton([image_input, custom_prompt])generate_btn = gr.Button("Generate Caption", variant="primary")with gr.Column():output = gr.Textbox(label="Generated Caption",lines=8,max_lines=15,show_copy_button=True)# Event handlersgenerate_btn.click(fn=caption_image,inputs=[image_input, custom_prompt],outputs=output)# Also generate on image upload if no custom promptimage_input.change(fn=lambda img, prompt: caption_image(img, prompt) if img is not None and not prompt else None,inputs=[image_input, custom_prompt],outputs=output)gr.Markdown("""---**Model:** [apple/FastVLM-0.5B](https://huggingface.co/apple/FastVLM-0.5B)**Note:** This Space uses ZeroGPU for dynamic GPU allocation.""")if __name__ == "__main__":demo.launch(share=False,show_error=True,server_name="0.0.0.0",server_port=7860)
app.py+169-75