Views
No views yet
pip install pillow torchao1from transformers import AutoModelForCausalLM, AutoTokenizer
2from PIL import Image
3
4model = AutoModelForCausalLM.from_pretrained(
5 "moondream/moondream-2b-2025-04-14-4bit",
6 trust_remote_code=True,
7 device_map={"": "cuda"}
8)
9
10# Optional, but recommended when running inference on a large number of
11# images since it has upfront compilation cost but significantly speeds
12# up inference:
13model.model.compile()
14
15# Captioning
16print("Short caption:")
17print(model.caption(image, length="short")["caption"])
18
19print("\nNormal caption:")
20for t in model.caption(image, length="normal", stream=True)["caption"]:
21 # Streaming generation example, supported for caption() and detect()
22 print(t, end="", flush=True)
23print(model.caption(image, length="normal"))
24
25# Visual Querying
26print("\nVisual query: 'How many people are in the image?'")
27print(model.query(image, "How many people are in the image?")["answer"])
28
29# Object Detection
30print("\nObject detection: 'face'")
31objects = model.detect(image, "face")["objects"]
32print(f"Found {len(objects)} face(s)")
33
34# Pointing
35print("\nPointing: 'person'")
36points = model.point(image, "person")["points"]
37print(f"Found {len(points)} person(s)")