Spaces:
Running on Zero

molmo3-8b / app.py
multimodalart's picture
multimodalart HF Staff
Upload app.py with huggingface_hub
490742f verified
Raw History Blame Contribute Delete
12.4 kB
import spaces # must come before torch
import json
import time
import gradio as gr
import numpy as np
import torch
from PIL import Image, ImageDraw, ImageFont
from transformers import AutoModelForImageTextToText, AutoProcessor
MODEL_ID = "allenai/Molmo3-8B"
processor = AutoProcessor.from_pretrained(MODEL_ID, trust_remote_code=True)
model = AutoModelForImageTextToText.from_pretrained(
MODEL_ID, trust_remote_code=True, dtype=torch.bfloat16
).to("cuda").eval()
PALETTE = [
(240, 82, 156), (15, 203, 140), (59, 130, 246), (250, 204, 21),
(168, 85, 247), (249, 115, 22), (20, 184, 166), (239, 68, 68),
]
try:
FONT = ImageFont.load_default(size=14)
except TypeError:
FONT = ImageFont.load_default()
def _rle_to_mask(rle):
fn = getattr(processor, "rle_to_mask", None)
if fn is None:
import sys
fn = sys.modules[type(processor).__module__].rle_to_mask
return np.asarray(fn(rle), dtype=bool)
def _label(draw, xy, text, color):
x, y = xy
l, t, r, b = draw.textbbox((0, 0), text, font=FONT)
W, H = draw.im.size
x = max(3, min(x, W - (r - l) - 4))
y = max(2, min(y, H - (b - t) - 4))
l, t, r, b = draw.textbbox((x, y), text, font=FONT)
draw.rectangle((l - 3, t - 2, r + 3, b + 2), fill=(0, 0, 0, 170))
draw.text((x, y), text, fill=color + (255,), font=FONT)
def _dot(draw, x, y, color, r):
draw.ellipse((x - r, y - r, x + r, y + r), fill=color + (255,), outline=(255, 255, 255, 255), width=2)
def _box_corners(box, K):
"""Project the 8 corners of a 3D box (camera coords: x right, y down, z forward)."""
c = np.asarray(box["center"], dtype=np.float64)
R = np.asarray(box["rotation"], dtype=np.float64)
w, h, l = [float(v) for v in box["size"]]
signs = np.array([[sx, sy, sz] for sx in (-1, 1) for sy in (-1, 1) for sz in (-1, 1)], dtype=np.float64)
local = signs * np.array([w, h, l]) / 2.0
pts = local @ R.T + c
if np.any(pts[:, 2] <= 1e-3):
return None
K = np.asarray(K, dtype=np.float64)
uv = pts @ K.T
return uv[:, :2] / uv[:, 2:3]
BOX_EDGES = [(0, 1), (2, 3), (4, 5), (6, 7), (0, 2), (1, 3), (4, 6), (5, 7), (0, 4), (1, 5), (2, 6), (3, 7)]
def render(image: Image.Image, document: dict) -> Image.Image:
"""Overlay every grounding element of a decoded Molmo3 document onto the image."""
base = image.convert("RGBA")
W, H = base.size
r = max(4, int(round(min(W, H) / 90)))
lw = max(2, int(round(min(W, H) / 250)))
overlay = Image.new("RGBA", base.size, (0, 0, 0, 0))
elements = [e for e in document.get("multi_modal", []) if e.get("type") != "camera_intrinsics"]
# Masks first (beneath everything else)
for i, el in enumerate(elements):
if el.get("type") != "segmentation":
continue
color = PALETTE[i % len(PALETTE)]
mm_ids = el.get("mm_ids")
for j, rle in enumerate(el.get("masks") or []):
if mm_ids and mm_ids[j] != 0:
continue
mask = _rle_to_mask(rle)
if mask.shape != (H, W):
mask = np.array(Image.fromarray(mask.astype(np.uint8) * 255).resize((W, H), Image.NEAREST)) > 127
layer = np.zeros((H, W, 4), dtype=np.uint8)
layer[mask] = color + (120,)
overlay = Image.alpha_composite(overlay, Image.fromarray(layer, "RGBA"))
# outline
edge = mask ^ np.roll(mask, 1, 0) | mask ^ np.roll(mask, 1, 1)
e_layer = np.zeros((H, W, 4), dtype=np.uint8)
e_layer[edge & mask] = color + (255,)
overlay = Image.alpha_composite(overlay, Image.fromarray(e_layer, "RGBA"))
draw = ImageDraw.Draw(overlay)
for i, el in enumerate(elements):
kind = el.get("type")
color = PALETTE[i % len(PALETTE)]
label = el.get("label") or ""
coords = [c for c in (el.get("coordinates") or []) if c.get("mm_ix", 0) == 0]
if kind == "segmentation":
masks = el.get("masks") or []
if masks and label:
m = _rle_to_mask(masks[0])
ys, xs = np.nonzero(m)
if len(xs):
_label(draw, (int(xs.min()), max(0, int(ys.min()) - 18)), label, color)
continue
if kind == "points":
pts = [(c["x"], c["y"]) for c in coords if c.get("x") is not None]
if el.get("ordered") and len(pts) > 1:
draw.line(pts, fill=color + (255,), width=lw)
for k, (x, y) in enumerate(pts):
_dot(draw, x, y, color, r)
if el.get("ordered"):
_label(draw, (x + r + 2, y - r), str(k + 1), color)
if pts and label:
_label(draw, (pts[0][0] + r + 2, pts[0][1] + r), label, color)
elif kind == "points_3d":
for c in coords:
x, y, d = c["x"], c["y"], c.get("depth")
_dot(draw, x, y, color, r)
txt = f"{d:.2f} m" if d is not None and d >= 0 else "n/a"
_label(draw, (x + r + 2, y - r), txt, color)
elif kind == "points_normal":
L = min(W, H) / 10
for c in coords:
x, y = c["x"], c["y"]
_dot(draw, x, y, color, r)
nx, ny = c.get("nx"), c.get("ny")
if nx is not None and ny is not None:
ex, ey = x + nx * L, y + ny * L
draw.line((x, y, ex, ey), fill=color + (255,), width=lw + 1)
ang = np.arctan2(ey - y, ex - x)
a = r * 1.8
draw.polygon([
(ex, ey),
(ex - a * np.cos(ang - 0.45), ey - a * np.sin(ang - 0.45)),
(ex - a * np.cos(ang + 0.45), ey - a * np.sin(ang + 0.45)),
], fill=color + (255,))
_label(draw, (x + r + 2, y + r), f"({nx:.2f}, {ny:.2f}, {c.get('nz', 0):.2f})", color)
elif kind == "bounding_boxes_3d":
K = el.get("K")
for c in coords:
if c.get("mm_ix", 0) != 0:
continue
corners = None
if K is not None and c.get("center") is not None:
try:
corners = _box_corners(c, K)
except Exception:
corners = None
if corners is not None:
for a, b in BOX_EDGES:
draw.line([tuple(corners[a]), tuple(corners[b])], fill=color + (255,), width=lw)
cx, cy = c["center_2d"]
_dot(draw, cx, cy, color, max(3, r - 1))
size = c.get("size") or []
txt = (label + " " if label else "") + f"{c.get('depth', 0):.2f} m"
if len(size) == 3:
txt += f" | {size[0]:.2f}x{size[1]:.2f}x{size[2]:.2f} m"
_label(draw, (cx + r + 2, cy - r), txt, color)
return Image.alpha_composite(base, overlay).convert("RGB")
def _format_answer(document: dict) -> str:
text = document.get("text", "")
lines = [text.strip() or "_(no text)_"]
for el in document.get("multi_modal", []):
if el.get("type") == "camera_intrinsics":
for c in el.get("coordinates", []):
lines.append(f"\n**Camera FoV** — horizontal {c['hfov']:.1f}°, vertical {c['vfov']:.1f}°")
return "\n".join(lines)
def _jsonable(obj):
if isinstance(obj, dict):
return {k: _jsonable(v) for k, v in obj.items()}
if isinstance(obj, (list, tuple)):
return [_jsonable(v) for v in obj]
if isinstance(obj, (np.integer,)):
return int(obj)
if isinstance(obj, (np.floating,)):
return float(obj)
if isinstance(obj, np.ndarray):
return obj.tolist()
if isinstance(obj, bytes):
return obj.decode("utf-8", errors="replace")
return obj
def _duration(image, prompt, max_new_tokens=512, *args, **kwargs):
# measured on ZeroGPU: ~30 ms/token + ~1 s prefill (215 tok -> 6.5 s); ~15% margin
return int(4 + 0.03 * int(max_new_tokens))
@spaces.GPU(duration=_duration)
def run(image: Image.Image, prompt: str, max_new_tokens: int = 512):
"""Ask Molmo3-8B about an image: QA, captioning, pointing, segmentation, depth, normals, 3D boxes.
Args:
image: the input image.
prompt: instruction, e.g. "Point to the spoon.", "Segment the cat.", "Find the 3D boxes for cup."
max_new_tokens: generation budget.
Returns:
The annotated image, the answer text, and the structured grounding document (JSON).
"""
if image is None:
raise gr.Error("Please upload an image.")
if not prompt or not prompt.strip():
raise gr.Error("Please enter a prompt.")
image = image.convert("RGB")
t0 = time.perf_counter()
messages = [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": prompt.strip()}]}]
inputs = processor.apply_chat_template(messages, images=[image], tokenize=True).to("cuda")
with torch.inference_mode():
out = model.generate(**inputs, max_new_tokens=int(max_new_tokens), do_sample=False,
return_dict_in_generate=True)
ids = out.sequences[0, inputs["input_ids"].shape[1]:].cpu()
grounding = out.grounding[0] if getattr(out, "grounding", None) else None
document = processor.decode(ids, grounding, images=[image])
document = _jsonable(document)
print(f"[molmo3] '{prompt[:60]}' -> {len(ids)} tokens in {time.perf_counter() - t0:.1f}s")
annotated = render(image, document)
return annotated, _format_answer(document), document
CSS = """
#col-container { max-width: 1200px; margin: 0 auto; }
.dark .gradio-container { color: var(--body-text-color); }
"""
with gr.Blocks() as demo:
with gr.Column(elem_id="col-container"):
gr.Markdown(
"# Molmo3-8B\n"
"Ai2's open vision-language model for spatial & 3D understanding: ask questions, point, "
"segment, estimate depth / surface normals / field of view, and detect 3D boxes from free-form text. "
"Grounding outputs are drawn on the image.\n\n"
"[Model](https://huggingface.co/allenai/Molmo3-8B) · [Paper](https://allenai.org/papers/molmo3) · "
"[Blog](https://allenai.org/blog/molmo3) · [Code](https://github.com/allenai/molmo3)"
)
with gr.Row():
with gr.Column():
image_in = gr.Image(type="pil", label="Image", height=420)
prompt = gr.Textbox(label="Prompt", placeholder="e.g. Segment the cat. / Point to the spoon and tell me how far it is from the camera.", lines=2)
run_btn = gr.Button("Run", variant="primary")
with gr.Accordion("Advanced settings", open=False):
max_new_tokens = gr.Slider(16, 1024, value=512, step=16, label="Max new tokens")
with gr.Column():
image_out = gr.Image(type="pil", label="Grounding", height=420, format="png")
answer = gr.Markdown(label="Answer")
with gr.Accordion("Structured output (JSON)", open=False):
doc_out = gr.JSON(label="Decoded document")
gr.Examples(
examples=[
["examples/chelsea.png", "Segment the cat."],
["examples/chelsea.png", "Point to the cat's eyes."],
["examples/coffee.png", "Point to the spoon and tell me how far each is from the camera."],
["examples/coffee.png", "Find the 3D boxes for cup."],
["examples/coffee.png", "Point to the table and give the surface normal at each."],
["examples/coffee.png", "Give the horizontal and vertical field of view of this image, in degrees."],
["examples/astronaut.png", "Describe this image."],
],
inputs=[image_in, prompt],
outputs=[image_out, answer, doc_out],
fn=run,
cache_examples=True,
cache_mode="lazy",
)
gr.on([run_btn.click, prompt.submit], run, inputs=[image_in, prompt, max_new_tokens],
outputs=[image_out, answer, doc_out], api_name="run")
if __name__ == "__main__":
demo.launch(theme=gr.themes.Citrus(), css=CSS, mcp_server=True)