/
create_chat_set.py
232 lines (205 loc) · 7.71 KB
/
create_chat_set.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
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
import json
import sys
import random
from datasets import load_dataset
from tqdm import tqdm
BAD_SS = (
" ул. ",
" +7",
"Как ИИ",
"как ИИ",
"Как модель ИИ",
"как модель ИИ",
"как языковая модель ИИ",
"Как языковая модель ИИ",
"как искусственный интеллект",
"Как искусственный интеллект",
"Я - искусственный интеллект",
"я - искусственный интеллект",
"Я являюсь искусственным интеллектом",
"я являюсь искусственным интеллектом",
"я искусственный интеллект",
"OpenAI",
"ChatGPT",
"OpenAssistant",
"Ася",
"as a language model"
)
def has_bad_ss(messages):
for m in messages:
text = m["content"]
if any(ss in text for ss in BAD_SS):
return True
return False
def revert_flattening(records):
fixed_records = []
for key, values in records.items():
if not fixed_records:
fixed_records = [{} for _ in range(len(values))]
for i, value in enumerate(values):
fixed_records[i][key] = value
return fixed_records
def calc_max_length(records):
return max([sum([len(m["content"]) for m in r["messages"]]) for r in records])
def build_char_system_messages(char):
name = char["name"]
context = char["context"]
greeting = char["greeting"]
example_dialogue = char["example_dialogue"]
context = f"Ты {name}. {context}"
chat = []
if random.random() < 0.2:
context += f"\nПриветствие: {greeting}"
chat.append({
"role": "bot",
"content": greeting
})
if random.random() < 0.2:
mapping = {
"user": "Пользователь",
"char": "Персонаж"
}
example_messages = [f'{mapping[m["role"]]}: {m["content"]}' for m in example_dialogue]
context += "\nПример диалога:\n" + "\n".join(example_messages)
chat.insert(0, {
"role": "system",
"content": context
})
return chat
def main(train_path, val_path):
records = []
for row in tqdm(load_dataset("IlyaGusev/gpt_roleplay_realm", split="ru")):
name = row["name"]
context = row["context"]
greeting = row["greeting"]
example_dialogue = row["example_dialogue"]
for dialogue in row["dialogues"]:
chat = dialogue["chat"]
for message in chat:
if message["role"] == "char":
message["role"] = "bot"
if message["role"] == "operator":
message["role"] = "user"
system_messages = build_char_system_messages(row)
chat = system_messages + chat
records.append({
"messages": chat,
"source": "roleplay"
})
print("Roleplay count:", len(records))
for row in tqdm(load_dataset("IlyaGusev/ru_turbo_saiga", split="train")):
messages = revert_flattening(row["messages"])
if has_bad_ss(messages):
continue
records.append({
"messages": messages,
"source": "saiga"
})
print("Saiga count:", len(records))
print("Max Saiga length:", calc_max_length(records))
alpaca_records = []
for row in tqdm(load_dataset("IlyaGusev/ru_turbo_alpaca", split="train")):
message = row["instruction"]
if row["input"]:
message += "\nДано: " + row["input"]
output = row["alternative_output"]
if has_bad_ss([{"content": output}]):
output = row["output"]
if has_bad_ss([{"content": output}]):
continue
alpaca_records.append({
"messages": [
{"role": "user", "content": message},
{"role": "bot", "content": output}
],
"source": "alpaca"
})
print("Alpaca count:", len(alpaca_records))
print("Max Alpaca length:", calc_max_length(alpaca_records))
merged_alpaca_records = []
prev_record_idx = None
for idx, record in enumerate(alpaca_records):
text_length = sum([len(m["content"]) for m in record["messages"]])
if text_length > 1000:
merged_alpaca_records.append(record)
continue
if prev_record_idx is None:
prev_record_idx = idx
continue
messages = alpaca_records[prev_record_idx]["messages"] + record["messages"]
merged_alpaca_records.append({
"messages": messages,
"source": "merged_alpaca"
})
prev_record_idx = None
print("Merged Alpaca count:", len(merged_alpaca_records))
print("Max Merged Alpaca length:", calc_max_length(alpaca_records))
alpaca_records = merged_alpaca_records
excluded_indices = set()
for record in tqdm(alpaca_records):
text_length = sum([len(m["content"]) for m in record["messages"]])
if text_length > 1500 or random.random() < 0.5:
records.append(record)
continue
index = random.randrange(len(records))
while index in excluded_indices:
index = random.randrange(len(records))
excluded_indices.add(index)
records[index]["source"] = "mixed"
records[index]["messages"] += record["messages"]
print("Saiga + Alpaca count:", len(records))
print("Max Saiga + Alpaca length:", calc_max_length(records))
for row in tqdm(load_dataset("IlyaGusev/ru_sharegpt_cleaned", split="train")):
messages = revert_flattening(row["messages"])
text_length = sum([len(m["content"]) for m in messages])
while text_length > 10000 and messages:
messages = messages[:-2]
text_length = sum([len(m["content"]) for m in messages])
if not messages:
continue
records.append({
"messages": messages,
"source": "sharegpt"
})
print("Saiga + Alpaca + ShareGPT count:", len(records))
print("Saiga + Alpaca + ShareGPT max length:", calc_max_length(records))
for row in tqdm(load_dataset("IlyaGusev/oasst1_ru_main_branch", split="train")):
messages = revert_flattening(row["messages"])
text_length = sum([len(m["content"]) for m in messages])
while text_length > 10000 and messages:
messages = messages[:-2]
text_length = sum([len(m["content"]) for m in messages])
if not messages:
continue
records.append({
"messages": messages,
"source": "oasst"
})
print("All count:", len(records))
print("All max length:", calc_max_length(records))
cleaned_records = []
for record in records:
messages = record["messages"]
roles = {m["role"] for m in messages}
for role in roles:
assert role in ("bot", "user", "system"), role
if has_bad_ss(messages):
continue
if not record["messages"]:
continue
cleaned_records.append(record)
records = cleaned_records
print("All count after cleaning:", len(records))
random.shuffle(records)
border = int(0.95 * len(records))
train_records = records[:border]
val_records = records[border:]
with open(train_path, "w") as w:
for record in train_records:
w.write(json.dumps(record, ensure_ascii=False).strip() + "\n")
with open(val_path, "w") as w:
for record in val_records:
w.write(json.dumps(record, ensure_ascii=False).strip() + "\n")
train_path = sys.argv[1]
val_path = sys.argv[2]
main(train_path, val_path)