-
Notifications
You must be signed in to change notification settings - Fork 3
/
model_loader.py
135 lines (90 loc) · 3.46 KB
/
model_loader.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
# -*- coding: utf-8 -*-
"""
Transfer Learning Project
author: Hao Zhou
"""
import torch
from tqdm import tqdm
import numpy as np
import os, random, time
from signTrans.Models import (
Transformer,
Transformer2d,
Transformer_test,
)
from signTrans.utils import (
load_cfg,
cal_cdf,
)
from signTrans.batch import Batch
from signTrans.iter import make_iter
def load_model(opt, device, load=True):
if opt['model_type'] == '1d':
model = Transformer(
opt['src_vocab_size'],
opt['trg_vocab_size'],
src_pad_idx=None,
trg_pad_idx=None,
trg_emb_prj_weight_sharing=opt['proj_share_weight'],
emb_src_trg_weight_sharing=opt['embs_share_weight'],
d_k=opt['d_k'],
d_v=opt['d_v'],
d_model=opt['d_model'],
d_word_vec=opt['d_model'],
d_hidden=opt['d_hidden'],
n_layers=opt['n_layers'],
n_heads=opt['n_heads'],
dropout=opt['dropout'],
scale_emb_or_prj=opt['scale_emb_or_prj'],
n_position=opt['n_position'],
src_is_text=opt['src_is_text'],
).to(device)
elif opt['model_type'] == '2d':
model = Transformer2d(
opt['src_vocab_size'],
opt['trg_vocab_size'],
src_pad_idx=None,
trg_pad_idx=None,
trg_emb_prj_weight_sharing=opt['proj_share_weight'],
emb_src_trg_weight_sharing=opt['embs_share_weight'],
d_k=opt['d_k'],
d_v=opt['d_v'],
d_model=opt['d_model'],
d_word_vec=opt['d_model'],
d_hidden=opt['d_hidden'],
n_layers=opt['n_layers'],
n_heads=opt['n_heads'],
dropout=opt['dropout'],
scale_emb_or_prj=opt['scale_emb_or_prj'],
n_position=opt['n_position'],
src_is_text=opt['src_is_text'],
).to(device)
elif opt['model_type'] == 'Transformer_test':
model = Transformer_test(
opt['src_vocab_size'],
opt['trg_vocab_size'],
src_pad_idx=None,
trg_pad_idx=None,
trg_emb_prj_weight_sharing=opt['proj_share_weight'],
emb_src_trg_weight_sharing=opt['embs_share_weight'],
d_k=opt['d_k'],
d_v=opt['d_v'],
d_model=opt['d_model'],
d_word_vec=opt['d_model'],
d_hidden=opt['d_hidden'],
n_layers=opt['n_layers'],
n_heads=opt['n_heads'],
dropout=opt['dropout'],
scale_emb_or_prj=opt['scale_emb_or_prj'],
n_position=opt['n_position'],
src_is_text=opt['src_is_text'],
).to(device)
if load:
model_path = os.path.join(opt['output_dir'], 'model.chkpt')
checkpoint = torch.load(model_path, map_location=device)
model.load_state_dict(checkpoint['model'])
print('[Info] Trained model state loaded.')
return model
else:
print('[Info] Model created.')
return model