Spaces:
Runtime error
Runtime error
File size: 23,452 Bytes
11fa0f1 |
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 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 |
#!/usr/bin/env python
# coding=utf-8
'''
This script is used to reformat the downloaded datasets into the format that can be used by the model.
Here we use jsonl for the converted data. Each line in the jsonl file is a json object formatted as follows:
{
"dataset": "dataset_name",
"id": "unique_id",
"messages": [
{"role": "system", "content": "message_text"}, # optional
{"role": "user", "content": "message_text"},
{"role": "assistant", "content": "message_text"},
{"role": "user", "content": "message_text"},
{"role": "assistant", "content": "message_text"},
...
],
}
'''
import json
import random
import re
import os
import pandas as pd
import argparse
from instruction_encode_templates import encode_instruction_example, encode_few_shot_example
def convert_super_ni_data(data_dir, output_dir, zero_shot_examples_per_task=60, few_shot_examples_per_task=20, n_few_shot=2):
os.makedirs(output_dir, exist_ok=True)
train_tasks = []
with open(os.path.join(data_dir, "splits", "xlingual", "train_tasks.txt"), "r") as fin:
for line in fin:
if not "_mmmlu_" in line: # skip mmlu to avoid test leakage
train_tasks.append(line.strip())
with open(os.path.join(output_dir, "super_ni_data.jsonl"), "w") as fout:
for task in train_tasks:
with open(os.path.join(data_dir, "tasks", f"{task}.json"), "r") as fin:
task_data = json.load(fin)
instruction = task_data["Definition"][0]
if zero_shot_examples_per_task + few_shot_examples_per_task < len(task_data["Instances"]):
instances = random.sample(task_data["Instances"], k=zero_shot_examples_per_task+few_shot_examples_per_task)
else:
instances = task_data["Instances"]
for instance in instances[:zero_shot_examples_per_task]:
encoded_example = encode_instruction_example(
instruction=instruction,
input=instance["input"],
output=instance["output"][0],
random_template=True,
eos_token=None
)
fout.write(json.dumps({
"dataset": "super_ni",
"id": f"super_ni_{instance['id']}",
"messages": [
{"role": "user", "content": encoded_example["prompt"]},
{"role": "assistant", "content": encoded_example["completion"]},
]
}) + "\n")
for instance in instances[zero_shot_examples_per_task:]:
if n_few_shot < len(task_data["Positive Examples"]):
examplars = random.sample(task_data["Positive Examples"], k=n_few_shot)
else:
examplars = task_data["Positive Examples"]
encoded_example = encode_few_shot_example(
instruction=instruction,
examplars=examplars,
input=instance["input"],
output=instance["output"][0],
eos_token=None
)
fout.write(json.dumps({
"dataset": "super_ni",
"id": f"super_ni_{instance['id']}",
"messages": [
{"role": "user", "content": encoded_example["prompt"]},
{"role": "assistant", "content": encoded_example["completion"]},
]
}) + "\n")
def convert_cot_data(data_dir, output_dir, num_zero_shot_examples=50000, num_few_shot_examples=50000):
os.makedirs(output_dir, exist_ok=True)
examples = []
if num_few_shot_examples > 0:
with open(os.path.join(data_dir, "cot_zsopt.jsonl"), "r") as fin:
zero_shot_examples = [json.loads(line) for line in fin]
if num_zero_shot_examples < len(zero_shot_examples):
zero_shot_examples = random.sample(zero_shot_examples, k=num_zero_shot_examples)
examples.extend(zero_shot_examples)
if num_few_shot_examples > 0:
with open(os.path.join(data_dir, "cot_fsopt.jsonl"), "r") as fin:
few_shot_examples = [json.loads(line) for line in fin]
if num_few_shot_examples < len(few_shot_examples):
few_shot_examples = random.sample(few_shot_examples, k=num_few_shot_examples)
examples.extend(few_shot_examples)
output_path = os.path.join(output_dir, "cot_data.jsonl")
with open(output_path, "w") as fout:
for idx, example in enumerate(examples):
prompt = example["inputs"]
if not prompt.endswith("\n") and not prompt.rstrip().endswith(":"):
prompt += "\n"
completion = example["targets"]
fout.write(json.dumps({
"dataset": "cot",
"id": f"cot_{idx}",
"messages": [
{"role": "user", "content": prompt},
{"role": "assistant", "content": completion},
]
}) + "\n")
def convert_flan_v2_data(data_dir, output_dir):
os.makedirs(output_dir, exist_ok=True)
examples = []
with open(os.path.join(data_dir, "flan_v2_resampled_100k.jsonl"), "r") as fin:
for line in fin:
examples.append(json.loads(line))
output_path = os.path.join(output_dir, "flan_v2_data.jsonl")
with open(output_path, "w") as fout:
for idx, example in enumerate(examples):
prompt = example["inputs"]
if not prompt.endswith("\n") and not prompt.rstrip().endswith(":"):
prompt += "\n"
completion = example["targets"]
fout.write(json.dumps({
"dataset": "flan_v2",
"id": f"flan_v2_{idx}",
"messages": [
{"role": "user", "content": prompt},
{"role": "assistant", "content": completion},
]
}) + "\n")
def convert_dolly_data(data_dir, output_dir):
os.makedirs(output_dir, exist_ok=True)
examples = []
with open(os.path.join(data_dir, "databricks-dolly-15k.jsonl"), "r") as fin:
for line in fin:
examples.append(json.loads(line))
output_path = os.path.join(output_dir, "dolly_data.jsonl")
with open(output_path, "w") as fout:
for idx, example in enumerate(examples):
encoded_example = encode_instruction_example(
instruction=example["instruction"],
input=example["context"],
output=example["response"],
random_template=True,
eos_token=None
)
fout.write(json.dumps({
"dataset": "dolly",
"id": f"dolly_{idx}",
"messages": [
{"role": "user", "content": encoded_example["prompt"]},
{"role": "assistant", "content": encoded_example["completion"]},
]
}) + "\n")
def convert_self_instruct_data(data_dir, output_dir):
os.makedirs(output_dir, exist_ok=True)
examples = []
with open(os.path.join(data_dir, "all_instances_82K.jsonl"), "r") as fin:
for line in fin:
examples.append(json.loads(line))
output_path = os.path.join(output_dir, "self_instruct_data.jsonl")
with open(output_path, "w") as fout:
for idx, example in enumerate(examples):
encoded_example = encode_instruction_example(
instruction=example["instruction"],
input=example["input"],
output=example["output"],
random_template=True,
eos_token=None
)
fout.write(json.dumps({
"dataset": "self_instruct",
"id": f"self_instruct_{idx}",
"messages": [
{"role": "user", "content": encoded_example["prompt"]},
{"role": "assistant", "content": encoded_example["completion"]},
]
}) + "\n")
def convert_unnatural_instructions_data(data_dir, output_dir):
os.makedirs(output_dir, exist_ok=True)
instance_cnt = 0
with open(os.path.join(data_dir, "core_data.jsonl"), "r") as fin, open((os.path.join(output_dir, "unnatural_instructions_data.jsonl")), "w") as fout:
for line in fin:
task_data = json.loads(line)
instruction = task_data["instruction"]
for instance in task_data["instances"]:
if instance["constraints"] and instance["constraints"].lower() not in ["none", "none."]:
instance_instruction = instruction + "\n" + instance["constraints"]
else:
instance_instruction = instruction
encoded_example = encode_instruction_example(
instruction=instance_instruction,
input=instance["input"],
output=instance["output"],
random_template=True,
eos_token=None
)
fout.write(json.dumps({
"dataset": "unnatural_instructions",
"id": f"unnatural_instructions_{instance_cnt}",
"messages": [
{"role": "user", "content": encoded_example["prompt"]},
{"role": "assistant", "content": encoded_example["completion"]},
]
}) + "\n")
instance_cnt += 1
def convert_stanford_alpaca_data(data_dir, output_dir):
os.makedirs(output_dir, exist_ok=True)
examples = []
with open(os.path.join(data_dir, "alpaca_data.json"), "r") as fin:
examples.extend(json.load(fin))
output_path = os.path.join(output_dir, "stanford_alpaca_data.jsonl")
with open(output_path, "w") as fout:
for idx, example in enumerate(examples):
encoded_example = encode_instruction_example(
instruction=example["instruction"],
input=example["input"],
output=example["output"],
random_template=True,
eos_token=None
)
fout.write(json.dumps({
"dataset": "stanford_alpaca",
"id": f"stanford_alpaca_{idx}",
"messages": [
{"role": "user", "content": encoded_example["prompt"]},
{"role": "assistant", "content": encoded_example["completion"]},
]
}) + "\n")
def convert_code_alpaca_data(data_dir, output_dir):
os.makedirs(output_dir, exist_ok=True)
examples = []
with open(os.path.join(data_dir, "code_alpaca_20k.json"), "r") as fin:
examples.extend(json.load(fin))
output_path = os.path.join(output_dir, "code_alpaca_data.jsonl")
with open(output_path, "w") as fout:
for idx, example in enumerate(examples):
encoded_example = encode_instruction_example(
instruction=example["instruction"],
input=example["input"],
output=example["output"],
random_template=True,
eos_token=None
)
fout.write(json.dumps({
"dataset": "code_alpaca",
"id": f"code_alpaca_{idx}",
"messages": [
{"role": "user", "content": encoded_example["prompt"]},
{"role": "assistant", "content": encoded_example["completion"]},
]
}) + "\n")
def convert_gpt4_alpaca_data(data_dir, output_dir, load_en=True, load_zh=False):
os.makedirs(output_dir, exist_ok=True)
examples = []
if load_en:
with open(os.path.join(data_dir, "alpaca_gpt4_data.json"), "r") as fin:
examples.extend(json.load(fin))
if load_zh:
with open(os.path.join(data_dir, "alpaca_gpt4_data_zh.json"), "r") as fin:
examples.extend(json.load(fin))
output_path = os.path.join(output_dir, "gpt4_alpaca_data.jsonl")
with open(output_path, "w") as fout:
for idx, example in enumerate(examples):
encoded_example = encode_instruction_example(
instruction=example["instruction"],
input=example["input"],
output=example["output"],
random_template=True,
eos_token=None
)
fout.write(json.dumps({
"dataset": "gpt4_alpaca",
"id": f"gpt4_alpaca_{idx}",
"messages": [
{"role": "user", "content": encoded_example["prompt"]},
{"role": "assistant", "content": encoded_example["completion"]},
]
}) + "\n")
def convert_sharegpt_data(data_dir, output_dir):
os.makedirs(output_dir, exist_ok=True)
examples = []
with open(os.path.join(data_dir, "sharegpt_html_cleaned_and_split.json"), "r") as fin:
examples.extend(json.load(fin))
output_path = os.path.join(output_dir, "sharegpt_data.jsonl")
with open(output_path, "w") as fout:
invalid_cnt = 0
for idx, example in enumerate(examples):
messages = []
valid = True
for message in example["conversations"]:
if message["from"] == "human" or message["from"] == "user":
messages.append({
"role": "user",
"content": message["value"]
})
elif message["from"] == "gpt" or message["from"] == "chatgpt":
messages.append({
"role": "assistant",
"content": message["value"]
})
elif message["from"] == "system":
valid = False
invalid_cnt += 1
break
elif message["from"] == "bing":
valid = False
invalid_cnt += 1
break
else:
raise ValueError(f"Unknown message sender: {message['from']}")
if messages and valid:
fout.write(json.dumps({
"dataset": "sharegpt",
"id": f"sharegpt_{example['id']}",
"messages": messages
}) + "\n")
print(f"# of invalid examples in sharegpt data: {invalid_cnt}")
def convert_baize_data(data_dir, output_dir):
os.makedirs(output_dir, exist_ok=True)
examples = []
for source in ["alpaca", "medical", "quora", "stackoverflow"]:
with open(os.path.join(data_dir, f"{source}_chat_data.json"), "r") as fin:
examples.extend(json.load(fin))
output_path = os.path.join(output_dir, "baize_data.jsonl")
with open(output_path, "w") as fout:
for idx, example in enumerate(examples):
# split example["input"] by [|Human|] and [|AI|]
messages = []
rounds = example["input"].split("[|Human|]")[1:]
for round in rounds:
if not round.strip() or "[|AI|]" not in round:
continue
human, assistant = round.split("[|AI|]")
messages.append({
"role": "user",
"content": human.strip()
})
messages.append({
"role": "assistant",
"content": assistant.strip()
})
fout.write(json.dumps({
"dataset": "baize",
"id": f"baize_{idx}",
"messages": messages
}) + "\n")
def convert_oasst1_data(data_dir, output_dir):
'''
For OASST1, because it's in a tree structure, where every user input might get multiple replies,
we have to save every path from the root node to the assistant reply (including both leaf node and intemediate node).
This results in some of the messages being duplicated among different paths (instances).
Be careful when using this dataset for training. Ideally, you should only minimize the loss of the last message in each path.
'''
os.makedirs(output_dir, exist_ok=True)
conversations = []
with open(os.path.join(data_dir, "2023-04-12_oasst_ready.trees.jsonl"), "r") as fin:
for line in fin:
conversations.append(json.loads(line))
output_path = os.path.join(output_dir, "oasst1_data.jsonl")
# we filter out the sequences that mention the creator information
filter_strings = [
"LAION",
"Open Asssistant",
"OpenAssistant",
]
# tranvers the conversation tree, and collect all valid sequences
def dfs(reply, messages, valid_sequences):
if any([filter_string in reply["text"] for filter_string in filter_strings]):
return
if reply["role"] == "assistant":
messages.append(
{"role": "assistant", "content": reply["text"]}
)
if not reply["replies"]: # leaf node
valid_sequences.append(messages[:])
else:
for child in reply["replies"]:
dfs(child, messages, valid_sequences)
messages.pop()
elif reply["role"] == "prompter":
messages.append(
{"role": "user", "content": reply["text"]}
)
for child in reply["replies"]:
dfs(child, messages, valid_sequences)
messages.pop()
else:
raise ValueError(f"Unknown role: {reply['role']}")
with open(output_path, "w") as fout:
example_cnt = 0
for _, conversation in enumerate(conversations):
valid_sequences = []
dfs(conversation["prompt"], [], valid_sequences)
for sequence in valid_sequences:
fout.write(json.dumps({
"dataset": "oasst1",
"id": f"oasst1_{example_cnt}",
"messages": sequence
}) + "\n")
example_cnt += 1
def convert_lima_data(data_dir, output_dir):
os.makedirs(output_dir, exist_ok=True)
examples = []
with open(os.path.join(data_dir, "train.jsonl"), "r") as fin:
for line in fin:
examples.append(json.loads(line))
output_path = os.path.join(output_dir, "lima_data.jsonl")
with open(output_path, "w") as fout:
for idx, example in enumerate(examples):
messages = []
if not len(example["conversations"]) % 2 == 0:
print(f"Waring: example {idx} in LIMA has odd number of messages. Cutting off the last message.")
example["conversations"] = example["conversations"][:-1]
for i in range(0, len(example["conversations"]), 2):
messages.append({
"role": "user",
"content": example["conversations"][i]
})
messages.append({
"role": "assistant",
"content": example["conversations"][i+1]
})
fout.write(json.dumps({
"dataset": "lima",
"id": f"lima_{idx}",
"messages": messages,
}) + "\n")
def convert_wizardlm_data(data_dir, output_dir):
os.makedirs(output_dir, exist_ok=True)
examples = []
with open(os.path.join(data_dir, "WizardLM_evol_instruct_V2_143k.json"), "r") as fin:
examples = json.load(fin)
output_path = os.path.join(output_dir, "wizardlm_data.jsonl")
with open(output_path, "w") as fout:
for idx, example in enumerate(examples):
messages = []
assert len(example["conversations"]) % 2 == 0
for i in range(0, len(example["conversations"]), 2):
assert example["conversations"][i]["from"] == "human"
assert example["conversations"][i+1]["from"] == "gpt"
messages.append({
"role": "user",
"content": example["conversations"][i]["value"]
})
messages.append({
"role": "assistant",
"content": example["conversations"][i+1]["value"]
})
fout.write(json.dumps({
"dataset": "wizardlm",
"id": f"wizardlm_{example['idx']}",
"messages": messages,
}) + "\n")
def convert_open_orca_data(data_dir, output_dir, num_gpt4_examples=100000, num_gpt35_examples=0):
os.makedirs(output_dir, exist_ok=True)
examples = []
df = pd.read_parquet(os.path.join(data_dir, "1M-GPT4-Augmented.parquet"))
gpt4_examples = [row.to_dict() for _, row in df.iterrows()]
random.shuffle(gpt4_examples)
examples.extend(gpt4_examples[:num_gpt4_examples])
df = pd.read_parquet(os.path.join(data_dir, "3_5M-GPT3_5-Augmented.parquet"))
gpt35_examples = [row.to_dict() for _, row in df.iterrows()]
random.shuffle(gpt35_examples)
examples.extend(gpt35_examples[:num_gpt35_examples])
output_path = os.path.join(output_dir, "open_orca_data.jsonl")
with open(output_path, "w") as fout:
for idx, example in enumerate(examples):
messages = [
{"role": "system", "content": example["system_prompt"]},
{"role": "user", "content": example["question"]},
{"role": "assistant", "content": example["response"]}
]
fout.write(json.dumps({
"dataset": "open_orca",
"id": f"open_orca_{example['id']}",
"messages": messages,
}) + "\n")
if __name__ == "__main__":
arg_parser = argparse.ArgumentParser()
arg_parser.add_argument("--raw_data_dir", type=str, default="data/downloads")
arg_parser.add_argument("--output_dir", type=str, default="data/processed")
arg_parser.add_argument("--seed", type=int, default=42)
args = arg_parser.parse_args()
random.seed(args.seed)
# get the subfolder names in raw_data_dir
subfolders = [f for f in os.listdir(args.raw_data_dir) if os.path.isdir(os.path.join(args.raw_data_dir, f))]
# all supported datasets
supported_datasets = []
all_funcs = [func_name for func_name in globals() if callable(globals()[func_name])]
for func_name in all_funcs:
if re.match(r"convert_.+_data", func_name):
supported_datasets.append(func_name[8:-5])
# check if the subfolder names are supported datasets
valid_subfolders = []
for subfolder in subfolders:
if subfolder not in supported_datasets:
print(f"Warning: {subfolder} in the raw data folder is not a supported dataset. We will skip it.")
else:
valid_subfolders.append(subfolder)
# prepare data for each dataset
statistics = {}
for subfolder in valid_subfolders:
print(f"Processing {subfolder} data...")
globals()[f"convert_{subfolder}_data"](os.path.join(args.raw_data_dir, subfolder), os.path.join(args.output_dir, subfolder))
|