-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathptmod.py
208 lines (175 loc) · 6.64 KB
/
ptmod.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
import argparse
import collections
import shlex
from typing import Sequence
import torch
def torch_load(fname):
obj = torch.load(fname, map_location=torch.device("cpu"))
if not isinstance(obj, collections.abc.Mapping):
raise RuntimeError(f"{fname} must be dict, but got {type(obj)}")
return obj
def modify(
operations: Sequence[str],
):
states = {}
modified = set()
for s in operations:
s = s.strip()
commands = shlex.split(s)
if commands[0] == "rm":
for c in commands[1:]:
if ":" not in c:
raise RuntimeError(f"Must be a form as filepath:key, but got {c}")
var, key = c.split(":", 1)
if var not in states:
states[var] = torch_load(var)
state = states[var]
new_state = {}
found = False
for k, v in state.items():
if not (k == key or k.startswith(f"{key}.")):
new_state[k] = v
found = True
if not found:
raise RuntimeError(f"Key '{key}' is not found in {var}")
states[var] = new_state
modified.add(var)
elif commands[0] == "cp":
if len(commands) != 3:
raise RuntimeError(f"Must be a form as 'cp src dest', but got {s}")
src_state = {}
if ":" not in commands[1]:
var1 = commands[1]
if var1 not in states:
states[var1] = torch_load(var1)
src_state = states[var1]
else:
var1, key1 = commands[1].split(":", 1)
if var1 not in states:
states[var1] = torch_load(var1)
for k, v in states[var1].items():
if k == key1 or k.startswith(f"{key1}."):
src_state[k[len(key1) :]] = v
if len(src_state) == 0:
raise RuntimeError(f"Key '{key1}' is not found in {var1}")
if ":" not in commands[2]:
var2 = commands[2]
key2 = ""
else:
var2, key2 = commands[2].split(":", 1)
if var2 not in states:
states[var2] = {}
for k, v in src_state.items():
if key2 == "":
if k == "":
raise RuntimeError("No key name is specified")
if k.startswith("."):
states[var2][k[1:]] = v
else:
states[var2][k] = v
else:
if key2.endswith(".") and k.startswith("."):
states[var2][key2 + k[1:]] = v
elif not key2.endswith(".") and not k.startswith("."):
states[var2][key2 + "." + k] = v
else:
states[var2][key2 + k] = v
modified.add(var2)
elif commands[0] == "ls":
if commands[1] == "-l":
verbose = True
commands = commands[1:]
else:
verbose = False
for var in commands[1:]:
if var not in states:
states[var] = torch_load(var)
for k, v in states[var].items():
if verbose:
print(k, tuple(v.shape))
else:
print(k)
elif commands[0] in ("average", "sum"):
if len(commands) > 3:
raise RuntimeError(
f"Require 2 or more arguments: '{commands[0]} out-file in-file...'"
)
out_states = {}
for var in commands[2:]:
if var not in states:
states[var] = torch_load(var)
for k, v in states[var].items():
if k not in out_states:
out_states[k] = v
else:
out_states[k] += v
if commands[0] == "average":
for k, v in list(out_states.items()):
# For integer type, not dividing
if not str(out_states[k].dtype).startswith("torch.int"):
out_states[k] = v / len(commands[2:])
states[commands[1]] = out_states
modified.add(commands[1])
else:
raise RuntimeError(
"Available commands:\n"
" ls model.pth\n"
" rm model.pth:key\n"
" average out.pth in.pth in2.pth...\n"
" sum out.pth in.pth in2.pth...\n"
)
for var in modified:
torch.save(states[var], var)
def ptmod_ls():
parser = argparse.ArgumentParser(
description="Modify PyTorch model file",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
parser.add_argument("args", nargs="+")
args = parser.parse_args()
modify(["ls " + " ".join(args.args)])
def ptmod_rm():
parser = argparse.ArgumentParser(
description="Modify PyTorch model file",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
parser.add_argument("args", nargs="+")
args = parser.parse_args()
modify(["rm" + " ".join(args.args)])
def ptmod_cp():
parser = argparse.ArgumentParser(
description="Modify PyTorch model file",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
parser.add_argument("input")
parser.add_argument("output")
args = parser.parse_args()
modify([f"cp {args.input} {args.output}"])
def ptmod_average():
parser = argparse.ArgumentParser(
description="Modify PyTorch model file",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
parser.add_argument("output")
parser.add_argument("args", nargs="+")
args = parser.parse_args()
modify([f"average {args.output}" + " ".join(args.args)])
def ptmod_sum():
parser = argparse.ArgumentParser(
description="Modify PyTorch model file",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
parser.add_argument("output")
parser.add_argument("args", nargs="+")
args = parser.parse_args()
modify([f"sum {args.output}" + " ".join(args.args)])
def ptmod_main():
parser = argparse.ArgumentParser(
description="Modify PyTorch model file",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
parser.add_argument("operations", nargs="+")
args = parser.parse_args()
modify(**vars(args))
if __name__ == "__main__":
ptmod_main()