ericsorides commited on
Commit
8924b53
1 Parent(s): 2299968

Create README.md

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