nghodki commited on
Commit
cf9284c
·
verified ·
1 Parent(s): f98bb3d

Upload 2 files

Browse files
Files changed (2) hide show
  1. code/inference.py +226 -0
  2. code/requirements.txt +2 -0
code/inference.py ADDED
@@ -0,0 +1,226 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import time
2
+
3
+ from transformers import (
4
+ AutoModelForCausalLM,
5
+ AutoTokenizer,
6
+ BitsAndBytesConfig,
7
+ pipeline,
8
+ logging,
9
+ )
10
+ import torch
11
+ import json
12
+ import re
13
+
14
+ # Activate 4-bit precision base model loading
15
+ use_4bit = True
16
+
17
+ # Compute dtype for 4-bit base models
18
+ bnb_4bit_compute_dtype = "float16"
19
+
20
+ # Quantization type (fp4 or nf4)
21
+ bnb_4bit_quant_type = "nf4"
22
+
23
+ use_nested_quant = False
24
+
25
+ # Load the entire model on the GPU 0
26
+ device_map = {"": 0}
27
+
28
+ compute_dtype = getattr(torch, bnb_4bit_compute_dtype)
29
+
30
+ bnb_config = BitsAndBytesConfig(
31
+ load_in_4bit=use_4bit,
32
+ bnb_4bit_quant_type=bnb_4bit_quant_type,
33
+ bnb_4bit_compute_dtype=compute_dtype,
34
+ bnb_4bit_use_double_quant=use_nested_quant,
35
+ )
36
+ model_name = "cjsanjay/llama-3-8B-gorilla-meraki_v2"
37
+ model = AutoModelForCausalLM.from_pretrained(
38
+ model_name,
39
+ quantization_config=bnb_config,
40
+ device_map=device_map
41
+ )
42
+ # Load LLaMA tokenizer
43
+ tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
44
+ tokenizer.pad_token = tokenizer.eos_token
45
+ tokenizer.padding_side = "right"
46
+ # tokenizer.add_tokens(["<START_Q>", "<END_Q>", "<START_A>", "<END_A>"], special_tokens=True)
47
+
48
+ logging.set_verbosity(logging.CRITICAL)
49
+
50
+
51
+ # model.resize_token_embeddings(len(tokenizer))
52
+
53
+
54
+ # def get_question_prompt_old(data):
55
+ # instruction = f"### Instruction\n{data['Instruction']}"
56
+ # context = f"### Context\n{data['Functions']}" if len(data["Functions"]) > 0 else None
57
+ # # join all the parts together
58
+ # prompt = "\n\n".join([i for i in [instruction, context] if i is not None])
59
+ # return prompt
60
+ #
61
+ #
62
+ # # def generate_prompt_for_llama3(data):
63
+ # # system = "You are an AI programming assistant, utilizing the finetuned LLM model you only answer questions related to function calling using the provided functions. For politically sensitive questions, security and privacy issues, and other non-computer science questions, you will refuse to answer."
64
+ # # output_string = json.dumps(data['Output'])
65
+ # # functions_string = json.dumps(data['Functions'])
66
+ # # prompt = f"""<|start_header_id|>system<|end_header_id|> {system}\n### Instruction: <<functions>> {functions_string} <|eot_id|><|start_header_id|>user<|end_header_id|> This is the question: {data['Instruction']}<|eot_id|><|start_header_id|>assistant<|end_header_id|> {output_string}<|eot_id|>"""
67
+ # # return prompt
68
+ #
69
+ #
70
+ # def generate_prompt_for_llama3_test(data):
71
+ #
72
+ # functions_string = json.dumps(data['Functions'])
73
+ # prompt = f"""<|start_header_id|>system<|end_header_id|> {system}\n### Instruction: <<functions>> {functions_string} <|eot_id|><|start_header_id|>user<|end_header_id|> This is the question: {data['Instruction']}<|eot_id|><|start_header_id|>assistant<|end_header_id|>"""
74
+ # return prompt
75
+ #
76
+ with open('meraki_full_unknown_fn_dataset_llama_v1.json', 'r') as json_file:
77
+ known_test_dataset_gorilla = json.load(json_file)
78
+
79
+ matched = 0
80
+ skipped = 0
81
+ failed = 0
82
+ total = len(known_test_dataset_gorilla)
83
+ failed_questions = []
84
+ skipped_questions = []
85
+ accuracy = {}
86
+ i = 0
87
+ processed_questions = []
88
+ pattern = r'<|im_start|>assistant(.*?)(?:<|im_end|>|$)'
89
+ system = ("You are an AI programming assistant, utilizing the finetuned LLM model you only answer questions related to "
90
+ "function calling using the provided functions. For politically sensitive questions, security and privacy "
91
+ "issues, and other non-computer science questions, you will refuse to answer. Use ")
92
+
93
+
94
+ def extract_assistant_function_response(r_patter, generated_text):
95
+ """
96
+
97
+ :param r_patter:
98
+ :param generated_text:
99
+ :return:
100
+ """
101
+ m_result = re.findall(pattern, seq['generated_text'], re.DOTALL)
102
+ # # Remove leading and trailing whitespace from the matches
103
+ m_result = [match.strip() for match in m_result]
104
+ for match in m_result:
105
+ if match.find("api_name") > -1:
106
+ return match.strip()
107
+
108
+ return None
109
+
110
+
111
+ for d in known_test_dataset_gorilla:
112
+ i += 1
113
+ # prompt = generate_prompt_for_llama3_test(d)
114
+ # tokenized_input = tokenizer.tokenize(prompt)
115
+ # if len(tokenized_input) > 4096:
116
+ # skipped += 1
117
+ # skipped_questions.append(d)
118
+ # print (f"Skipped: {i}, token_size: {len(tokenized_input)}")
119
+ # continue
120
+ functions_string = json.dumps(d['Functions'])
121
+ messages = [
122
+ {"role": "system", "content": f"{system}\n### Instruction: <<functions>> {functions_string}"},
123
+ {"role": "user", "content": d['Instruction']},
124
+ ]
125
+ processed_questions.append(d)
126
+ pipeline1 = pipeline(
127
+ "text-generation",
128
+ model=model,
129
+ model_kwargs={"torch_dtype": torch.bfloat16},
130
+ device_map="auto",
131
+ tokenizer=tokenizer
132
+ )
133
+ prompt = pipeline1.tokenizer.apply_chat_template(
134
+ messages,
135
+ tokenize=False,
136
+ add_generation_prompt=True
137
+ )
138
+ terminators = [
139
+ pipeline1.tokenizer.eos_token_id,
140
+ pipeline1.tokenizer.convert_tokens_to_ids("<|eot_id|>")
141
+ ]
142
+ outputs = pipeline1(
143
+ prompt,
144
+ max_new_tokens=512,
145
+ eos_token_id=terminators,
146
+ do_sample=True,
147
+ temperature=0.6,
148
+ top_p=0.9,
149
+ )
150
+ final_assistant_response = None
151
+ assistant_raw_response = ""
152
+ for seq in outputs:
153
+ assistant_raw_response = seq['generated_text']
154
+ final_assistant_response = extract_assistant_function_response(pattern, seq['generated_text'])
155
+ try:
156
+ if final_assistant_response is None:
157
+ d["GotOutput"] = str(assistant_raw_response)
158
+ failed_questions.append(d)
159
+ failed += 1
160
+ print(f"Improper response from assistant Expected: {d['Output']}, Got: {assistant_raw_response}")
161
+ output_data = final_assistant_response
162
+ try:
163
+ output_data_json = json.loads(final_assistant_response)
164
+ if "arguments" in output_data_json:
165
+ try:
166
+ arg_dict_ans = json.loads(output_data_json["arguments"].replace("'", '"').replace("True", "true").replace("False", "false"))
167
+ arg_dict_input = json.loads(d["Output"]["arguments"].replace("'", '"').replace("True", "true").replace("False", "false"))
168
+ except Exception as ex:
169
+ print (f"Json loading failed for args string: {str(ex)}, Falling back to string comparison, args_string: {output_data_json['arguments']}")
170
+ raise
171
+ if output_data_json["api_name"] == d["Output"]["api_name"] and arg_dict_ans == arg_dict_input:
172
+ matched += 1
173
+ print ("Matched")
174
+ else:
175
+ d["GotOutput"] = str(output_data)
176
+ failed_questions.append(d)
177
+ failed += 1
178
+ print(f"JSON mismatch Expected: {d['Output']}, Got: {output_data_json}")
179
+ else:
180
+ if output_data_json == d["Output"]:
181
+ matched += 1
182
+ print ("Matched")
183
+ else:
184
+ d["GotOutput"] = str(output_data)
185
+ failed_questions.append(d)
186
+ failed += 1
187
+ print(f"JSON mismatch Expected: {d['Output']}, Got: {output_data_json}")
188
+ except Exception as ex:
189
+ print (f"Json loading failed: {str(ex)}, Falling back to string comparison")
190
+ if str(output_data) == str(d["Output"]):
191
+ matched += 1
192
+ print ("Matched")
193
+ else:
194
+ d["GotOutput"] = str(output_data)
195
+ failed_questions.append(d)
196
+ failed += 1
197
+ print(f"Expected: {d['Output']}, Got: {output_data}")
198
+ except Exception as ex:
199
+ print(f"Expected: {d['Output']}, Got: {output_data}, error: {str(ex)}")
200
+ failed_questions.append(d)
201
+ failed += 1
202
+
203
+ del pipeline1
204
+ del outputs
205
+ pipeline1 = None
206
+ outputs = None
207
+ with torch.no_grad():
208
+ torch.cuda.empty_cache()
209
+ print(f"Done: {i}/{total}, Skipped: {skipped}, matched: {matched}, failed: {failed}")
210
+ if len(processed_questions) >= 100:
211
+ break
212
+ time.sleep(1)
213
+ input()
214
+
215
+ accuracy["matched"] = matched
216
+ accuracy["total"] = total - skipped
217
+ accuracy["recall"] = float(accuracy["matched"])/accuracy["total"]
218
+
219
+ with open("failed_questions_meraki_unknown_test_dataset_llama3_gorilla.json", "w") as f:
220
+ json.dump(failed_questions, f, indent=4)
221
+
222
+ with open("skipped_questions_meraki_unknown_test_dataset_llama3_gorilla.json", "w") as f:
223
+ json.dump(skipped_questions, f, indent=4)
224
+
225
+ with open("accuracy_meraki_unknown_test_dataset_llama3_gorilla", "w") as f:
226
+ json.dump(accuracy, f, indent=4)
code/requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ torch
2
+ transformers