Views
No views yet
1from transformers import AutoConfig, AutoTokenizer
2import onnxruntime
3import numpy as np
4
5# 1. Setup
6## Load config and tokenizer
7model_id = "onnx-community/granite-4.0-h-1b-ONNX"
8config = AutoConfig.from_pretrained(model_id)
9tokenizer = AutoTokenizer.from_pretrained(model_id)
10
11## Load model
12filename = "model" # Options: "model", "model_q4", "model_fp16", "model_q4f16"
13dtype = np.float32 # or np.float16 if using fp16/q4f16
14model_path = f"/path/to/model/onnx/{filename}.onnx"
15decoder_session = onnxruntime.InferenceSession(model_path)
16output_names = [o.name for o in decoder_session.get_outputs()]
17
18## Initialize config values
19num_key_value_heads = config.num_key_value_heads
20head_dim = config.hidden_size // config.num_attention_heads
21eos_token_id = config.eos_token_id
22d_conv = config.mamba_d_conv
23mamba_n_heads = config.mamba_n_heads
24mamba_d_head = config.mamba_d_head
25mamba_d_state = config.mamba_d_state
26mamba_n_groups = config.mamba_n_groups
27mamba_expand = config.mamba_expand
28hidden_size = config.hidden_size
29conv_d_inner = (mamba_expand * hidden_size) + (2 * mamba_n_groups * mamba_d_state)
30
31# 2. Prepare inputs
32## Define messages
33messages = [
34 { "role": "user", "content": "What is the capital of France?" },
35]
36inputs = tokenizer.apply_chat_template(messages, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="np")
37input_ids = inputs['input_ids']
38attention_mask = inputs['attention_mask']
39batch_size = input_ids.shape[0]
40num_logits_to_keep = np.array(1, dtype=np.int64)
41
42## Initialize cache
43cache = {}
44for i, layer_type in enumerate(config.layer_types):
45 if layer_type == "attention":
46 for kv in ('key', 'value'):
47 cache[f'past_key_values.{i}.{kv}'] = np.zeros([batch_size, num_key_value_heads, 0, head_dim], dtype=dtype)
48 elif layer_type == "mamba":
49 cache[f'past_conv.{i}'] = np.zeros([batch_size, conv_d_inner, d_conv], dtype=dtype)
50 cache[f'past_ssm.{i}'] = np.zeros([batch_size, mamba_n_heads, mamba_d_head, mamba_d_state], dtype=dtype)
51
52# 3. Generation loop
53max_new_tokens = 1024
54generated_tokens = np.array([[]], dtype=np.int64)
55for i in range(max_new_tokens):
56 feed_dict = dict(
57 input_ids=input_ids,
58 attention_mask=attention_mask,
59 num_logits_to_keep=num_logits_to_keep,
60 )
61 outputs = decoder_session.run(None, feed_dict | cache)
62 named_outputs = dict(zip(output_names, outputs))
63
64 ## Update values for next generation loop
65 input_ids = outputs[0][:, -1].argmax(-1, keepdims=True)
66 attention_mask = np.concatenate([attention_mask, np.ones_like(input_ids, dtype=np.int64)], axis=-1)
67
68 for name in cache:
69 new_name = name.replace('past_key_values', 'present').replace('past_', 'present_')
70 cache[name] = named_outputs[new_name]
71
72 generated_tokens = np.concatenate([generated_tokens, input_ids], axis=-1)
73 if (input_ids == eos_token_id).all():
74 break
75
76 ## (Optional) Streaming
77 print(tokenizer.decode(input_ids[0]), end='', flush=True)
78print()
79
80# 4. Output result
81print(tokenizer.batch_decode(generated_tokens, skip_special_tokens=True)[0])