ericsorides commited on
Commit
7d10df3
·
verified ·
1 Parent(s): c3962b4

Create README.md

Browse files
Files changed (1) hide show
  1. README.md +139 -0
README.md ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ tags:
3
+ - text-generation-inference
4
+ - phi3
5
+ - 4-bit precision
6
+ - AWQ
7
+ base_model:
8
+ - microsoft/Phi-3-mini-4k-instruct
9
+ ---
10
+
11
+ # Phi 3 mini 4k instruct instruct with Key-Value-Cache enabled in ONNX AWQ (4-bit) format
12
+ - Model creator: [Microsoft](https://huggingface.co/microsoft)
13
+ - Original model: [Phi 3 mini 4k instruct](https://huggingface.co/microsoft/Phi-3-mini-4k-instruct)
14
+
15
+ <!-- description start -->
16
+ ## Description
17
+
18
+ This repo contains the ONNX files of the ONNX conversion of Phi 3 mini 4k instruct instruct done by Esperanto Technologies.
19
+ The model is in the 4-bit format quantized with AWQ and has the KVC enabled.
20
+
21
+ ### About AWQ
22
+
23
+ AWQ is an efficient, accurate and blazing-fast low-bit weight quantization method, currently supporting 4-bit quantization. Compared to GPTQ, it offers faster Transformers-based inference with equivalent or better quality compared to the most commonly used GPTQ settings.
24
+ More here: [AutoAWQ](https://github.com/casper-hansen/AutoAWQ)
25
+
26
+ <!-- description end -->
27
+
28
+ ## How to download ONNX model and weight files
29
+
30
+ The easiest way to obtain the model is to clone this whole repo.
31
+ Alternatively you can download the files is using the `huggingface-hub` Python library.
32
+
33
+ ```shell
34
+ pip3 install huggingface-hub>=0.17.1
35
+ ```
36
+
37
+ Then you can download any individual model file to the current directory, at high speed, with a command like this:
38
+
39
+ ```shell
40
+ huggingface-cli download Esperanto/phi3-mini-4k-instruct-kvc-AWQ-int4-onnx --local-dir phi3-mini-4k-instruct-kvc-AWQ-int4-onnx --local-dir-use-symlinks False
41
+ ```
42
+
43
+ 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).
44
+
45
+ ## How to run from Python code using ONNXRuntime
46
+
47
+ This model can easily be ran in a CPU using [ONNXRuntime](https://onnxruntime.ai/).
48
+
49
+ #### First install the packages
50
+
51
+ ```bash
52
+ pip3 install onnx==1.16.1
53
+ pip3 install onnxruntime==1.17.1
54
+ ```
55
+
56
+ #### Example code: generate text with this model
57
+
58
+ We define the loop with greedy decoding:
59
+ ```python
60
+ import numpy as np
61
+ import onnxruntime
62
+ import onnx
63
+ from transformers import AutoTokenizer
64
+ def generate_text(model_path, prompt, tokenizer, max_gen_tokens, total_sequence, window, context):
65
+ model = onnx.load(model_path)
66
+ #we create the inputs for the first iteration
67
+ input_tensor = tokenizer(prompt, return_tensors="pt")
68
+ prompt_size = len(input_tensor['input_ids'][0])
69
+ actual_input = input_tensor['input_ids']
70
+ if prompt_size < window:
71
+ actual_input = np.concatenate((tokenizer.bos_token_id*np.ones([1, window - prompt_size], dtype = 'int64'),
72
+ actual_input), axis=1)
73
+ if prompt_size + max_gen_tokens > total_sequence:
74
+ print("ERROR: Longer total sequence is needed!")
75
+ return
76
+ first_attention = np.concatenate((np.zeros([1, total_sequence - window], dtype = 'int64'),
77
+ np.ones((1, window), dtype = 'int64')), axis=1)
78
+ max_gen_tokens += prompt_size #we need to generate on top of parsing the prompt
79
+ inputs_names =[node.name for node in model.graph.input]
80
+ output_names =[node.name for node in model.graph.output]
81
+ n_heads = 32 #gqa-heads of the kvc
82
+ inputs_dict = {}
83
+ inputs_dict['input_ids'] = actual_input[:, :window].reshape(1, window).numpy()
84
+ inputs_dict['attention_mask'] = first_attention
85
+ for name in inputs_names:
86
+ if name == 'input_ids' or name == 'attention_mask': continue
87
+ inputs_dict[name] = np.zeros([1, n_heads, context-window, 96], dtype="float16")
88
+ index = 0
89
+ new_token = np.array([10])
90
+ next_index = window
91
+ old_j = 0
92
+ total_input = actual_input.numpy()
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
+ answer = tokenizer.decode(total_input[0], skip_special_tokens=True, clean_up_tokenization_spaces=False)
121
+ return answer
122
+ ```
123
+ We now run the inferences:
124
+
125
+ ```python
126
+ tokenizer = AutoTokenizer.from_pretrained("Esperanto/phi3-mini-4k-instruct-kvc-AWQ-int4-onnx")
127
+ model_path = "phi3-mini-4k-instruct-kvc-AWQ-int4-onnx/model.onnx"
128
+ max_gen_tokens = 20 #number of tokens we want tog eneral
129
+ total_sequence = 128 #total sequence_length
130
+ context = 1024 #the context to extend the kvc
131
+ window = 16 #number of tokens we want to parse at the time
132
+ messages = [
133
+ {"role": "system", "content": "You are a pirate chatbot who always responds in pirate speak!"},
134
+ {"role": "user", "content": "Who are you?"},
135
+ ]
136
+ prompt = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
137
+ generated = generate_text(model_path, prompt, tokenizer, max_gen_tokens, total_sequence, window, context)
138
+ print(generated)
139
+ ```