-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathload_models.py
More file actions
547 lines (503 loc) · 24.3 KB
/
load_models.py
File metadata and controls
547 lines (503 loc) · 24.3 KB
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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
import os
import torch
from molecule_pretrain.model import GPT as MolGPT_SF, GPTConfig as MolConfig_SF
from MultiSpec2Mol_Unified.model import BERT,BERTConfig
from spectra_prdiction.model import GPT as SpectraGPT, GPTConfig as SpectraConfig
from spectra_prediction_token.model import GPTConfig as HNMRConfig, GPT as HNMRGPT
from spectra_prediction_token.model_cnmr import GPTConfig as CNMRConfig, GPT as CNMRGPT
from spectra_prediction_token.model_hsqc import GPTConfig as HSQCConfig, GPT as HSQCGPT
from molecule_pretrain.model import GPTConfig as MolConfig, GPT as MolGPT
from molecule_pretrain.model_attn import GPTConfig as MolConfig, GPT as MolGPT_Attn
# from HNMR_prediction.model import GPTConfig as HNMRSConfig, GPT as HNMRSGPT
# from CNMR_prediction.model import GPTConfig as CNMRSConfig, GPT as CNMRSGPT
def load_HSQCNMR_GPT(config: dict,relative_dir:str):
if relative_dir == '':
out_dir = config['out_dir']
else:
out_dir = os.path.join(relative_dir, config['out_dir'])
os.makedirs(out_dir, exist_ok=True)
ckpt_path = os.path.join(out_dir, 'ckpt.pt')
init_from = config['init_from']
block_size = config['block_size']
n_layer = config['n_layer']
n_head = config['n_head']
n_embd = config['n_embd']
dropout = config['dropout']
bias = config['bias']
device = config['device']
if 'rotary' in config:
rotary = config['rotary']
else:
rotary = False
# -----------------------------------------------------------------------------
gpt_config = HSQCConfig(n_layer=n_layer, n_head=n_head, n_embd=n_embd,
rotary=rotary,
dropout=dropout, bias=bias)
model_args = dict(n_layer=n_layer,
n_head=n_head,
n_embd=n_embd,
rotary=rotary,
block_size=block_size,
bias=bias,dropout=dropout) # start with model_args from command line
model = HSQCGPT(gpt_config)
if init_from == 'scratch':
# init a new model from scratch
print("Initializing a new model from scratch")
# determine the vocab size we'll use for from-scratch training
print(f"initializing model with vq-vae config: {gpt_config}")
elif init_from == 'resume':
print(f"Resuming training from {out_dir}")
# resume training from a checkpoint.
checkpoint = torch.load(ckpt_path, map_location='cpu')
checkpoint_model_args = checkpoint['model_args']
# force these config attributes to be equal otherwise we can't even resume training
# the rest of the attributes (e.g. dropout) can stay as desired from command line
for k in ['n_layer', 'n_head', 'n_embd', 'block_size', 'bias', 'dropout']:
if k in checkpoint_model_args:
model_args[k] = checkpoint_model_args[k]
else:
model_args[k] = config[k]
# create the model
gptconf = HSQCConfig(**model_args)
model = HSQCGPT(gptconf)
state_dict = checkpoint['model']
model.load_state_dict(state_dict, strict=False)
return model,model_args
def load_IR_GPT(config: dict,relative_dir:str):
if relative_dir == '':
out_dir = config['out_dir']
else:
out_dir = os.path.join(relative_dir,config['out_dir'])
os.makedirs(out_dir, exist_ok=True)
ckpt_path = os.path.join(out_dir, 'ckpt.pt')
init_from = config['init_from']
block_size = config['block_size']
n_layer = config['n_layer']
n_head = config['n_head']
n_embd = config['n_embd']
n_patchsize = config['n_patchsize']
signal_length = config['signal_length']
dropout = config['dropout']
bias = config['bias']
if 'rotary' in config:
rotary = config['rotary']
else:
rotary = False
# -----------------------------------------------------------------------------
# model settings && initialization
gpt_config = SpectraConfig(n_layer=n_layer, n_head=n_head, n_embd=n_embd,
n_patchsize=n_patchsize, signal_length=signal_length,
dropout=dropout, bias=bias,rotary=rotary)
model_args = dict(n_layer=n_layer, n_head=n_head, n_embd=n_embd, block_size=block_size,
bias=bias,dropout=dropout,n_patchsize=n_patchsize,signal_length=signal_length,
rotary=rotary) # start with model_args from command line
model = SpectraGPT(gpt_config)
if init_from == 'scratch':
# init a new model from scratch
print("Initializing a new model from scratch")
# determine the vocab size we'll use for from-scratch training
gptconf = SpectraConfig(**model_args)
model = SpectraGPT(gptconf)
print(f"initializing model with config: {gptconf}")
elif init_from == 'resume':
print(f"Resuming training from {out_dir}")
# resume training from a checkpoint.
checkpoint = torch.load(ckpt_path, map_location='cpu')
checkpoint_model_args = checkpoint['model_args']
# force these config attributes to be equal otherwise we can't even resume training
# the rest of the attributes (e.g. dropout) can stay as desired from command line
for k in ['n_layer', 'n_head', 'n_embd', 'block_size', 'bias','n_patchsize','signal_length','dropout']:
if k in checkpoint_model_args:
model_args[k] = checkpoint_model_args[k]
else:
model_args[k] = config[k]
# create the model
gptconf = SpectraConfig(**model_args)
model = SpectraGPT(gptconf)
state_dict = checkpoint['model']
# fix the keys of the state dictionary :(
# honestly no idea how checkpoints sometimes get this prefix, have to debug more
unwanted_prefix = '_orig_mod.'
# for k, v in list(state_dict.items()):
# if k.startswith(unwanted_prefix):
# state_dict[k[len(unwanted_prefix):]] = state_dict.pop(k)
model.load_state_dict(state_dict, strict=False)
return model,model_args
def load_HNMR_GPT(config: dict,relative_dir:str):
if relative_dir == '':
out_dir = config['out_dir']
else:
out_dir = os.path.join(relative_dir,config['out_dir'])
os.makedirs(out_dir, exist_ok=True)
ckpt_path = os.path.join(out_dir, 'ckpt.pt')
init_from = config['init_from']
block_size = config['block_size']
n_layer = config['n_layer']
n_head = config['n_head']
n_embd = config['n_embd']
dropout = config['dropout']
bias = config['bias']
learning_rate = config['learning_rate']
weight_decay = config['weight_decay']
beta1 = config['beta1']
beta2 = config['beta2']
device = config['device']
dtype = config['dtype']
gpu_ids = config['gpu_ids']
device_type = config['device_type']
dp = config['dp'] if len(gpu_ids) > 1 else False
if 'rotary' in config:
rotary = config['rotary']
else:
rotary = False
ptdtype = {'float32': torch.float32, 'bfloat16': torch.bfloat16, 'float16': torch.float16}[dtype]
# -----------------------------------------------------------------------------
# -----------------------------------------------------------------------------
# model settings && initialization
# config['use_categories_jvalue'] = True
gpt_config = HNMRConfig(n_layer=n_layer, n_head=n_head, n_embd=n_embd,
rotary=rotary,
dropout=dropout, bias=bias,
use_categories_jvalue=config.get('use_categories_jvalue', True),)
model_args = dict(n_layer=n_layer,
n_head=n_head,
n_embd=n_embd,
block_size=block_size,
rotary=rotary,
use_categories_jvalue=config.get('use_categories_jvalue', True),
bias=bias, dropout=dropout) # start with model_args from command line
print('use_categories_jvalue', config.get('use_categories_jvalue', True))
model = HNMRGPT(gpt_config)
if init_from == 'scratch':
# init a new model from scratch
print("Initializing a new model from scratch")
# determine the vocab size we'll use for from-scratch training
gptconf = HNMRConfig(**model_args)
model = HNMRGPT(gptconf).to(device)
print(f"initializing model with vq-vae config: {gptconf}")
iter_num = 0
elif init_from == 'resume':
print(f"Resuming training from {out_dir}")
# resume training from a checkpoint.
checkpoint = torch.load(ckpt_path, map_location='cpu')
checkpoint_model_args = checkpoint['model_args']
# force these config attributes to be equal otherwise we can't even resume training
# the rest of the attributes (e.g. dropout) can stay as desired from command line
for k in ['n_layer', 'n_head', 'n_embd', 'block_size', 'bias', 'dropout']:
if k in checkpoint_model_args:
model_args[k] = checkpoint_model_args[k]
else:
model_args[k] = config[k]
# create the model
gptconf = HNMRConfig(**model_args)
model = HNMRGPT(gptconf)
state_dict = checkpoint['model']
model.load_state_dict(state_dict, strict=False)
elif init_from.startswith('gpt2'):
print(f"Initializing from OpenAI GPT-2 weights: {init_from}")
# initialize from OpenAI GPT-2 weights
override_args = dict(dropout=dropout)
model = HNMRGPT.from_pretrained(init_from, override_args)
# read off the created config params, so we can store them into checkpoint correctly
for k in ['n_layer', 'n_head', 'n_embd', 'block_size', 'bias', 'vocab_size']:
model_args[k] = getattr(model.config, k)
# crop down the model block size if desired, using model surgery
if block_size < model.config.block_size:
model.crop_block_size(block_size)
model_args['block_size'] = block_size # so that the checkpoint will have the right value
return model,model_args
def load_CNMR_GPT(config: dict,relative_dir:str,use_intensity:bool=False):
if relative_dir == '':
out_dir = config['out_dir']
else:
out_dir = os.path.join(relative_dir,config['out_dir'])
os.makedirs(out_dir, exist_ok=True)
init_from = config['init_from']
block_size = config['block_size']
n_layer = config['n_layer']
n_head = config['n_head']
n_embd = config['n_embd']
dropout = config['dropout']
bias = config['bias']
device = config['device']
ckpt_path = os.path.join(out_dir, 'ckpt.pt')
if 'rotary' in config:
rotary = config['rotary']
else:
rotary = False
# -----------------------------------------------------------------------------
# -----------------------------------------------------------------------------
# model settings && initialization
gpt_config = CNMRConfig(n_layer=n_layer, n_head=n_head, n_embd=n_embd,
rotary=rotary,
dropout=dropout, bias=bias,use_intensity=use_intensity)
model_args = dict(n_layer=n_layer,
n_head=n_head,
n_embd=n_embd,
block_size=block_size,
rotary=rotary,
bias=bias, dropout=dropout,
use_intensity=use_intensity) # start with model_args from command line
model = CNMRGPT(gpt_config)
if init_from == 'scratch':
# init a new model from scratch
print("Initializing a new model from scratch")
# determine the vocab size we'll use for from-scratch training
gptconf = CNMRConfig(**model_args)
model = CNMRGPT(gptconf).to(device)
print(f"initializing model with vq-vae config: {gptconf}")
elif init_from == 'resume':
print(f"Resuming training from {out_dir}")
# resume training from a checkpoint.
checkpoint = torch.load(ckpt_path, map_location='cpu')
checkpoint_model_args = checkpoint['model_args']
# force these config attributes to be equal otherwise we can't even resume training
# the rest of the attributes (e.g. dropout) can stay as desired from command line
for k in ['n_layer', 'n_head', 'n_embd', 'block_size', 'bias', 'dropout']:
if k in checkpoint_model_args:
model_args[k] = checkpoint_model_args[k]
else:
model_args[k] = config[k]
# create the model
gptconf = CNMRConfig(**model_args)
model = CNMRGPT(gptconf)
state_dict = checkpoint['model']
# fix the keys of the state dictionary :(
# honestly no idea how checkpoints sometimes get this prefix, have to debug more
unwanted_prefix = '_orig_mod.'
# for k, v in list(state_dict.items()):
# if k.startswith(unwanted_prefix):
# state_dict[k[len(unwanted_prefix):]] = state_dict.pop(k)
model.load_state_dict(state_dict, strict=False)
iter_num = checkpoint['iter_num']
best_val_loss = checkpoint['best_val_loss']
return model,model_args
self_define_tokens = {'[predict]':0,'[functional_group]':1,}
def load_MolGPT_SF(config: dict,relative_dir:str):
if relative_dir == '':
out_dir = config['out_dir']
else:
out_dir = os.path.join(relative_dir, config['out_dir'])
os.makedirs(out_dir, exist_ok=True)
ckpt_path = os.path.join(out_dir, 'ckpt.pt')
init_from = config['init_from']
block_size = config['block_size']
n_layer = config['n_layer']
n_head = config['n_head']
n_embd = config['n_embd']
dropout = config['dropout']
bias = config['bias']
device = config['device']
dtype = config['dtype']
vocab_size = config['vocab_size']
rotary = config['rotary']
# -----------------------------------------------------------------------------
# model settings && initialization
gpt_config = MolConfig_SF(n_layer=n_layer, n_head=n_head, n_embd=n_embd,
vocab_size=vocab_size, block_size=block_size,
dropout=dropout, bias=bias,
rotary=rotary,
bos_token_id=config['bos_id'],
eos_token_id=config['eos_id'],
pad_token_id=config['pad_id'])
model_args = dict(n_layer=n_layer, n_head=n_head, n_embd=n_embd, block_size=block_size,
bias=bias, dropout=dropout,
rotary = rotary) # start with model_args from command line
model = MolGPT_SF(gpt_config)
if init_from == 'scratch':
# init a new model from scratch
print("Initializing a new model from scratch")
# determine the vocab size we'll use for from-scratch training
gptconf = MolConfig_SF(**model_args)
model = MolGPT_SF(gptconf)
print(f"initializing model with config: {gptconf}")
iter_num = 0
elif init_from == 'resume':
print(f"Resuming training from {out_dir}")
# resume training from a checkpoint.
checkpoint = torch.load(ckpt_path, map_location='cpu')
# create the model
gptconf = MolConfig_SF(**model_args)
model = MolGPT_SF(gptconf)
state_dict = checkpoint['model']
# fix the keys of the state dictionary :(
# honestly no idea how checkpoints sometimes get this prefix, have to debug more
unwanted_prefix = '_orig_mod.'
# for k, v in list(state_dict.items()):
# if k.startswith(unwanted_prefix):
# state_dict[k[len(unwanted_prefix):]] = state_dict.pop(k)
model.load_state_dict(state_dict, strict=False)
iter_num = checkpoint['iter_num']
best_val_loss = checkpoint['best_val_loss']
return model,gpt_config
def load_MolGPT(config: dict,relative_dir:str):
if relative_dir == '':
out_dir = config['out_dir']
else:
out_dir = os.path.join(relative_dir,config['out_dir'])
os.makedirs(out_dir, exist_ok=True)
ckpt_path = os.path.join(out_dir, 'ckpt.pt')
init_from = config['init_from']
block_size = config['block_size']
n_layer = config['n_layer']
n_head = config['n_head']
n_embd = config['n_embd']
dropout = config['dropout']
bias = config['bias']
vocab_size = config['vocab_size']
if 'rotary' in config:
rotary = config['rotary']
else:
rotary = False
print('if use rotary embeddings,', rotary)
# -----------------------------------------------------------------------------
# model settings && initialization
gpt_config = MolConfig(n_layer=n_layer, n_head=n_head, n_embd=n_embd,
vocab_size=vocab_size, block_size=block_size,
dropout=dropout, bias=bias,rotary=rotary)
model_args = dict(n_layer=n_layer, n_head=n_head, n_embd=n_embd, block_size=block_size,
bias=bias,dropout=dropout,rotary=rotary) # start with model_args from command line
model = MolGPT(gpt_config)
if init_from == 'scratch':
# init a new model from scratch
print("Initializing a new model from scratch")
# determine the vocab size we'll use for from-scratch training
gptconf = MolConfig(**model_args)
model = MolGPT(gptconf)
print(f"initializing model with config: {gptconf}")
iter_num = 0
elif init_from == 'resume':
print(f"Resuming training from {out_dir}")
# resume training from a checkpoint.
checkpoint = torch.load(ckpt_path, map_location='cpu')
checkpoint_model_args = checkpoint['model_args']
# force these config attributes to be equal otherwise we can't even resume training
# the rest of the attributes (e.g. dropout) can stay as desired from command line
for k in ['n_layer', 'n_head', 'n_embd', 'block_size', 'bias','vocab_size','dropout']:
if k in checkpoint_model_args:
model_args[k] = checkpoint_model_args[k]
else:
model_args[k] = config[k]
# create the model
gptconf = MolConfig(**model_args)
model = MolGPT(gptconf)
state_dict = checkpoint['model']
# fix the keys of the state dictionary :(
# honestly no idea how checkpoints sometimes get this prefix, have to debug more
unwanted_prefix = '_orig_mod.'
# for k, v in list(state_dict.items()):
# if k.startswith(unwanted_prefix):
# state_dict[k[len(unwanted_prefix):]] = state_dict.pop(k)
model.load_state_dict(state_dict, strict=False)
iter_num = checkpoint['iter_num']
best_val_loss = checkpoint['best_val_loss']
return model,model_args
def load_MolGPT_Attn(config: dict,relative_dir:str):
if relative_dir == '':
out_dir = config['out_dir']
else:
out_dir = os.path.join(relative_dir,config['out_dir'])
os.makedirs(out_dir, exist_ok=True)
ckpt_path = os.path.join(out_dir, 'ckpt.pt')
init_from = config['init_from']
block_size = config['block_size']
n_layer = config['n_layer']
n_head = config['n_head']
n_embd = config['n_embd']
dropout = config['dropout']
bias = config['bias']
vocab_size = config['vocab_size']
if 'rotary' in config:
rotary = config['rotary']
else:
rotary = False
print('if use rotary embeddings,', rotary)
# -----------------------------------------------------------------------------
# model settings && initialization
gpt_config = MolConfig(n_layer=n_layer, n_head=n_head, n_embd=n_embd,
vocab_size=vocab_size, block_size=block_size,
dropout=dropout, bias=bias,rotary=rotary)
model_args = dict(n_layer=n_layer, n_head=n_head, n_embd=n_embd, block_size=block_size,
bias=bias,dropout=dropout,rotary=rotary) # start with model_args from command line
model = MolGPT_Attn(gpt_config)
if init_from == 'scratch':
# init a new model from scratch
print("Initializing a new model from scratch")
# determine the vocab size we'll use for from-scratch training
gptconf = MolConfig(**model_args)
model = MolGPT(gptconf)
print(f"initializing model with config: {gptconf}")
iter_num = 0
elif init_from == 'resume':
print(f"Resuming training from {out_dir}")
# resume training from a checkpoint.
checkpoint = torch.load(ckpt_path, map_location='cpu')
checkpoint_model_args = checkpoint['model_args']
# force these config attributes to be equal otherwise we can't even resume training
# the rest of the attributes (e.g. dropout) can stay as desired from command line
for k in ['n_layer', 'n_head', 'n_embd', 'block_size', 'bias','vocab_size','dropout']:
if k in checkpoint_model_args:
model_args[k] = checkpoint_model_args[k]
else:
model_args[k] = config[k]
# create the model
gptconf = MolConfig(**model_args)
model = MolGPT(gptconf)
state_dict = checkpoint['model']
# fix the keys of the state dictionary :(
# honestly no idea how checkpoints sometimes get this prefix, have to debug more
unwanted_prefix = '_orig_mod.'
# for k, v in list(state_dict.items()):
# if k.startswith(unwanted_prefix):
# state_dict[k[len(unwanted_prefix):]] = state_dict.pop(k)
model.load_state_dict(state_dict, strict=False)
iter_num = checkpoint['iter_num']
best_val_loss = checkpoint['best_val_loss']
return model,model_args
def load_BERT(config: dict):
out_dir = config['out_dir']
os.makedirs(out_dir, exist_ok=True)
ckpt_path = os.path.join(out_dir, 'ckpt.pt')
init_from = config['init_from']
block_size = config['block_size']
n_layer = config['n_layer']
n_head = config['n_head']
n_embd = config['n_embd']
n_learnable_tokens = config['n_learnable_tokens']
dropout = config['dropout']
bias = config['bias']
# -----------------------------------------------------------------------------
# model settings && initialization
gpt_config = BERTConfig(n_layer=n_layer, n_head=n_head, n_embd=n_embd,
block_size=block_size, n_learnable_tokens=n_learnable_tokens,
dropout=dropout, bias=bias, rotary=config.get('rotary', False))
model_args = dict(n_layer=n_layer, n_head=n_head, n_embd=n_embd, block_size=block_size,
n_learnable_tokens=n_learnable_tokens,
bias=bias, dropout=dropout,rotary=config.get('rotary', False)) # start with model_args from command line
model = BERT(gpt_config)
if init_from == 'scratch':
# init a new model from scratch
print("Initializing a new model from scratch")
# determine the vocab size we'll use for from-scratch training
gptconf = BERTConfig(**model_args)
model = BERT(gptconf)
print(f"initializing model with config: {gptconf}")
iter_num = 0
elif init_from == 'resume':
print(f"Resuming training from {out_dir}")
# resume training from a checkpoint.
checkpoint = torch.load(ckpt_path, map_location='cpu')
checkpoint_model_args = checkpoint['model_args']
# force these config attributes to be equal otherwise we can't even resume training
# the rest of the attributes (e.g. dropout) can stay as desired from command line
for k in ['n_layer', 'n_head', 'n_embd', 'block_size', 'bias', 'dropout']:
if k in checkpoint_model_args:
model_args[k] = checkpoint_model_args[k]
else:
model_args[k] = config[k]
# create the model
bertconf = BERTConfig(**model_args)
model = BERT(bertconf)
state_dict = checkpoint['model']
model.load_state_dict(state_dict, strict=False)
return model,model_args