-
Notifications
You must be signed in to change notification settings - Fork 0
/
training_data_collecting_openai.py
323 lines (261 loc) · 10.9 KB
/
training_data_collecting_openai.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
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
"""
======================================================================
TRAINING_DATA_COLLECTING_OPENAI ---
Collecting Training Data from OpenAI's APIs
Author: Zi Liang <zi1415926.liang@connect.polyu.hk>
Copyright © 2024, ZiLiang, all rights reserved.
Created: 23 February 2024
======================================================================
"""
# ------------------------ Code --------------------------------------
import torch
from datasets import load_dataset
from openai import OpenAI as oa
# import time
import json
from collections import OrderedDict
import os
from math import exp
import random
import pickle
from tqdm import tqdm
client = oa()
def chatWithOpenAI_APIs(modelname="gpt-3.5-turbo-1106",
prompt="",
utter="",
):
res = client.chat.completions.create(
model=modelname,
# prompt=f"Instruction: {prompt}. User: {utter}. System: ",
messages=[
{"role": "system", "content": "Instruction: " + prompt},
{"role": "user", "content": utter}
]
)
# time.sleep(1)
return res.choices[0].message.content
def chatWithOpenAI__LogLogits(modelname="gpt-3.5-turbo-1106",
messages=[],
num_top_logprobs=5):
# empty_prefix=[{"role":"system","content":""},]
# empty_prefix.extend(messages)
# print("messages: ",messages)
# print(type(messages[0]))
res = client.chat.completions.create(
model=modelname,
messages=messages,
logprobs=True,
top_logprobs=num_top_logprobs,
)
# print("Inference Results: ",res)
generated_text = res.choices[0].message.content
logprobs = res.choices[0].logprobs.content
# print("-----------------------")
return generated_text, logprobs
def obtain_beginning_sents():
dataset_name = "Anthropic/hh-rlhf"
dataset = load_dataset(dataset_name, split="train")["chosen"]
split_word = " Assistant: "
extracted_beggin_sents = []
for d in dataset:
if split_word not in d:
continue
else:
utterance = d.split(split_word)[0]
extracted_beggin_sents.append(utterance)
if not os.path.exists("./intermediate_data"):
os.makedirs("./intermediate_data")
with open("./intermediate_data/extracted_biggin_sentence.json",
'w', encoding='utf8') as f:
json.dump(extracted_beggin_sents,
f, ensure_ascii=False, indent=4)
return extracted_beggin_sents
def free_sampled_utterance_by_Prompts(
model="gpt-3.5-turbo-1106",
num=10,
):
prompt = "Suppose you are a user. Please generate one utterance (a question) to begin the dialogue."
utter_ls = []
for _ in range(num):
res = chatWithOpenAI_APIs(model, prompt, prompt)
utter_ls.append(res)
if not os.path.exists("./intermediate_data"):
os.makedirs("./intermediate_data")
with open(f"./intermediate_data/{model}_{num}_free_gen.json",
'w', encoding='utf8') as f:
json.dump(utter_ls,
f, ensure_ascii=False, indent=4)
return utter_ls
def chatting_to_generate_positive_dialogues(
utter,
modelname="gpt-3.5-turbo-1106",
L=10):
dialogue = [
{"role": "user", "content": utter}
]
for _ in range(L):
res = client.chat.completions.create(
model=modelname,
# prompt=f"Instruction: {prompt}. User: {utter}. System: ",
messages=dialogue)
resp = res.choices[0].message.content
role = "assistant"
if dialogue[-1]["role"] == "user":
dialogue.append({
"role": role,
"content": resp,
})
return dialogue
def generate_training_data(
chatting_method="anthropic",
):
if chatting_method == "anthropic":
utterls = obtain_beginning_sents()
elif chatting_method == "free":
utterls = free_sampled_utterance_by_Prompts(num=15)
# then generate the training dataset.
dialogue_ls = []
for utter in utterls:
dialogue = chatting_to_generate_positive_dialogues(utter)
dialogue_ls.append(dialogue)
if not os.path.exists("./intermediate_data"):
os.makedirs("./intermediate_data")
with open(f"./intermediate_data/{chatting_method}Positive_set.json",
'w', encoding='utf8') as f:
json.dump(dialogue_ls,
f, ensure_ascii=False, indent=4)
return dialogue_ls
def load_raw_train_datals(lm_tokenizer, max_length=1024):
dataset_name = "Anthropic/hh-rlhf"
trainset_text = load_dataset(dataset_name, split="train")
trainset_text = trainset_text["chosen"][:100]
data = lm_tokenizer(trainset_text,
padding="longest",
truncation=True,
max_length=max_length,
return_tensors="pt"
).input_ids
return data
def load_steal_datals(lm_tokenizer,
model_name="gpt-3.5-turbo-1106",
topk=5,
max_length=1024,
openai_tmp_save_pth="./ultrachat2k_openai_probs_res1.pickle",
):
V = lm_tokenizer.vocab_size
dataset_name = "HuggingFaceH4/ultrachat_200k"
trainset_text = load_dataset(dataset_name, split="train_sft[:1]")
prompts = trainset_text["prompt"]
prompts = [f"###User: {x} ###Assistant: " for x in prompts]
p_idxls = lm_tokenizer(prompts,
padding="longest",
truncation=True,
max_length=max_length,
return_tensors="pt"
).input_ids
messages = trainset_text["messages"]
# messages=[x[1] for x in messages]
if not os.path.exists(openai_tmp_save_pth):
print("RUNNING ChatGPT Stealing...")
text2ls = []
idx2_dist_ls=[]
probsls = []
iii_bgn=0
for q in tqdm(messages, desc="ChatGPT Inference:"):
qd=[{"role":"user",
"content":q[0]["content"]}]
res = chatWithOpenAI__LogLogits(
model_name,
qd,
topk,
)
resp, logprb=res
bgn_idx = lm_tokenizer([resp],
padding="longest",
truncation=True,
max_length=max_length,
return_tensors="pt"
).input_ids[0][0]
idx2=p_idxls[iii_bgn].tolist()
logits_distr = torch.nn.functional.one_hot(
p_idxls[iii_bgn][1:],
num_classes=V,
).float()
idx2_dist=[[x,] for x in idx2]
for i in range(len(idx2_dist)):
for _ in range(topk-1):
idxxx=random.randint(0, V-1)
idx2_dist[i].append(idxxx)
idx2_dist=idx2_dist[1:]
# print(logits_distr.shape)
# logits_distr=logits_distr[torch.tensor(idx2_dist,
# dtype=torch.long)]
logits_distr=torch.gather(logits_distr, 1,
torch.tensor(idx2_dist,
dtype=torch.long))
logits_distr=[logits_distr[i]\
for i in range(len(logits_distr))]
for i, topkdict in enumerate(logprb):
selected_token = topkdict.token
subtokens = lm_tokenizer.tokenize(selected_token)
sub_idxes=lm_tokenizer.convert_tokens_to_ids(subtokens)
idx2.extend(sub_idxes)
topk_tokens = [x.token for x in topkdict.top_logprobs]
topk_subtokenss = [lm_tokenizer.tokenize(x)
for x in topk_tokens]
topk_subidxes = [lm_tokenizer.convert_tokens_to_ids(x)
for x in topk_subtokenss]
topk_logits = [x.logprob
for x in topkdict.top_logprobs]
# topk_logits = [exp(x) for x in topk_logits]
# idx2_dist.extend(topk_subidxes)
# logits_distr.extend(topk_logits)
for j in range(len(subtokens)):
dist = torch.zeros(topk)
idx2_tmp_token_dist=torch.zeros(topk,
dtype=torch.long)
dist = torch.tensor(topk_logits)
for k, subidx in enumerate(topk_subidxes):
if len(subidx)<=j:
idx2_tmp_token_dist[k]=subidx[0]
else:
idx2_tmp_token_dist[k]=subidx[j]
logits_distr.append(dist)
idx2_dist.append(idx2_tmp_token_dist)
# print(len(idx2), len(logits_distr))
assert len(idx2) == len(logits_distr)+1
probsls.append(logits_distr)
text2ls.append(idx2)
idx2_dist_ls.append(idx2_dist)
with open(openai_tmp_save_pth,
'wb') as f:
pickle.dump([text2ls, probsls, idx2_dist_ls],
f,)
else:
print("Directly Loading...")
# from collections import OrderedDict
with open(openai_tmp_save_pth, 'rb') as f:
data = pickle.load(f,)
text2ls = data[0]
probsls = data[1]
idx2_dist_ls = data[2]
return p_idxls, text2ls, probsls, idx2_dist_ls
def most_vanilla_anthropicModel():
dataset_name = "Anthropic/hh-rlhf"
train_set = load_dataset(dataset_name, split="train")
test_set = load_dataset(dataset_name, split="test")
return train_set, test_set
def main():
pass
# running entry
if __name__ == "__main__":
# main()
# res=chatWithOpenAI_APIs(prompt="1",utter="1")
# ms=[{'content': "These instructions apply to section-based themes (Responsive 6.0+, Retina 4.0+, Parallax 3.0+ Turbo 2.0+, Mobilia 5.0+). What theme version am I using?\nOn your Collections pages & Featured Collections sections, you can easily show the secondary image of a product on hover by enabling one of the theme's built-in settings!\nYour Collection pages & Featured Collections sections will now display the secondary product image just by hovering over that product image thumbnail.\nDoes this feature apply to all sections of the theme or just specific ones as listed in the text material?", 'role': 'user'}]
# res=chatWithOpenAI__LogLogits(messages=ms)
# print(res)
from transformers import AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained("google/gemma-2b")
raw_train_datals = load_steal_datals(tokenizer,
max_length=1024)
print("EVERYTHING DONE.")