-
Notifications
You must be signed in to change notification settings - Fork 116
/
Copy pathsample.py
208 lines (140 loc) · 6.92 KB
/
sample.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
# Copyright (c) 2022, salesforce.com, inc.
# All rights reserved.
# SPDX-License-Identifier: BSD-3-Clause
# For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
import os
import time
import random
import argparse
import torch
from tokenizers import Tokenizer
from models.progen.modeling_progen import ProGenForCausalLM
########################################################################
# util
class print_time:
def __init__(self, desc):
self.desc = desc
def __enter__(self):
print(self.desc)
self.t = time.time()
def __exit__(self, type, value, traceback):
print(f'{self.desc} took {time.time()-self.t:.02f}s')
def set_env():
os.environ['TOKENIZERS_PARALLELISM'] = 'false'
def set_seed(seed, deterministic=True):
random.seed(seed)
os.environ['PYTHONHASHSEED'] = str(seed)
torch.manual_seed(seed)
if torch.cuda.is_available():
torch.cuda.manual_seed(seed)
torch.backends.cudnn.deterministic = deterministic
torch.backends.cudnn.benchmark = not deterministic
########################################################################
# model
def create_model(ckpt, fp16=True):
if fp16:
return ProGenForCausalLM.from_pretrained(ckpt, revision='float16', torch_dtype=torch.float16, low_cpu_mem_usage=True)
else:
return ProGenForCausalLM.from_pretrained(ckpt)
def create_tokenizer_custom(file):
with open(file, 'r') as f:
return Tokenizer.from_str(f.read())
########################################################################
# sample
def sample(device, model, tokenizer, context, max_length, num_return_sequences, top_p, temp, pad_token_id):
with torch.no_grad():
input_ids = torch.tensor(tokenizer.encode(context).ids).view([1, -1]).to(device)
tokens_batch = model.generate(input_ids, do_sample=True, temperature=temp, max_length=max_length, top_p=top_p, num_return_sequences=num_return_sequences, pad_token_id=pad_token_id)
as_lists = lambda batch: [batch[i, ...].detach().cpu().numpy().tolist() for i in range(batch.shape[0])]
return tokenizer.decode_batch(as_lists(tokens_batch))
def truncate(sample, terminals):
pos = []
for terminal in terminals:
find_pos = sample.find(terminal, 1)
if find_pos != -1:
pos.append(find_pos)
if len(pos) > 0:
return sample[:(min(pos)+1)]
else:
return sample
def cross_entropy(logits, target, reduction='mean'):
return torch.nn.functional.cross_entropy(input=logits, target=target, weight=None, size_average=None, reduce=None, reduction=reduction)
########################################################################
# main
def main():
# (0) constants
models_151M = [ 'progen2-small' ]
models_754M = [ 'progen2-medium', 'progen2-oas', 'progen2-base' ]
models_2B = [ 'progen2-large', 'progen2-BFD90' ]
models_6B = [ 'progen2-xlarge' ]
models = models_151M + models_754M + models_2B + models_6B
# (1) params
parser = argparse.ArgumentParser()
parser.add_argument('--model', type=str, choices=models, default='progen2-large')
parser.add_argument('--device', type=str, default='cuda:0')
parser.add_argument('--rng-seed', type=int, default=42)
parser.add_argument('--rng-deterministic', default=True, type=lambda x: (str(x).lower() == 'true'))
parser.add_argument('--p', type=float, default=0.95)
parser.add_argument('--t', type=float, default=0.2)
parser.add_argument('--max-length', type=int, default=256)
parser.add_argument('--num-samples', type=int, default=1)
parser.add_argument('--fp16', default=True, type=lambda x: (str(x).lower() == 'true'))
parser.add_argument('--context', type=str, default='1')
parser.add_argument('--sanity', default=True, type=lambda x: (str(x).lower() == 'true'))
args = parser.parse_args()
# (2) preamble
set_env()
set_seed(args.rng_seed, deterministic=args.rng_deterministic)
if not torch.cuda.is_available():
print('falling back to cpu')
args.device = 'cpu'
device = torch.device(args.device)
ckpt = f'./checkpoints/{args.model}'
if device.type == 'cpu':
print('falling back to fp32')
args.fp16 = False
# (3) load
with print_time('loading parameters'):
model = create_model(ckpt=ckpt, fp16=args.fp16).to(device)
with print_time('loading tokenizer'):
tokenizer = create_tokenizer_custom(file='tokenizer.json')
# (4) sanity
if args.sanity:
with print_time('sanity cross-entropy'):
def ce(tokens):
with torch.no_grad():
with torch.cuda.amp.autocast(enabled=args.fp16):
target = torch.tensor(tokenizer.encode(tokens).ids).to(device)
logits = model(target, labels=target).logits
# shift
logits = logits[:-1, ...]
target = target[1:]
return cross_entropy(logits=logits, target=target).item()
x_uniref90bfd30 = '2GFLPFRGADEGLAAREAATLAARGTAARAYREDSWAVPVPRGLLGDLTARVAALGAASPPPADPLAVTLDLHHVTAEVALTTVLDAATLVHGQTRVLSAEDAAEAATAAAAATEAYLERLQDFVLFMSASVRVWRRGNAAGATGPEWDQWYTVADRDALGSAPTHLAVLGRQADALCHFVLDRVAWGTCGTPLWSGDEDLGNVVATFAGYADRLATAPRDLIM1'
x_oas = '1EVQLVESGGGLVQPGGSLRLSCAASGFTFSSYAMHWVRQAPWKGLEYVSAISSNGGSTYYANSVKGRFTISRDNSKNTLYLQMGSLRAEDMAVYYCARDESGYSYGWGYYFDYWGQGTLVTVSS2'
x_bfd90 = '1TAPRSTRASGSEGSRPPGIPAKGRRCLPSRAGSVTPRFRHARQGTATVAKEQGRKLIASNRKARHDYHIEDTFEAGLVLTGTEVKSLRMGRASLIDGYAVFYGEELWLEGVHIPEYLNGNWTNHTPRRRRKLLLNRSELTKLAHKTSESGHTIVPLALYFKDGRAKVEIAVAKGKKAYDKRHALRERQDQREV2'
checkpoint_x_ce = {
'progen2-small': (x_uniref90bfd30, 2.4),
'progen2-medium': (x_uniref90bfd30, 1.9),
'progen2-base': (x_uniref90bfd30, 1.9),
'progen2-large': (x_uniref90bfd30, 1.8),
'progen2-xlarge': (x_uniref90bfd30, 1.0),
'progen2-oas': (x_oas, 0.3),
'progen2-BFD90': (x_bfd90, 1.3),
}
ce_eval = ce(checkpoint_x_ce[args.model][0])
ce_target = checkpoint_x_ce[args.model][1]
print(ce_target, ce_eval, abs(ce_eval - ce_target))
assert abs(ce_eval - ce_target) < 0.1
# (5) sample
with print_time('sampling'):
completions = sample(device=device, model=model, tokenizer=tokenizer, context=args.context, pad_token_id=tokenizer.encode('<|pad|>').ids[0], num_return_sequences=args.num_samples, temp=args.t, top_p=args.p, max_length=args.max_length)
truncations = [truncate(completion, terminals=['1', '2']) for completion in completions]
print(args.context)
for (i, truncation) in enumerate(truncations):
print()
print(i)
print(truncation)
if __name__ == '__main__':
main()
print('done.')