ericsorides commited on
Commit
06a0d51
·
verified ·
1 Parent(s): 7b599e4

Create README.md

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