Views
No views yet
$ pip install git+https://github.com/huggingface/transformers@v4.49.0-Gemma-3pipeline APIpipeline as follows.1from transformers import pipeline
2import torch
3
4pipe = pipeline(
5 "image-text-to-text",
6 model="google/gemma-3-4b-it",
7 device="cuda",
8 torch_dtype=torch.bfloat16
9)1messages = [
2 {
3 "role": "system",
4 "content": [{"type": "text", "text": "You are a helpful assistant."}]
5 },
6 {
7 "role": "user",
8 "content": [
9 {"type": "image", "url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/p-blog/candy.JPG"},
10 {"type": "text", "text": "What animal is on the candy?"}
11 ]
12 }
13]
14
15output = pipe(text=messages, max_new_tokens=200)
16print(output[0][0]["generated_text"][-1]["content"])
17# Okay, let's take a look!
18# Based on the image, the animal on the candy is a **turtle**.
19# You can see the shell shape and the head and legs.1# pip install accelerate
2
3from transformers import AutoProcessor, Gemma3ForConditionalGeneration
4from PIL import Image
5import requests
6import torch
7
8model_id = "google/gemma-3-4b-it"
9
10model = Gemma3ForConditionalGeneration.from_pretrained(
11 model_id, device_map="auto"
12).eval()
13
14processor = AutoProcessor.from_pretrained(model_id)
15
16messages = [
17 {
18 "role": "system",
19 "content": [{"type": "text", "text": "You are a helpful assistant."}]
20 },
21 {
22 "role": "user",
23 "content": [
24 {"type": "image", "image": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/bee.jpg"},
25 {"type": "text", "text": "Describe this image in detail."}
26 ]
27 }
28]
29
30inputs = processor.apply_chat_template(
31 messages, add_generation_prompt=True, tokenize=True,
32 return_dict=True, return_tensors="pt"
33).to(model.device, dtype=torch.bfloat16)
34
35input_len = inputs["input_ids"].shape[-1]
36
37with torch.inference_mode():
38 generation = model.generate(**inputs, max_new_tokens=100, do_sample=False)
39 generation = generation[0][input_len:]
40
41decoded = processor.decode(generation, skip_special_tokens=True)
42print(decoded)
43
44# **Overall Impression:** The image is a close-up shot of a vibrant garden scene,
45# focusing on a cluster of pink cosmos flowers and a busy bumblebee.
46# It has a slightly soft, natural feel, likely captured in daylight.