vwxyzjn commited on
Commit
951106b
1 Parent(s): 0b75507

Upload create_dataset.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. create_dataset.py +150 -0
create_dataset.py ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ from collections import defaultdict
3
+ from dataclasses import dataclass
4
+ import json
5
+ import random
6
+ import pandas as pd
7
+ from inference_swarm import InferenceSwarm, InferenceSwarmConfig
8
+ from huggingface_hub import AsyncInferenceClient
9
+ from transformers import AutoTokenizer, HfArgumentParser
10
+ from tqdm.asyncio import tqdm_asyncio
11
+ from datasets import load_dataset, Dataset
12
+ import time
13
+ from huggingface_hub import HfApi
14
+
15
+ api = HfApi()
16
+
17
+
18
+ @dataclass
19
+ class Args:
20
+ max_samples: int = 128
21
+ """The maximum umber of samples to generate (use -1 for all))"""
22
+ max_new_tokens: int = 1500
23
+ """Max new tokens"""
24
+ temperature: float = 1.0
25
+ """Generation temperature"""
26
+ constitution_path: str = "examples/hh/constitution.json"
27
+ """Path to the constitution"""
28
+ repo_id: str = "cai-conversation-dev"
29
+ """The repo id to push to"""
30
+ timestamp: bool = True
31
+ """Whether to add a timestamp to the repo_id"""
32
+ push_to_hub: bool = False
33
+ """Whether to push to hub"""
34
+
35
+
36
+ parser = HfArgumentParser((Args, InferenceSwarmConfig))
37
+ args, isc = parser.parse_args_into_dataclasses()
38
+ if args.timestamp:
39
+ args.repo_id += str(int(time.time()))
40
+ tokenizer = AutoTokenizer.from_pretrained("mistralai/Mistral-7B-Instruct-v0.1")
41
+ tokenizer.add_special_tokens({"sep_token": "", "cls_token": "", "mask_token": "", "pad_token": "[PAD]"})
42
+ with open(args.constitution_path) as f:
43
+ data = json.load(f)
44
+ constitutions = data["constitutions"]
45
+ system_chat = data["system_chat"]
46
+ system_chat = [item for sublist in system_chat for item in sublist]
47
+ ds = load_dataset("Anthropic/hh-rlhf", data_dir="harmless-base")
48
+ for key in ds:
49
+ max_samples = len(ds[key]) if args.max_samples == -1 else args.max_samples
50
+ ds[key] = ds[key].select(range(max_samples))
51
+
52
+
53
+ def extract(example):
54
+ # Extract the "Human:" prompts
55
+ example = example["chosen"]
56
+ split_text = example.split("\n\n")
57
+ for segment in split_text:
58
+ if "Human:" in segment:
59
+ return {"prompt": segment.split(": ")[1]}
60
+
61
+
62
+ ds = ds.map(extract)
63
+ ds.remove_columns(["chosen", "rejected"])
64
+ rate_limit = 500 * isc.instances
65
+ semaphore = asyncio.Semaphore(rate_limit)
66
+ with InferenceSwarm(isc) as inference_swarm:
67
+ client = AsyncInferenceClient(model=inference_swarm.endpoint)
68
+ STOP_SEQ = ["User:", "###", "<|endoftext|>"]
69
+
70
+ async def process_text(split, i, task):
71
+ chat = system_chat.copy()
72
+ constitution = random.choice(constitutions)
73
+ token_length = 0
74
+ row = {}
75
+ for prompt, prompt_key, response_key in [
76
+ (task, "init_prompt", "init_response"),
77
+ (constitution["critic"], "critic_prompt", "critic_response"),
78
+ (constitution["revision"], "revision_prompt", "revision_response"),
79
+ ]:
80
+ async with semaphore:
81
+ prompt_dict = {"role": "user", "content": prompt}
82
+ chat.append(prompt_dict)
83
+ completion = await client.text_generation(
84
+ prompt=tokenizer.apply_chat_template(chat, tokenize=False),
85
+ max_new_tokens=args.max_new_tokens,
86
+ stop_sequences=STOP_SEQ,
87
+ temperature=args.temperature,
88
+ )
89
+ for stop_seq in STOP_SEQ:
90
+ if completion.endswith(stop_seq):
91
+ completion = completion[: -len(stop_seq)].rstrip()
92
+ response_dict = {"role": "assistant", "content": completion}
93
+ chat.append(response_dict)
94
+ token_length += len(tokenizer.encode(completion))
95
+ row[prompt_key] = prompt
96
+ row[response_key] = completion
97
+ return split, i, token_length, row
98
+
99
+ async def main():
100
+ start_time = time.time()
101
+ tasks = [process_text(split, idx, row["prompt"]) for split in ds for idx, row in enumerate(ds[split])]
102
+ print(f"WARNING: the first generation can hang like this for up to 1 hour because it will finish the first two turns of conversation of the entire dataset")
103
+ results = await tqdm_asyncio.gather(*tasks)
104
+ end_time = time.time()
105
+
106
+ total_duration = end_time - start_time
107
+ total_tokens = sum(result[2] for result in results)
108
+ overall_tokens_per_second = total_tokens / total_duration if total_duration > 0 else 0
109
+ print(f"Overall Tokens per Second: {overall_tokens_per_second}")
110
+ all_ds = defaultdict(lambda: defaultdict(list))
111
+ for result in results:
112
+ [all_ds[result[0]][key].append(value) for key, value in result[3].items()]
113
+
114
+ def process(example):
115
+ return {
116
+ "prompt": example["init_prompt"].strip(),
117
+ "messages": [
118
+ {"role": "user", "content": example["init_prompt"].strip()},
119
+ {"role": "assistant", "content": example["revision_response"].strip()},
120
+ ],
121
+ "chosen": [
122
+ {"role": "user", "content": example["init_prompt"].strip()},
123
+ {"role": "assistant", "content": example["revision_response"].strip()},
124
+ ],
125
+ "rejected": [
126
+ {"role": "user", "content": example["init_prompt"].strip()},
127
+ {"role": "assistant", "content": example["init_response"].strip()},
128
+ ],
129
+ }
130
+
131
+ for split in all_ds:
132
+ df = pd.DataFrame(all_ds[split])
133
+ print("=" * 10 + split + "=" * 10)
134
+ print(df)
135
+ post_ds = Dataset.from_dict(all_ds[split])
136
+ post_ds = post_ds.map(process)
137
+ if args.push_to_hub:
138
+ post_ds.select(range(len(post_ds) // 2)).push_to_hub(args.repo_id, split=f"{split}_sft")
139
+ post_ds.select(range(len(post_ds) // 2, len(post_ds))).push_to_hub(args.repo_id, split=f"{split}_prefs")
140
+ if "/" not in args.repo_id: # find the current user
141
+ repo_id = f"{api.whoami()['name']}/{args.repo_id}"
142
+ for file, name in zip([__file__, args.constitution_path], ["create_dataset.py", "constitution.json"]):
143
+ api.upload_file(
144
+ path_or_fileobj=file,
145
+ path_in_repo=name,
146
+ repo_id=repo_id,
147
+ repo_type="dataset",
148
+ )
149
+
150
+ asyncio.run(main())