-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmulti_turn.py
203 lines (163 loc) · 6.05 KB
/
multi_turn.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
import json
import os
import warnings
from argparse import ArgumentParser
from typing import Dict, List
from collections import defaultdict
from tqdm import tqdm
from src.data import HFDepthQALoader, filter_data_dict, slice_data_dict
from src.model import VLLM
from src.utils import (
SAMPLING_PARAMS,
SYSTEM_PROMPT_ZERO_SHOT,
USER_PROMPT_TEMPLATE_ZERO_SHOT,
USER_PROMPT_TEMPLATE_LAST_TURN,
get_output_path,
show_random_inputs,
)
DEBUG = False
def multiturn_completions(
model,
inputs: List[str],
tokenizer,
total_len
):
system_prompt = SYSTEM_PROMPT_ZERO_SHOT
chat_dict = defaultdict(str)
# Adjust batch size to fit the number of inputs
# VLLM supports adaptive batch size already
total_len = len(inputs)
# Process initial batches with progress bar
print("Processing initial chat...")
for i in tqdm(
range(0, len(inputs)), total=total_len, desc="Initial Chat"
):
chat_input = inputs[i]
for j, inst in enumerate(chat_input):
if j == 0:
input_ = apply_template_chat(system_prompt, inst["input"], tokenizer)
else:
input_.append({"role": "user", "content": inst["input"]})
if inst["id"] in chat_dict:
input_.append({"role": "assistant", "content": chat_dict[inst["id"]]})
continue
tokenized_input = tokenizer.apply_chat_template(
input_, tokenize=False, add_generation_prompt=True)
output = model.completions([tokenized_input], **SAMPLING_PARAMS)
chat_dict[inst["id"]] = output[0]
input_.append({"role": "assistant", "content": output[0]})
# Final aggregation and printing
outputs_len = len(chat_dict)
print(f"Processed {outputs_len} / {total_len} instances.")
if outputs_len < total_len:
warnings.warn("Some instances failed.")
warnings.warn("They will be written as None in the output file.")
raise Exception(
f"Failed to generate feedback for {total_len - outputs_len} instances."
)
return chat_dict
def apply_template_chat(system_prompt, user_prompt, tokenizer):
if tokenizer.chat_template and "system" not in tokenizer.chat_template:
messages = [
{"role": "user", "content": system_prompt + "\n" + user_prompt},
]
else:
messages = [
{"role": "system", "content": system_prompt},
{"role": "user", "content": user_prompt},
]
return messages
def prepare_inputs_multiturn(
questions: Dict[str, Dict],
nodes: Dict[str, Dict],
node_to_q: Dict[str, str]
) -> List[str]:
chat_inputs = []
for nodeid, node in nodes.items():
chat = []
target_question_d = questions[node_to_q[nodeid]]
target_question = target_question_d["question"]
for predec_nodeid in node["direct_predecessors"]:
predec_question_d = questions[node_to_q[predec_nodeid]]
predec_question = predec_question_d["question"]
user_prompt = USER_PROMPT_TEMPLATE_ZERO_SHOT.format(question=predec_question)
chat.append({"id":predec_nodeid, "input": user_prompt})
last_user_prompt = USER_PROMPT_TEMPLATE_LAST_TURN.format(question=target_question)
chat.append({"id": nodeid, "input": last_user_prompt})
chat_inputs.append(chat)
return chat_inputs
def main(args):
global DEBUG
DEBUG = args.debug
# Load data
dataloader = HFDepthQALoader()
questions, nodes, node_to_q = dataloader.load_data()
print(f"Loaded {len(questions)} questions and {len(nodes)} nodes.")
# Load model
model = VLLM(args.model_name, num_gpus=args.num_gpus)
tokenizer = model.get_tokenizer()
nodes = filter_data_dict(nodes, lambda node: node["depth"] > 1)
if DEBUG:
nodes = slice_data_dict(nodes, start=0, end=5)
inputs = prepare_inputs_multiturn(
questions,
nodes,
node_to_q
)
if DEBUG:
inputs = inputs[:5]
# Inference
predictions = multiturn_completions(model, inputs, tokenizer, len(node_to_q))
# Save results
results = {}
for idx, nodeid in enumerate(predictions.keys()):
results[nodeid] = questions[node_to_q[nodeid]]
results[nodeid].update({"predicted_answer": predictions[nodeid]})
output_path = get_output_path(
output_file=args.output_file, default_output_dir="../../outputs/inference"
)
with open(output_path, "w") as f:
json.dump(results, f, indent=4)
if __name__ == "__main__":
parser = ArgumentParser()
# I/O arguments
parser.add_argument(
"--model_name",
type=str,
required=True,
help="Name of model hosted in Hugging Face under AutoModelForCausalLM",
)
parser.add_argument(
"--input",
type=str,
default="kaist-ai/DepthQA",
help="Dataset name in Hugging Face (for zero-shot) or local zero-shot JSON output file (for prompt-*)",
)
parser.add_argument(
"--output_file",
type=str,
required=True,
help="Output JSON file name. Unless the parent directory is specified, will be saved under outputs/inference by default.",
)
parser.add_argument(
"--force_rerun",
action="store_true",
help="Force rerun even if output file exists.",
)
parser.add_argument("--debug", action="store_true", help="Debug mode.")
# Compute arguments
parser.add_argument(
"--num_gpus",
type=int,
default=2,
help="Number of GPUs to use for inference. Note that we use bfloat16 if available and float16 otherwise.",
)
args = parser.parse_args()
assert args.output_file.endswith(".json"), "Output file must be a JSON file."
output_path = get_output_path(
output_file=args.output_file, default_output_dir="../../outputs/inference"
)
assert not (
os.path.exists(output_path) and not args.force_rerun
), f"Output file {output_path} already exists. Skipping inference."
main(args)