Views
No views yet
1from transformers import AutoConfig, AutoProcessor, GenerationConfig
2from transformers.image_utils import load_image
3import onnxruntime
4import numpy as np
5import os
6
7# 1. Load config, processor, and model
8model_id = "onnx-community/gemma-3-4b-it-ONNX"
9local_dir = "./gemma-3-4b-it"
10onnx_dir = os.path.join(local_dir, "onnx")
11
12config = AutoConfig.from_pretrained(model_id)
13processor = AutoProcessor.from_pretrained(model_id)
14generation_config = GenerationConfig.from_pretrained(model_id)
15
16## Load sessions
17providers = ['CPUExecutionProvider']
18vision_session = onnxruntime.InferenceSession(os.path.join(onnx_dir, "vision_encoder.onnx"), providers=providers)
19embed_session = onnxruntime.InferenceSession(os.path.join(onnx_dir, "embed_tokens.onnx"), providers=providers)
20decoder_session = onnxruntime.InferenceSession(os.path.join(onnx_dir, "decoder_model_merged.onnx"), providers=providers)
21
22## Set config values
23text_config = config.text_config
24num_key_value_heads = text_config.num_key_value_heads
25head_dim = text_config.head_dim
26num_hidden_layers = text_config.num_hidden_layers
27eos_token_id = generation_config.eos_token_id
28image_token_index = config.image_token_index
29
30# 2. Prepare inputs
31image_url = "https://www.ilankelman.org/stopsigns/australia.jpg"
32image = load_image(image_url)
33messages = [
34 {
35 "role": "user",
36 "content": [
37 {"type": "image", "image": image},
38 {"type": "text", "text": "What is in this image?"},
39 ],
40 },
41]
42inputs = processor.apply_chat_template(
43 messages,
44 add_generation_prompt=True,
45 return_tensors="pt",
46 return_dict=True,
47 tokenize=True,
48)
49
50input_ids = inputs['input_ids'].numpy()
51attention_mask = inputs['attention_mask'].numpy()
52has_vision_inputs = 'pixel_values' in inputs
53pixel_values = inputs['pixel_values'].numpy() if has_vision_inputs else None
54num_logits_to_keep = np.array(1, dtype=np.int64)
55
56batch_size = input_ids.shape[0]
57past_cache_values = {}
58for i in range(num_hidden_layers):
59 for kv in ('key', 'value'):
60 past_cache_values[f'past_key_values.{i}.{kv}'] = np.zeros([batch_size, num_key_value_heads, 0, head_dim], dtype=np.float32)
61
62# 3. Generation loop
63max_new_tokens = 1024
64generated_tokens = np.array([[]], dtype=np.int64)
65image_features = None
66for i in range(max_new_tokens):
67 inputs_embeds = embed_session.run(None, {'input_ids': input_ids})[0]
68
69 if has_vision_inputs and image_features is None:
70 ## Only compute vision features on first iteration
71 image_features = vision_session.run(None, dict(
72 pixel_values=pixel_values,
73 ))[0]
74
75 ## Merge text and vision embeddings
76 inputs_embeds[input_ids == image_token_index] = image_features.reshape(-1, image_features.shape[-1])
77
78 decoder_inputs = dict(
79 inputs_embeds=inputs_embeds,
80 attention_mask=attention_mask,
81 num_logits_to_keep=num_logits_to_keep,
82 **past_cache_values,
83 )
84
85 logits, *present_cache_values = decoder_session.run(None, decoder_inputs)
86
87 ## Update values for next generation loop
88 input_ids = logits[:, -1].argmax(-1, keepdims=True)
89 attention_mask = np.concatenate([attention_mask, np.ones((batch_size, 1), dtype=attention_mask.dtype)], axis=-1)
90 for j, key in enumerate(past_cache_values):
91 past_cache_values[key] = present_cache_values[j]
92
93 generated_tokens = np.concatenate([generated_tokens, input_ids], axis=-1)
94 if np.isin(input_ids, eos_token_id).any():
95 break
96
97 ## (Optional) Streaming
98 print(processor.decode(input_ids[0], skip_special_tokens=False), end='', flush=True)
99print()
100
101# 4. Output result
102print(processor.batch_decode(generated_tokens, skip_special_tokens=False)[0])