ericsorides commited on
Commit
c56c180
1 Parent(s): f3ebb3c

Create README.md

Browse files
Files changed (1) hide show
  1. README.md +143 -0
README.md ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ pipeline_tag: text-generation
3
+ license: apache-2.0
4
+ library_name: transformers
5
+ tags:
6
+ - language
7
+ - granite-3.0
8
+ base_model:
9
+ - ibm-granite/granite-3.0-2b-instruct
10
+ ---
11
+
12
+
13
+ # Granite 3.0 2b instruct with Key-Value-Cache enabled in ONNX fp16 format
14
+ - Model creator: [IBM-Granite](https://huggingface.co/ibm-granite)
15
+ - Original model: [IBM-Granite Granite 3.0 2b instruct](https://huggingface.co/ibm-granite/granite-3.0-2b-instruct)
16
+
17
+ <!-- description start -->
18
+ ## Description
19
+
20
+ This repo contains the ONNX files for the ONNX conversion of Granite 3.0 2b instruct done by Esperanto Technologies.
21
+ The model is in the fp16 format and has the KVC enabled.
22
+
23
+ <!-- description end -->
24
+
25
+ ## How to download ONNX model and weight files
26
+
27
+ The easiest way to obtain the model is to clone this whole repo.
28
+ Alternatively you can download the files is using the `huggingface-hub` Python library.
29
+
30
+ ```shell
31
+ pip3 install huggingface-hub>=0.17.1
32
+ ```
33
+
34
+ Then you can download any individual model file to the current directory, at high speed, with a command like this:
35
+
36
+ ```shell
37
+ huggingface-cli download Esperanto/granite-3.0-2b-instruct-fp16-onnx --local-dir granite-3.0-2b-instruct-fp16-onnx --local-dir-use-symlinks False
38
+ ```
39
+
40
+ For more documentation on downloading with `huggingface-cli`, please see: [HF -> Hub Python Library -> Download files -> Download from the CLI](https://huggingface.co/docs/huggingface_hub/guides/download#download-from-the-cli).
41
+
42
+ ## How to run from Python code using ONNXRuntime
43
+
44
+ This model can easily be ran in a CPU using [ONNXRuntime](https://onnxruntime.ai/).
45
+
46
+ #### First install the packages
47
+
48
+ ```bash
49
+ pip3 install onnx==1.16.1
50
+ pip3 install onnxruntime==1.17.1
51
+ ```
52
+
53
+ #### Example code: generate text with this model
54
+
55
+ We define the loop with greedy decoding:
56
+ ```python
57
+ import numpy as np
58
+ import onnxruntime
59
+ import onnx
60
+ from transformers import AutoTokenizer
61
+
62
+ def generate_text(model_path, prompt, tokenizer, max_gen_tokens, total_sequence, window, context):
63
+ model = onnx.load(model_path)
64
+
65
+ #we create the inputs for the first iteration
66
+ input_tensor = tokenizer(prompt, return_tensors="pt")
67
+ prompt_size = len(input_tensor['input_ids'][0])
68
+ actual_input = input_tensor['input_ids']
69
+ if prompt_size < window:
70
+ actual_input = np.concatenate((tokenizer.bos_token_id*np.ones([1, window - prompt_size], dtype = 'int64'),
71
+ actual_input), axis=1)
72
+ if prompt_size + max_gen_tokens > total_sequence:
73
+ print("ERROR: Longer total sequence is needed!")
74
+ return
75
+ first_attention = np.concatenate((np.zeros([1, total_sequence - window], dtype = 'int64'),
76
+ np.ones((1, window), dtype = 'int64')), axis=1)
77
+ max_gen_tokens += prompt_size #we need to generate on top of parsing the prompt
78
+ inputs_names =[node.name for node in model.graph.input]
79
+ output_names =[node.name for node in model.graph.output]
80
+ n_heads = 8 #gqa-heads of the kvc
81
+ inputs_dict = {}
82
+ inputs_dict['input_ids'] = actual_input[:, :window].reshape(1, window).numpy()
83
+ inputs_dict['attention_mask'] = first_attention
84
+ for name in inputs_names:
85
+ if name == 'input_ids' or name == 'attention_mask': continue
86
+ inputs_dict[name] = np.zeros([1, n_heads, context-window, 64], dtype="float16")
87
+ index = 0
88
+ new_token = np.array([10])
89
+ next_index = window
90
+ old_j = 0
91
+ total_input = actual_input.numpy()
92
+
93
+ rt_session = onnxruntime.InferenceSession(model_path)
94
+ ## We run the inferences
95
+ while next_index < max_gen_tokens:
96
+ if new_token.any() == tokenizer.eos_token_id:
97
+ break
98
+ #inference
99
+ output = rt_session.run(output_names, inputs_dict)
100
+ outs_dictionary = {name: content for (name, content) in zip (output_names, output)}
101
+ #we prepare the inputs for the next inference
102
+ for name in inputs_names:
103
+ if name == 'input_ids':
104
+ old_j = next_index
105
+ if next_index < prompt_size:
106
+ if prompt_size - next_index >= window: next_index += window
107
+ else: next_index = prompt_size
108
+ j = next_index - window
109
+ else:
110
+ next_index +=1
111
+ j = next_index - window
112
+ new_token = outs_dictionary['logits'].argmax(-1).reshape(1, window)
113
+ total_input = np.concatenate((total_input, new_token[: , -1:]), axis = 1)
114
+ inputs_dict['input_ids']= total_input[:, j:next_index].reshape(1, window)
115
+ elif name == 'attention_mask':
116
+ inputs_dict['attention_mask'] = np.concatenate((np.zeros((1, total_sequence-next_index), dtype = 'int64'), np.ones((1, next_index), dtype = 'int64')), axis=1)
117
+ else:
118
+ old_name = name.replace("past_key_values", "present")
119
+ inputs_dict[name] = outs_dictionary[old_name][:, :, next_index-old_j:context-window+(next_index - old_j), :]
120
+
121
+ answer = tokenizer.decode(total_input[0], skip_special_tokens=True, clean_up_tokenization_spaces=False)
122
+ return answer
123
+ ```
124
+ We now run the inferences:
125
+
126
+ ```python
127
+ tokenizer = AutoTokenizer.from_pretrained("Esperanto/granite-3.0-2b-instruct-fp16-onnx")
128
+ model_path = "granite-3.0-2b-instruct-fp16-onnx/model.onnx"
129
+
130
+ max_gen_tokens = 20 #number of tokens we want tog eneral
131
+ total_sequence = 128 #total sequence_length
132
+ context = 1024 #the context to extend the kvc
133
+ window = 16 #number of tokens we want to parse at the time
134
+ messages = [
135
+ {"role": "system", "content": "You are a pirate chatbot who always responds in pirate speak!"},
136
+ {"role": "user", "content": "Who are you?"},
137
+ ]
138
+
139
+ prompt = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
140
+
141
+ generated = generate_text(model_path, prompt, tokenizer, max_gen_tokens, total_sequence, window, context)
142
+ print(generated)
143
+ ```