ericsorides commited on
Commit
5b54b9b
·
verified ·
1 Parent(s): bc7adeb

Create README.md

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