This model is a fine-tuned version of
google/medgemma-4b-it.
It has been trained using
TRL.
1import torch
2from PIL import Image
3import requests
4from transformers import AutoModelForImageTextToText, AutoProcessor
5import os
6
7# Disable torch.compile to avoid the "Unsupported: generator" error
8torch._dynamo.config.disable = True
9
10# --- Configuration ---
11# Use the model
12MODEL_PATH = "Ab00D/Arabic_ElMostawsaf"
13
14# Automatically set device and data type
15DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
16# Use bfloat16 if supported (on Ampere GPUs like A100), otherwise float16
17DTYPE = torch.bfloat16 if torch.cuda.is_bf16_supported() else torch.float16
18
19print(f"Using device: {DEVICE}")
20print(f"Using dtype: {DTYPE}")
21
22# --- Load Model & Processor ---
23model = AutoModelForImageTextToText.from_pretrained(
24 MODEL_PATH,
25 torch_dtype=DTYPE,
26 device_map="auto", # Automatically handle model placement on devices
27 trust_remote_code=True # Add this if needed for custom model code
28)
29processor = AutoProcessor.from_pretrained(MODEL_PATH, trust_remote_code=True)
30tokenizer = processor.tokenizer
31
32
33# --- Prepare Image and Prompt ---
34# Load your image
35image = Image.open("Image Path").convert("RGB")
36
37# The prompt for the model
38user_prompt = "Analyze this medical image and provide step-by-step findings."
39
40# --- Create Chat Template ---
41chat = [
42 {
43 "role": "user",
44 "content": [
45 {"type": "image"},
46 {"type": "text", "text": user_prompt}
47 ],
48 }
49]
50formatted_prompt = processor.apply_chat_template(chat, add_generation_prompt=True, tokenize=False)
51
52# --- Run Inference ---
53# Process the text and image together
54inputs = processor(text=formatted_prompt, images=image, return_tensors="pt").to(DEVICE)
55
56# Move inputs to correct dtype if needed
57if hasattr(inputs, 'pixel_values') and inputs.pixel_values is not None:
58 inputs.pixel_values = inputs.pixel_values.to(dtype=DTYPE)
59
60input_ids_len = inputs["input_ids"].shape[-1]
61
62# Generate a response from the model with additional safeguards
63with torch.inference_mode():
64 try:
65 output_ids = model.generate(
66 **inputs,
67 max_new_tokens=200,
68 use_cache=True,
69 do_sample=False, # Use greedy decoding for more stable results
70 pad_token_id=tokenizer.eos_token_id, # Explicitly set pad token
71 temperature=0.7, # Add temperature control
72 top_p=0.9, # Add nucleus sampling
73 )
74 except Exception as e:
75 print(f"Error during generation: {e}")
76 print("Trying with simplified generation parameters...")
77 output_ids = model.generate(
78 input_ids=inputs["input_ids"],
79 pixel_values=inputs.get("pixel_values"),
80 max_new_tokens=200,
81 pad_token_id=tokenizer.eos_token_id,
82 )
83
84# Decode the generated tokens to text, skipping the prompt
85response = processor.decode(output_ids[0, input_ids_len:], skip_special_tokens=True)
86
87# --- Output ---
88print("\n📌 Model Prediction:")
89print(response)
This model was trained with SFT.
1@misc{vonwerra2022trl,
2 title = {{TRL: Transformer Reinforcement Learning}},
3 author = {Leandro von Werra and Younes Belkada and Lewis Tunstall and Edward Beeching and Tristan Thrush and Nathan Lambert and Shengyi Huang and Kashif Rasul and Quentin Gallou{\'e}dec},
4 year = 2020,
5 journal = {GitHub repository},
6 publisher = {GitHub},
7 howpublished = {\url{https://github.com/huggingface/trl}}
8}