-
Notifications
You must be signed in to change notification settings - Fork 0
/
distributed_generate.py
190 lines (171 loc) · 8.23 KB
/
distributed_generate.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
import os
import logging
import time
import datetime
import torch
import torch.distributed as dist
import transformers.utils as transformer_utils
import multiprocessing as mp
from pythia.utils.mmap_dataset import MMapIndexedDataset
from transformers import GPTNeoXForCausalLM
import argparse
from utils import *
import pdb
def generate_dataset(args, start_seq_idx, end_seq_idx, mp_queue, prefetch_max=128):
prefix = 'undeduped_merge/document.bin'
if "deduped" in args.model:
prefix = 'deduped_merge/document.bin'
print(prefix)
print("Building dataset")
mmap_ds = MMapIndexedDataset(prefix, skip_warmup=True)
context_tokens = []
true_continuation = []
i = 0
for i in range(start_seq_idx, end_seq_idx + 1, args.batch_size):
if i + args.batch_size > end_seq_idx:
data = mmap_ds[i:end_seq_idx+1]
else:
data = mmap_ds[i:i + args.batch_size]
context_tokens.extend(data[:, :args.context_size].tolist())
true_continuation.extend(data[:, args.context_size:args.context_size+args.continuation_size].tolist())
i += len(context_tokens)
if len(context_tokens) == args.batch_size:
# (start index of batch, context tokens, true continuation)
mp_queue.put((
i - len(context_tokens),
context_tokens, true_continuation))
context_tokens = []
true_continuation = []
while mp_queue.qsize() > prefetch_max:
time.sleep(0.05)
if len(context_tokens) > 0:
mp_queue.put((i - len(context_tokens), context_tokens, true_continuation))
context_tokens = []
true_continuation = []
mp_queue.put((None, None, None))
def score(model, context_tokens, true_continuation, context_size, continuation_size):
"""Calculate memorization score from context tokens and true continuation
Performs greedy generation from context tokens and calculates memorization score
Args:
model (transformers.GPTNeoXForCausalLM): Pythia model instance being evaluated
context_tokens (torch.Tensor): Context token indicies of shape (batch_size, 32)
true_continuation (torch.Tensor): True continuation indicies of shape (batch_size, 32)
Returns:
accuracies (torch.Tensor): Accuracies of shape (batch_size,)
"""
with torch.no_grad():
context_tokens = torch.tensor(context_tokens).to('cuda')
true_continuation = torch.tensor(true_continuation).to('cuda')
generations = model.generate(context_tokens, temperature = 0.0, top_k = 0, top_p = 0, max_length = context_size+continuation_size, min_length = context_size+continuation_size)
accuracies = (true_continuation == generations[:,context_size:context_size+continuation_size]).float().mean(axis=-1)
return accuracies.cpu()
def main():
paser = argparse.ArgumentParser()
paser.add_argument("--batch_size", type=int, default=1024)
paser.add_argument("--context_size", type=int, default=32)
paser.add_argument("--continuation_size", type=int, default=16)
paser.add_argument("--model", type=str, default="1b-deduped-v0")
paser.add_argument("--checkpoint", type=int, default=143000)
paser.add_argument("--specific_rank", type=int, default=1)
paser.add_argument("--total_ranks", type=int, default=64)
args = paser.parse_args()
print(args)
RANK = int(os.environ['RANK'])
LOCAL_RANK = int(os.environ['LOCAL_RANK'])
NUM_PROCS = int(os.environ['WORLD_SIZE'])
logging.basicConfig(format = f'rank-{RANK}:' + '%(levelname)s:%(message)s', level = logging.INFO)
logging.info(f"Initializing torch distributed with gpus {torch.cuda.device_count()}")
print("start")
print(f"Rank: {RANK}")
print(f"World Size: {NUM_PROCS}")
print(f"Local Rank: {LOCAL_RANK}")
torch.cuda.set_device(LOCAL_RANK)
dist.init_process_group(
"nccl",
world_size=NUM_PROCS,
rank=RANK
)
#store = dist.TCPStore(os.environ['MASTER_ADDR'], port=29504,
# world_size=NUM_PROCS, is_master=RANK == 0, timeout=datetime.timedelta(hours=3))
dist.barrier()
transformer_utils.logging.set_verbosity_error()
# Calculate start and end sequence indicies
total_num_sequences = args.checkpoint * 1024
num_sequences_per_proc = total_num_sequences // NUM_PROCS
if f"memorization_evals_{args.model}_{args.context_size}_{args.context_size + args.continuation_size}_{args.checkpoint}_{RANK}.csv" in os.listdir(
"generate_results"):
try:
exsit_df = pd.read_csv(
f"generate_results/memorization_evals_{args.model}_{args.context_size}_{args.context_size + args.continuation_size}_{args.checkpoint}_{RANK}.csv",
index_col=0)
start_idx = num_sequences_per_proc * RANK+len(exsit_df)
file_exisits = True
print(f"Found memorization_evals_{args.model}_{args.context_size}_{args.context_size + args.continuation_size}_{args.checkpoint}_{RANK}.csv and continues from idx {start_idx}")
except pd.errors.EmptyDataError:
file_exisits = False
start_idx = num_sequences_per_proc * RANK
else:
file_exisits = False
start_idx = num_sequences_per_proc * RANK
end_idx = num_sequences_per_proc * (RANK + 1) - 1
if RANK == (NUM_PROCS - 1):
end_idx = total_num_sequences - 1
# Dataset Initialization
mp_queue = mp.Queue()
ds_process = mp.Process(target=generate_dataset, args=(args, start_idx, end_idx, mp_queue))
ds_process.start()
# Model initialization
model = GPTNeoXForCausalLM.from_pretrained(
f"EleutherAI/pythia-{args.model}",
use_cache=False,
revision=f'step{args.checkpoint}',
).half().eval()
model = model.to_bettertransformer()
model = model.cuda()
dist.barrier()
logging.info("Loaded Model")
# Run generations
memorization_evals = []
memorization_evals_values = []
iters = 0
while (True):
try:
t = time.time()
idx, context, true_continuation = mp_queue.get()
if idx is None:
mp_queue.close()
break
idx = idx
logging.info(f"Loading data took {time.time() - t:.3}s")
t = time.time()
accuracies = score(model, context, true_continuation, args.context_size, args.continuation_size)
for acc in accuracies:
memorization_evals.append(f'{idx},{acc}')
memorization_evals_values.append([idx, acc.tolist()])
idx += 1
logging.info(f"Generation uptil {idx} took {time.time() - t:.3}s")
dist.barrier()
iters += 1
if iters % 500 == 0:
if file_exisits:
new_df = pd.DataFrame(memorization_evals_values, columns=["idx", "score"])
df = pd.concat((exsit_df,new_df), ignore_index=True)
df.to_csv(f"generate_results/memorization_evals_{args.model}_{args.context_size}_{args.context_size + args.continuation_size}_{args.checkpoint}_{RANK}.csv")
else:
df = pd.DataFrame(memorization_evals_values, columns=["idx", "score"])
df.to_csv(f"generate_results/memorization_evals_{args.model}_{args.context_size}_{args.context_size + args.continuation_size}_{args.checkpoint}_{RANK}.csv")
except StopIteration:
break
ds_process.join()
if file_exisits:
new_df = pd.DataFrame(memorization_evals_values, columns=["idx", "score"])
df = pd.concat((exsit_df, new_df), ignore_index=True)
df.to_csv(f"generate_results/memorization_evals_{args.model}_{args.context_size}_{args.context_size + args.continuation_size}_{args.checkpoint}_{RANK}.csv")
else:
df = pd.DataFrame(memorization_evals_values, columns=["idx", "score"])
df.to_csv(f"generate_results/memorization_evals_{args.model}_{args.context_size}_{args.context_size + args.continuation_size}_{args.checkpoint}_{RANK}.csv")
with open(f"experiment_cache/memorization_evals_{args.model}_{args.context_size}_{args.context_size + args.continuation_size}_{args.checkpoint}.txt", "a+") as f:
f.write(f"{RANK} done\n")
dist.barrier()
if __name__ == '__main__':
main()