-
Notifications
You must be signed in to change notification settings - Fork 10
/
tokenize_dataset_rows.py
70 lines (57 loc) · 2.11 KB
/
tokenize_dataset_rows.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
#!python
# -*- coding: utf-8 -*-
# @author: Kun
'''
Author: Kun
Date: 2023-04-19 01:00:19
LastEditTime: 2023-04-19 01:00:27
LastEditors: Kun
Description:
FilePath: /ChatGLM-LoRA-RLHF-PyTorch/tokenize_dataset_rows.py
'''
"""
https://github.com/mymusise/ChatGLM-Tuning
"""
import argparse
import json
from tqdm import tqdm
import datasets
import transformers
def preprocess(tokenizer, config, example, max_seq_length):
prompt = example["context"]
target = example["target"]
prompt_ids = tokenizer.encode(prompt, max_length=max_seq_length, truncation=True)
target_ids = tokenizer.encode(
target,
max_length=max_seq_length,
truncation=True,
add_special_tokens=False)
input_ids = prompt_ids + target_ids + [config.eos_token_id]
return {"input_ids": input_ids, "seq_len": len(prompt_ids)}
def read_jsonl(path, max_seq_length, skip_overlength=False):
model_name = "THUDM/chatglm-6b"
tokenizer = transformers.AutoTokenizer.from_pretrained(
model_name, trust_remote_code=True)
config = transformers.AutoConfig.from_pretrained(
model_name, trust_remote_code=True, device_map='auto')
with open(path, "r") as f:
for line in tqdm(f.readlines()):
example = json.loads(line)
feature = preprocess(tokenizer, config, example, max_seq_length)
if skip_overlength and len(feature["input_ids"]) > max_seq_length:
continue
feature["input_ids"] = feature["input_ids"][:max_seq_length]
yield feature
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--jsonl_path", type=str, default="data/alpaca_data.jsonl")
parser.add_argument("--save_path", type=str, default="data/alpaca")
parser.add_argument("--max_seq_length", type=int, default=384)
parser.add_argument("--skip_overlength", type=bool, default=False)
args = parser.parse_args()
dataset = datasets.Dataset.from_generator(
lambda: read_jsonl(args.jsonl_path, args.max_seq_length, args.skip_overlength)
)
dataset.save_to_disk(args.save_path)
if __name__ == "__main__":
main()