-
Notifications
You must be signed in to change notification settings - Fork 378
/
export_model.py
267 lines (243 loc) · 9.29 KB
/
export_model.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
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
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import argparse
import os
import os.path as osp
import sys
import paddle
from paddle.jit import to_static
from paddle.static import InputSpec
__dir__ = os.path.dirname(os.path.abspath(__file__))
sys.path.append(os.path.abspath(os.path.join(__dir__, '../')))
from paddlevideo.modeling.builder import build_model
from paddlevideo.utils import get_config
def parse_args():
parser = argparse.ArgumentParser("PaddleVideo export model script")
parser.add_argument('-c',
'--config',
type=str,
default='configs/example.yaml',
help='config file path')
parser.add_argument('--override',
action='append',
default=[],
help='config options to be overridden')
parser.add_argument("-p",
"--pretrained_params",
default='./best.pdparams',
type=str,
help='params path')
parser.add_argument("-o",
"--output_path",
type=str,
default="./inference",
help='output path')
parser.add_argument('--save_name',
type=str,
default=None,
help='specify the exported inference \
files(pdiparams and pdmodel) name,\
only used in TIPC')
return parser.parse_args()
def trim_config(cfg):
"""
Reuse the trainging config will bring useless attributes, such as: backbone.pretrained model.
and some build phase attributes should be overrided, such as: backbone.num_seg.
Trim it here.
"""
model_name = cfg.model_name
if cfg.MODEL.get('backbone') and cfg.MODEL.backbone.get('pretrained'):
cfg.MODEL.backbone.pretrained = "" # not ued when inference
# for distillation
if cfg.MODEL.get('models'):
if cfg.MODEL.models[0]['Teacher']['backbone'].get('pretrained'):
cfg.MODEL.models[0]['Teacher']['backbone']['pretrained'] = ""
if cfg.MODEL.models[1]['Student']['backbone'].get('pretrained'):
cfg.MODEL.models[1]['Student']['backbone']['pretrained'] = ""
return cfg, model_name
def get_input_spec(cfg, model_name):
if model_name in ['ppTSM', 'TSM', 'MoViNet', 'ppTSMv2']:
input_spec = [[
InputSpec(
shape=[None, cfg.num_seg, 3, cfg.target_size, cfg.target_size],
dtype='float32'),
]]
elif model_name in ['TokenShiftVisionTransformer']:
input_spec = [[
InputSpec(shape=[
None, 3, cfg.num_seg * 3, cfg.target_size, cfg.target_size
],
dtype='float32'),
]]
elif model_name in ['TSN', 'ppTSN']:
input_spec = [[
InputSpec(shape=[
None, cfg.num_seg * 10, 3, cfg.target_size, cfg.target_size
],
dtype='float32'),
]]
elif model_name in ['BMN']:
input_spec = [[
InputSpec(shape=[None, cfg.feat_dim, cfg.tscale],
dtype='float32',
name='feat_input'),
]]
elif model_name in ['TimeSformer', 'ppTimeSformer']:
input_spec = [[
InputSpec(shape=[
None, 3, cfg.num_seg * 3, cfg.target_size, cfg.target_size
],
dtype='float32'),
]]
elif model_name in ['VideoSwin']:
input_spec = [[
InputSpec(shape=[
None, 3, cfg.num_seg * cfg.seg_len * 1, cfg.target_size,
cfg.target_size
],
dtype='float32'),
]]
elif model_name in ['VideoSwin_TableTennis']:
input_spec = [[
InputSpec(shape=[
None, 3, cfg.num_seg * cfg.seg_len * 3, cfg.target_size,
cfg.target_size
],
dtype='float32'),
]]
elif model_name in ['AttentionLSTM']:
input_spec = [[
InputSpec(shape=[None, cfg.embedding_size, cfg.feature_dims[0]],
dtype='float32'), # for rgb_data
InputSpec(shape=[
None,
], dtype='int64'), # for rgb_len
InputSpec(shape=[None, cfg.embedding_size, cfg.feature_dims[0]],
dtype='float32'), # for rgb_mask
InputSpec(shape=[None, cfg.embedding_size, cfg.feature_dims[1]],
dtype='float32'), # for audio_data
InputSpec(shape=[
None,
], dtype='int64'), # for audio_len
InputSpec(shape=[None, cfg.embedding_size, cfg.feature_dims[1]],
dtype='float32'), # for audio_mask
]]
elif model_name in ['SlowFast']:
input_spec = [[
InputSpec(shape=[
None, 3, cfg.num_frames // cfg.alpha, cfg.target_size,
cfg.target_size
],
dtype='float32',
name='slow_input'),
InputSpec(shape=[
None, 3, cfg.num_frames, cfg.target_size, cfg.target_size
],
dtype='float32',
name='fast_input'),
]]
elif model_name in ['STGCN', 'AGCN', 'CTRGCN']:
input_spec = [[
InputSpec(shape=[
None, cfg.num_channels, cfg.window_size, cfg.vertex_nums,
cfg.person_nums
],
dtype='float32'),
]]
# 由于在模型运行过程中涉及到第一维乘human个数(N*M), 所以这里用1作为shape
elif model_name in ['AGCN2s']:
input_spec = [[
InputSpec(shape=[
1, cfg.num_channels, cfg.window_size, cfg.vertex_nums,
cfg.person_nums
],
dtype='float32'),
]]
elif model_name in ['TransNetV2']:
input_spec = [[
InputSpec(shape=[
None,
cfg.num_frames,
cfg.height,
cfg.width,
cfg.num_channels,
],
dtype='float32'),
]]
elif model_name in ['MSTCN', 'ASRF']:
input_spec = [[
InputSpec(shape=[None, cfg.num_channels, None], dtype='float32'),
]]
elif model_name in ['ADDS']:
input_spec = [[
InputSpec(shape=[None, cfg.num_channels, cfg.height, cfg.width],
dtype='float32'),
]]
elif model_name in ['AVA_SlowFast_FastRcnn']:
input_spec = [[
InputSpec(shape=[
None, 3, cfg.num_frames // cfg.alpha, cfg.target_size,
cfg.target_size
],
dtype='float32',
name='slow_input'),
InputSpec(shape=[
None, 3, cfg.num_frames, cfg.target_size, cfg.target_size
],
dtype='float32',
name='fast_input'),
InputSpec(shape=[None, None, 4], dtype='float32', name='proposals'),
InputSpec(shape=[None, 2], dtype='float32', name='img_shape')
]]
elif model_name in ['PoseC3D']:
input_spec = [[
InputSpec(shape=[None, 1, 17, 48, 56, 56], dtype='float32'),
]]
elif model_name in ['YOWO']:
input_spec = [[
InputSpec(shape=[
1, 3, cfg.num_seg, cfg.target_size, cfg.target_size
],
dtype='float32'),
]]
return input_spec
def main():
args = parse_args()
cfg, model_name = trim_config(
get_config(args.config, overrides=args.override, show=False))
print(f"Building model({model_name})...")
model = build_model(cfg.MODEL)
assert osp.isfile(
args.pretrained_params
), f"pretrained params ({args.pretrained_params} is not a file path.)"
if not os.path.isdir(args.output_path):
os.makedirs(args.output_path)
print(f"Loading params from ({args.pretrained_params})...")
params = paddle.load(args.pretrained_params)
model.set_dict(params)
model.eval()
# for rep nets
for layer in model.sublayers():
if hasattr(layer, "rep") and not getattr(layer, "is_repped"):
layer.rep()
input_spec = get_input_spec(cfg.INFERENCE, model_name)
model = to_static(model, input_spec=input_spec)
paddle.jit.save(
model,
osp.join(args.output_path,
model_name if args.save_name is None else args.save_name))
print(
f"model ({model_name}) has been already saved in ({args.output_path}).")
if __name__ == "__main__":
main()