import os
os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")
import spaces # ZeroGPU: must be imported before torch/CUDA
import json
import time
import gradio as gr
import torch
from PIL import Image
from transformers import AutoProcessor, Qwen3_5ForConditionalGeneration
MODEL_IDS = {
"BlinkOPD-4B": "Danny-Lian/BlinkOPD-4B",
"BlinkOPD-9B": "Danny-Lian/BlinkOPD-9B",
}
DEFAULT_MODEL = "BlinkOPD-4B"
EVAL_POST_PROMPT = "\nAnswer with the option's letter from the given choices directly."
# Example images from ZoomBench (Apache-2.0, https://huggingface.co/datasets/inclusionAI/ZoomBench),
# one of the fine-grained perception benchmarks used to evaluate BlinkOPD.
EXAMPLES = [
{
"image": "examples/vehicle_number.jpg",
"question": "What is the number written on the side of the blue vehicle?\nA. C519\nB. C518\nC. C517\nD. C520",
"answer": "B",
},
{
"image": "examples/magnet_bird.jpg",
"question": "What kind of bird is shown on the green magnet in the middle of the display?\nA. penguin\nB. owl\nC. parrot\nD. eagle",
"answer": "B",
},
{
"image": "examples/pirata_letters.jpg",
"question": "What color is the outline of the letters that spell 'Pirata'?\nA. Blue\nB. White\nC. Red\nD. Black",
"answer": "C",
},
{
"image": "examples/cap_text.jpg",
"question": "What text is written on the man's blue cap?\nA. OFF ROAD RALLY\nB. ROAD RACE TRIAL\nC. MOTOR SPORTS\nD. RACE TEAM JAPAN",
"answer": "B",
},
{
"image": "examples/tram_symbol.jpg",
"question": "What symbol is visible on the tram's front, to the left of the number 8275?\nA. European Union flag - blue background with yellow stars\nB. No Smoking symbol - red circle with diagonal line through cigarette\nC. International Symbol of Access (wheelchair symbol) - white wheelchair figure on blue background\nD. Emergency Exit symbol - green rectangle with white running figure",
"answer": "C",
},
{
"image": "examples/racket_strings.jpg",
"question": "What color are the strings on the tennis racket?",
"answer": "off-white/light colored with a red logo stenciled on them",
},
]
print("Loading processors...")
processors = {}
for name, mid in MODEL_IDS.items():
processors[name] = AutoProcessor.from_pretrained(mid)
print(f"Loading {DEFAULT_MODEL} weights...")
model = (
Qwen3_5ForConditionalGeneration.from_pretrained(
MODEL_IDS[DEFAULT_MODEL],
dtype=torch.bfloat16,
attn_implementation="sdpa",
)
.to("cuda")
.eval()
)
CURRENT = DEFAULT_MODEL
@spaces.GPU(duration=90)
def answer(
image: Image.Image | None,
question: str,
model_choice: str,
max_new_tokens: int = 256,
temperature: float = 0.0,
top_p: float = 1.0,
eval_mode: bool = True,
progress=gr.Progress(),
):
"""Answer a question about an image using BlinkOPD.
Args:
image: The image to examine.
question: Question about the image (multiple-choice with A./B./C./D. options, or open-ended).
model_choice: Which BlinkOPD checkpoint to use.
max_new_tokens: Maximum number of tokens to generate.
temperature: Sampling temperature (0 = greedy).
top_p: Nucleus sampling threshold.
eval_mode: Append the benchmark answer-format suffix used for multiple-choice evaluation.
"""
global CURRENT
if image is None:
raise gr.Error("Please upload an image first.")
question = (question or "").strip()
if not question:
raise gr.Error("Please enter a question.")
if model_choice not in MODEL_IDS:
model_choice = DEFAULT_MODEL
if model_choice != CURRENT:
raise gr.Error(
f"The {model_choice} checkpoint is not loaded in this Space — "
f"only {CURRENT} is kept resident to fit ZeroGPU memory."
)
if not isinstance(image, Image.Image):
image = Image.open(image)
if image.mode != "RGB":
image = image.convert("RGB")
prompt = question
if eval_mode and (
"\nA." in prompt or "\n(A)" in prompt or "\nA)" in prompt or "\nA " in prompt
):
prompt += EVAL_POST_PROMPT
processor = processors[model_choice]
messages = [
{
"role": "user",
"content": [
{"type": "image", "image": image},
{"type": "text", "text": prompt},
],
}
]
text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
inputs = processor(
text=[text], images=[image], return_tensors="pt"
).to("cuda")
do_sample = temperature > 0
gen_kwargs = dict(
max_new_tokens=int(max_new_tokens),
do_sample=do_sample,
temperature=float(temperature) if do_sample else None,
top_p=float(top_p) if do_sample else None,
)
t0 = time.perf_counter()
with torch.inference_mode():
out = model.generate(**inputs, **gen_kwargs)
elapsed = time.perf_counter() - t0
new_tokens = out[0][inputs["input_ids"].shape[1]:]
response = processor.tokenizer.decode(new_tokens, skip_special_tokens=True).strip()
# strip the empty thinking block the chat template seeds
for prefix in ("\n\n\n\n", "\n\n\n", ""):
if response.startswith(prefix):
response = response[len(prefix):].strip()
break
timing = f"({elapsed:.1f}s · {model_choice} · {len(new_tokens)} tokens)"
return response or "—", timing
def make_examples():
rows = []
for ex in EXAMPLES:
rows.append(
[
os.path.join(os.path.dirname(__file__), ex["image"]),
ex["question"],
]
)
return rows
CSS = """
#col-container { max-width: 1100px; margin: 0 auto; }
.dark .gradio-container { color: var(--body-text-color); }
main, .gradio-container { width: 100% !important; max-width: 1100px !important; margin: 0 auto !important; }
"""
with gr.Blocks() as demo:
gr.Markdown(
"""
# 👁️ BlinkOPD — Fine-Grained Multimodal Perception
**BlinkOPD-4B** (Qwen3.5-based VLM, fine-tuned with *Blink On-Policy Distillation*) answers questions that
require reading small, subtle details in an image — without zooming.
[[Paper](https://arxiv.org/abs/2611.16402)] · [[Code](https://github.com/Supltz/BlinkOPD)] · [[Model](https://huggingface.co/Danny-Lian/BlinkOPD-4B)]
"""
)
with gr.Column(elem_id="col-container"):
with gr.Row():
with gr.Column(scale=1):
image_in = gr.Image(type="pil", label="Image", height=360)
question_in = gr.Textbox(
label="Question",
placeholder="Ask anything about the image — e.g. 'What text is written on the sign?'",
lines=4,
)
eval_mode = gr.Checkbox(
value=True,
label="Benchmark answer format",
info="For multiple-choice questions, append the suffix used in the paper's evaluation "
"(“Answer with the option's letter from the given choices directly.”). "
"Turn off for open-ended questions.",
)
run_btn = gr.Button("Answer", variant="primary")
with gr.Column(scale=1):
answer_out = gr.Textbox(label="Answer", lines=4)
timing_out = gr.Markdown()
with gr.Accordion("Advanced settings", open=False):
model_choice = gr.Radio(
choices=list(MODEL_IDS.keys()),
value=DEFAULT_MODEL,
label="Checkpoint",
info="Only BlinkOPD-4B is kept resident on the GPU; the 9B checkpoint does not fit "
"alongside it in ZeroGPU memory.",
interactive=False,
)
max_new_tokens = gr.Slider(16, 1024, value=256, step=16, label="Max new tokens")
temperature = gr.Slider(0.0, 1.5, value=0.0, step=0.1, label="Temperature (0 = greedy)")
top_p = gr.Slider(0.05, 1.0, value=1.0, step=0.05, label="Top-p")
gr.Markdown("### Examples — from ZoomBench (Apache-2.0), one of the paper's evaluation benchmarks")
gr.Examples(
examples=make_examples(),
inputs=[image_in, question_in],
outputs=[answer_out, timing_out],
fn=answer,
cache_examples=True,
cache_mode="lazy",
run_on_click=True,
)
gr.Markdown(
"""
**Reference answers** (from the ZoomBench annotations):
1. C518 · 2. owl · 3. Red · 4. wheelchair symbol · 5. ROAD RACE TRIAL · 6. off-white strings with a red logo stencil
"""
)
run_btn.click(
fn=answer,
inputs=[image_in, question_in, model_choice, max_new_tokens, temperature, top_p, eval_mode],
outputs=[answer_out, timing_out],
api_name="answer",
)
if __name__ == "__main__":
demo.launch(theme=gr.themes.Citrus(), css=CSS, mcp_server=True)