-
Notifications
You must be signed in to change notification settings - Fork 35
/
Copy pathextend_weight.py
161 lines (122 loc) · 5.1 KB
/
extend_weight.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
#!/usr/bin/env python
from __future__ import division
import onmt
import onmt.markdown
import torch
import argparse
import math
import numpy
import os, sys
from onmt.model_factory import build_model, build_language_model, build_classifier, optimize_model
from copy import deepcopy
from onmt.utils import checkpoint_paths, normalize_gradients
import glob
import torch.nn as nn
parser = argparse.ArgumentParser(description='translate.py')
onmt.markdown.add_md_help_argument(parser)
parser.add_argument('-model', required=True,
help='Path to model .pt file')
parser.add_argument('-output', default='model.averaged',
help="""Path to output averaged model""")
parser.add_argument('-gpu', type=int, default=-1,
help="Device to run on")
parser.add_argument('-n_languages', type=int, default=10,
help="Device to run on")
def custom_build_model(opt, dict, lm=False, type='seq2seq'):
if type == 'seq2seq':
if not lm:
model = build_model(opt, dict)
else:
model = build_language_model(opt, dict)
elif type == 'classifier':
model = build_classifier(opt, dict)
optimize_model(model)
return model
def main():
opt = parser.parse_args()
opt.cuda = opt.gpu > -1
if opt.cuda:
torch.cuda.set_device(opt.gpu)
# checkpoint for main model
checkpoint = torch.load(opt.model, map_location=lambda storage, loc: storage)
if 'optim' in checkpoint:
del checkpoint['optim']
model_opt = checkpoint['opt']
dicts = checkpoint['dicts']
# extending the weights
def is_factorize_params(p_name):
# feed forward neural net
if p_name.endswith(".r_i") or p_name.endswith(".s_i") \
or p_name.endswith(".r_o") or p_name.endswith(".s_o") \
or p_name.endswith(".r_p") or p_name.endswith(".s_p"):
return True
# if p_name.endswith(".sub_r_i") or p_name.endswith(".sub_s_i") \
# or p_name.endswith(".sub_r_o") or p_name.endswith(".sub_s_o") \
# or p_name.endswith(".sub_r_p") or p_name.endswith(".sub_s_p"):
# return True
if p_name.endswith(".rm_i") or p_name.endswith(".sm_i") or \
p_name.endswith(".rm_o") or p_name.endswith(".sm_o") or \
p_name.endswith(".rm_p") or p_name.endswith(".sm_p"):
return True
if p_name.endswith(".r_q") or p_name.endswith(".s_q") \
or p_name.endswith(".r_o") or p_name.endswith(".s_o") \
or p_name.endswith(".r_kv") or p_name.endswith(".s_kv"):
return True
if p_name.endswith(".rm_q") or p_name.endswith(".sm_q") \
or p_name.endswith(".rm_o") or p_name.endswith(".sm_o") \
or p_name.endswith(".rm_kv") or p_name.endswith(".sm_kv"):
return True
return False
# Saving
model_state_dict = checkpoint['model']
for name in model_state_dict:
if is_factorize_params(name):
param = model_state_dict[name]
sizes = list(param.size())
print(name)
# initialize it
if name.endswith("r_i") or name.endswith("r_o") or name.endswith("r_kv") or name.endswith("r_q") or name.endswith("r_p") or \
name.endswith("s_i") or name.endswith("s_o") or name.endswith("s_kv") or name.endswith("s_q") or name.endswith(
"s_p"):
std = 0.02
prev_n_languages = sizes[0]
sizes[0] = max(opt.n_languages, sizes[0])
# new parameter
p = param.new_zeros(sizes)
nn.init.normal_(p, 0.0, std)
p[0:prev_n_languages].copy_(param)
elif name.endswith("rm_i") or name.endswith("rm_o") or name.endswith("rm_kv") or name.endswith("rm_q") or name.endswith("rm_p") or \
name.endswith("sm_i") or name.endswith("sm_o") or name.endswith("sm_kv") or name.endswith("sm_q") or name.endswith(
"sm_p"):
rank = sizes[1]
fast = (sizes[0] > 1)
prev_n_languages = sizes[0]
if fast:
# new parameter
sizes[0] = max(opt.n_languages, sizes[0])
p = param.new_zeros(sizes)
else:
sizes[0] = 1
p = param.new_zeros(sizes)
sizes[0] = 1
constant = math.sqrt(1.0 / rank) if fast else 1
nn.init.constant_(p, constant)
if fast:
p[0:prev_n_languages].copy_(param)
else:
p.copy_(param)
model_state_dict[name] = p
save_checkpoint = {
'model': model_state_dict,
'dicts': dicts,
'opt': model_opt,
'epoch': -1,
'iteration': -1,
'batchOrder': None,
'optim': None
}
output = opt.model + ".extend" + str(opt.n_languages)
print("Saving averaged model to %s" % output)
torch.save(save_checkpoint, output)
if __name__ == "__main__":
main()