forked from osmr/imgclsmob
-
Notifications
You must be signed in to change notification settings - Fork 0
/
convert_models.py
1608 lines (1430 loc) · 82 KB
/
convert_models.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
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
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Script for converting models between frameworks (MXNet, Gluon, PyTroch, Chainer, Keras, TensorFlow).
"""
import argparse
import logging
import re
import numpy as np
from common.logger_utils import initialize_logging
def parse_args():
parser = argparse.ArgumentParser(description="Convert models (Gluon/PyTorch/Chainer/MXNet/Keras/TF/TF2)",
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument(
"--src-fwk",
type=str,
required=True,
help="source model framework name")
parser.add_argument(
"--dst-fwk",
type=str,
required=True,
help="destination model framework name")
parser.add_argument(
"--src-model",
type=str,
required=True,
help="source model name")
parser.add_argument(
"--dst-model",
type=str,
required=True,
help="destination model name")
parser.add_argument(
"--src-params",
type=str,
default="",
help="source model parameter file path")
parser.add_argument(
"--dst-params",
type=str,
default="",
help="destination model parameter file path")
parser.add_argument(
"--load-ignore-extra",
action="store_true",
help="ignore extra layers in the source PyTroch model")
parser.add_argument(
"--remove-module",
action="store_true",
help="enable if stored PyTorch model has module")
parser.add_argument(
"--src-num-classes",
type=int,
default=1000,
help="number of classes for source model")
parser.add_argument(
"--src-in-channels",
type=int,
default=3,
help="number of input channels for source model")
parser.add_argument(
"--dst-num-classes",
type=int,
default=1000,
help="number of classes for destination model")
parser.add_argument(
"--dst-in-channels",
type=int,
default=3,
help="number of input channels for destination model")
parser.add_argument(
"--save-dir",
type=str,
default="",
help="directory of saved models and log-files")
parser.add_argument(
"--logging-file-name",
type=str,
default="train.log",
help="filename of training log")
args = parser.parse_args()
return args
def prepare_src_model(src_fwk,
src_model,
src_params_file_path,
dst_fwk,
ctx,
use_cuda,
load_ignore_extra=False,
remove_module=False,
num_classes=None,
in_channels=None):
ext_src_param_keys = None
ext_src_param_keys2 = None
src_net = None
if src_fwk == "gluon":
from gluon.utils import prepare_model as prepare_model_gl
src_net = prepare_model_gl(
model_name=src_model,
use_pretrained=False,
pretrained_model_file_path=src_params_file_path,
dtype=np.float32,
tune_layers="",
classes=(num_classes if num_classes > 0 else None),
in_channels=in_channels,
ctx=ctx)
src_params = src_net._collect_params_with_prefix()
src_param_keys = list(src_params.keys())
if src_model in ["oth_resnet50_v1", "oth_resnet101_v1", "oth_resnet152_v1", "oth_resnet50_v1b",
"oth_resnet101_v1b", "oth_resnet152_v1b"]:
src_param_keys = [key for key in src_param_keys if
not (key.startswith("features.") and key.endswith(".bias"))]
if src_model in ["oth_resnet50_v1", "oth_resnet101_v1", "oth_resnet152_v1", "oth_resnet50_v1b",
"oth_resnet101_v1b", "oth_resnet152_v1b"]:
src_param_keys = [key for key in src_param_keys if
not (key.startswith("features.") and key.endswith(".bias"))]
if src_model.startswith("wrn20_10_1bit") or src_model.startswith("wrn20_10_32bit"):
src_param_keys = [key for key in src_param_keys if
not (key.startswith("features.") and
(key.endswith(".bn.gamma") or key.endswith(".bn.beta")))]
if dst_fwk == "chainer":
src_param_keys_ = src_param_keys.copy()
src_param_keys = [key for key in src_param_keys_ if (not key.endswith(".running_mean")) and
(not key.endswith(".running_var"))]
ext_src_param_keys = [key for key in src_param_keys_ if (key.endswith(".running_mean")) or
(key.endswith(".running_var"))]
if src_model in ["condensenet74_c4_g4", "condensenet74_c8_g8"]:
src_param_keys_ = src_param_keys.copy()
src_param_keys = [key for key in src_param_keys_ if (not key.endswith(".index"))]
ext_src_param_keys2 = [key for key in src_param_keys_ if (key.endswith(".index"))]
elif src_model.startswith("xdensenet"):
src_param_keys_ = src_param_keys.copy()
src_param_keys = [key for key in src_param_keys_ if (not key.endswith(".mask"))]
ext_src_param_keys2 = [key for key in src_param_keys_ if (key.endswith(".mask"))]
elif src_fwk == "pytorch":
from pytorch.utils import prepare_model as prepare_model_pt
src_net = prepare_model_pt(
model_name=src_model,
use_pretrained=False,
pretrained_model_file_path=src_params_file_path,
use_cuda=use_cuda,
use_data_parallel=False,
load_ignore_extra=load_ignore_extra,
num_classes=(num_classes if num_classes > 0 else None),
in_channels=in_channels,
remove_module=remove_module)
src_params = src_net.state_dict()
src_param_keys = list(src_params.keys())
if dst_fwk != "pytorch":
src_param_keys = [key for key in src_param_keys if not key.endswith("num_batches_tracked")]
if src_model in ["oth_shufflenetv2_wd2"]:
src_param_keys = [key for key in src_param_keys if not key.startswith("network.0.")]
if src_model.startswith("oth_dla"):
src1 = list(filter(re.compile("\.project").search, src_param_keys))
src1n = [key for key in src_param_keys if key not in src1]
src2 = []
for i in range(2, 6):
src1_i = list(filter(re.compile("level{}".format(i)).search, src1))
if len(src1_i) == 0:
continue
max_len = max([len(k) for k in src1_i])
pattern_i = [k for k in src1_i if len(k) == max_len][0][:-21]
src2_i = list(filter(re.compile(pattern_i).search, src1))
src2 += src2_i
src_param_keys = src2 + src1n
elif src_fwk == "mxnet":
import mxnet as mx
src_sym, src_arg_params, src_aux_params = mx.model.load_checkpoint(
prefix=src_params_file_path,
epoch=0)
src_params = {}
src_params.update(src_arg_params)
src_params.update(src_aux_params)
src_param_keys = list(src_params.keys())
elif src_fwk == "tensorflow":
# import tensorflow as tf
# from tensorflow_.utils import prepare_model as prepare_model_tf
# src_net = prepare_model_tf(
# model_name=src_model,
# classes=num_classes,
# use_pretrained=False,
# pretrained_model_file_path=src_params_file_path)
# src_param_keys = [v.name for v in tf.global_variables()]
# src_params = {v.name: v for v in tf.global_variables()}
src_net = None
src_params = dict(np.load(src_params_file_path))
src_param_keys = list(src_params.keys())
elif (src_fwk == "tf2") and (dst_fwk == "tfl"):
import tensorflow as tf
from tensorflow2.utils import prepare_model as prepare_model_tf2
gpus = tf.config.experimental.list_physical_devices("GPU")
if gpus:
for gpu in gpus:
tf.config.experimental.set_memory_growth(gpu, True)
src_net = prepare_model_tf2(
model_name=src_model,
use_pretrained=True,
pretrained_model_file_path="")
batch_size = 1
input_shape = ((batch_size, 3, src_net.in_size[0], src_net.in_size[1]) if
src_net.data_format == "channels_first" else
(batch_size, src_net.in_size[0], src_net.in_size[1], 3))
src_net(tf.random.normal(input_shape))
src_params = None
src_param_keys = None
else:
raise ValueError("Unsupported src fwk: {}".format(src_fwk))
return src_params, src_param_keys, ext_src_param_keys, ext_src_param_keys2, src_net
def prepare_dst_model(dst_fwk,
dst_model,
src_fwk,
ctx,
use_cuda,
num_classes=None,
in_channels=None):
if dst_fwk == "gluon":
from gluon.utils import prepare_model as prepare_model_gl
dst_net = prepare_model_gl(
model_name=dst_model,
use_pretrained=False,
pretrained_model_file_path="",
dtype=np.float32,
tune_layers="",
classes=(num_classes if num_classes > 0 else None),
in_channels=in_channels,
ctx=ctx)
dst_params = dst_net._collect_params_with_prefix()
dst_param_keys = list(dst_params.keys())
elif dst_fwk == "pytorch":
from pytorch.utils import prepare_model as prepare_model_pt
dst_net = prepare_model_pt(
model_name=dst_model,
use_pretrained=False,
pretrained_model_file_path="",
use_cuda=use_cuda,
use_data_parallel=False,
num_classes=(num_classes if num_classes > 0 else None),
in_channels=in_channels)
dst_params = dst_net.state_dict()
dst_param_keys = list(dst_params.keys())
if src_fwk != "pytorch":
dst_param_keys = [key for key in dst_param_keys if not key.endswith("num_batches_tracked")]
elif dst_fwk == "chainer":
from chainer_.utils import prepare_model as prepare_model_ch
dst_net = prepare_model_ch(
model_name=dst_model,
use_pretrained=False,
pretrained_model_file_path="")
dst_params = {i[0]: i[1] for i in dst_net.namedparams()}
dst_param_keys = list(dst_params.keys())
elif dst_fwk == "keras":
from keras_.utils import prepare_model as prepare_model_ke
dst_net = prepare_model_ke(
model_name=dst_model,
use_pretrained=False,
pretrained_model_file_path="")
# dst_param_keys = list(dst_net._arg_names) + list(dst_net._aux_names)
dst_param_keys = [v.name for v in dst_net.weights]
dst_params = {}
for layer in dst_net.layers:
if layer.name:
for weight in layer.weights:
if weight.name:
dst_params.setdefault(weight.name, []).append(weight)
dst_params[weight.name] = (layer, weight)
elif dst_fwk == "tensorflow":
import tensorflow as tf
from tensorflow_.utils import prepare_model as prepare_model_tf
dst_net = prepare_model_tf(
model_name=dst_model,
use_pretrained=False,
pretrained_model_file_path="")
dst_param_keys = [v.name for v in tf.global_variables()]
dst_params = {v.name: v for v in tf.global_variables()}
elif dst_fwk == "tf2":
import tensorflow as tf
from tensorflow2.utils import prepare_model as prepare_model_tf2
gpus = tf.config.experimental.list_physical_devices("GPU")
if gpus:
for gpu in gpus:
tf.config.experimental.set_memory_growth(gpu, True)
dst_net = prepare_model_tf2(
model_name=dst_model,
use_pretrained=False,
pretrained_model_file_path="")
batch_size = 1
input_shape = ((batch_size, 3, dst_net.in_size[0], dst_net.in_size[1]) if
dst_net.data_format == "channels_first" else
(batch_size, dst_net.in_size[0], dst_net.in_size[1], 3))
dst_net(tf.random.normal(input_shape))
dst_param_keys = [v.name for v in dst_net.weights]
dst_params = {v.name: v for v in dst_net.weights}
elif dst_fwk == "tfl":
dst_net = None
dst_params = None
dst_param_keys = None
else:
raise ValueError("Unsupported dst fwk: {}".format(dst_fwk))
return dst_params, dst_param_keys, dst_net
def convert_mx2gl(dst_net,
dst_params_file_path,
dst_params,
dst_param_keys,
src_params,
src_param_keys,
src_model,
ctx):
if src_model in ["crunet56", "crunet116"]:
src_param_keys.sort()
src_param_keys.sort(key=lambda var: ["{:10}".format(int(x)) if
x.isdigit() else x for x in re.findall(r"[^0-9]|[0-9]+", var)])
src_param_keys = [re.sub("^conv", "features.", key) for key in src_param_keys]
src_param_keys = [re.sub("^fc6", "output.1.", key) for key in src_param_keys]
src_param_keys = [re.sub('_c1x1-a', '.body.conv1.', key) for key in src_param_keys]
src_param_keys = [re.sub('_c3x3-b', '.body.conv2A.', key) for key in src_param_keys]
src_param_keys = [re.sub('_c1x1-b', '.body.conv2B.', key) for key in src_param_keys]
src_param_keys = [re.sub('_c1x1-c', '.body.conv3.', key) for key in src_param_keys]
src_param_keys = [re.sub('_x__x_1x1_bases\[dim3\]_weight$', '_x__1.body.conv1.convT.weight', key)
for key in src_param_keys]
src_param_keys = [re.sub('_x__x_3x3_bases\[dim21\]_weight$', '_x__1.body.conv2.convT.weight', key)
for key in src_param_keys]
src_param_keys = [re.sub('_x__\(1\)_1x1_bases\[dim3\]_weight$', '_x__1.body.conv1.convQ.weight', key)
for key in src_param_keys]
src_param_keys = [re.sub('_x__\(1\)_3x3_bases\[dim21\]_weight$', '_x__1.body.conv2.convQ.weight', key)
for key in src_param_keys]
src_param_keys = [re.sub('_x__\(2\)_1x1_bases\[dim3\]_weight$', '_x__7.body.conv1.convQ.weight', key)
for key in src_param_keys]
src_param_keys = [re.sub('_x__\(2\)_3x3_bases\[dim21\]_weight$', '_x__7.body.conv2.convQ.weight', key)
for key in src_param_keys]
src_param_keys = [re.sub('_x__\(3\)_1x1_bases\[dim3\]_weight$', '_x__14.body.conv1.convQ.weight', key)
for key in src_param_keys]
src_param_keys = [re.sub('_x__\(3\)_3x3_bases\[dim21\]_weight$', '_x__14.body.conv2.convQ.weight', key)
for key in src_param_keys]
src_param_keys = [re.sub('_c1x1-w\(s\/2\)', '.input_convZ.', key) for key in src_param_keys]
src_param_keys = [re.sub('_c1x1-w_weight$', '.input_convZ.conv.weight', key) for key in src_param_keys]
src_param_keys = [re.sub('_c1x1-w\(s\/1\)', '.input_conv.', key) for key in src_param_keys]
src_param_keys = [re.sub('_c1x1-w\(s\/key\)', '.identity_conv.', key) for key in src_param_keys]
src_param_keys = [re.sub('__conv_weight$', '.conv.weight', key) for key in src_param_keys]
src_param_keys = [re.sub('__bn__bn_beta$', '.bn.beta', key) for key in src_param_keys]
src_param_keys = [re.sub('__bn__bn_gamma$', '.bn.gamma', key) for key in src_param_keys]
src_param_keys = [re.sub('__bn__bn_moving_mean$', '.bn.running_mean', key) for key in src_param_keys]
src_param_keys = [re.sub('__bn__bn_moving_var$', '.bn.running_var', key) for key in src_param_keys]
src_param_keys = [re.sub('1_x_1__relu-sp__bn_', '1_x_1.conv.bnA.', key) for key in src_param_keys]
src_param_keys.sort()
src_param_keys.sort(key=lambda var: ["{:10}".format(int(x)) if
x.isdigit() else x for x in re.findall(r"[^0-9]|[0-9]+", var)])
dst_param_keys.sort()
dst_param_keys.sort(key=lambda var: ["{:10}".format(int(x)) if
x.isdigit() else x for x in re.findall(r"[^0-9]|[0-9]+", var)])
src_param_keys = [re.sub("^features\.", "conv", key) for key in src_param_keys]
src_param_keys = [re.sub('^output\.1\.', 'fc6', key) for key in src_param_keys]
src_param_keys = [re.sub('_x__1\.body\.conv1\.convT\.weight$', '_x__x_1x1_bases[dim3]_weight', key)
for key in src_param_keys]
src_param_keys = [re.sub('_x__1\.body\.conv2\.convT\.weight$', '_x__x_3x3_bases[dim21]_weight', key)
for key in src_param_keys]
src_param_keys = [re.sub('_x__1\.body\.conv1\.convQ\.weight$', '_x__(1)_1x1_bases[dim3]_weight', key)
for key in src_param_keys]
src_param_keys = [re.sub('_x__1\.body\.conv2\.convQ\.weight$', '_x__(1)_3x3_bases[dim21]_weight', key)
for key in src_param_keys]
src_param_keys = [re.sub('_x__7\.body\.conv1\.convQ\.weight$', '_x__(2)_1x1_bases[dim3]_weight', key)
for key in src_param_keys]
src_param_keys = [re.sub('_x__7\.body\.conv2\.convQ\.weight$', '_x__(2)_3x3_bases[dim21]_weight', key)
for key in src_param_keys]
src_param_keys = [re.sub('_x__14\.body\.conv1\.convQ\.weight$', '_x__(3)_1x1_bases[dim3]_weight', key)
for key in src_param_keys]
src_param_keys = [re.sub('_x__14\.body\.conv2\.convQ\.weight$', '_x__(3)_3x3_bases[dim21]_weight', key)
for key in src_param_keys]
src_param_keys = [re.sub('\.body\.conv1\.', '_c1x1-a', key) for key in src_param_keys]
src_param_keys = [re.sub('\.body\.conv2A\.', '_c3x3-b', key) for key in src_param_keys]
src_param_keys = [re.sub('\.body\.conv2B\.', '_c1x1-b', key) for key in src_param_keys]
src_param_keys = [re.sub('\.body\.conv3\.', '_c1x1-c', key) for key in src_param_keys]
src_param_keys = [re.sub('\.input_convZ\.conv\.weight$', '_c1x1-w_weight', key) for key in src_param_keys]
src_param_keys = [re.sub('\.input_convZ\.', '_c1x1-w(s/2)', key) for key in src_param_keys]
src_param_keys = [re.sub('\.input_conv\.', '_c1x1-w(s/1)', key) for key in src_param_keys]
src_param_keys = [re.sub('\.identity_conv\.', '_c1x1-w(s/key)', key) for key in src_param_keys]
src_param_keys = [re.sub('\.conv\.weight$', '__conv_weight', key) for key in src_param_keys]
src_param_keys = [re.sub('\.bn\.beta$', '__bn__bn_beta', key) for key in src_param_keys]
src_param_keys = [re.sub('\.bn\.gamma$', '__bn__bn_gamma', key) for key in src_param_keys]
src_param_keys = [re.sub('\.bn\.running_mean$', '__bn__bn_moving_mean', key) for key in src_param_keys]
src_param_keys = [re.sub('\.bn\.running_var$', '__bn__bn_moving_var', key) for key in src_param_keys]
src_param_keys = [re.sub('1_x_1\.conv\.bnA\.', '1_x_1__relu-sp__bn_', key) for key in src_param_keys]
dst_i = 0
for src_i, src_key in enumerate(src_param_keys):
dst_key = dst_param_keys[dst_i]
for tt in range(10):
if (dst_key.split('.')[-1].split('_')[-1] == src_key.split('_')[-1]) and\
(dst_params[dst_key].shape == src_params[src_key].shape):
break
assert (dst_key.split('.')[-1].split('_')[-1] == "weight")
dst_i += 1
dst_key = dst_param_keys[dst_i]
dst_i += 1
assert (dst_key.split('.')[-1].split('_')[-1] == src_key.split('_')[-1])
assert (dst_params[dst_key].shape == src_params[src_key].shape), \
"src_key={}, dst_key={}, src_shape={}, dst_shape={}".format(
src_key, dst_key, src_params[src_key].shape, dst_params[dst_key].shape)
dst_params[dst_key]._load_init(src_params[src_key], ctx)
for param in dst_net.collect_params().values():
if param._data is not None:
continue
print("param={}".format(param))
param.initialize(ctx=ctx)
dst_net.save_parameters(dst_params_file_path)
return
elif src_model in ["igcv3_w1"]:
src_param_keys = [key.replace("seq-", "features.") for key in src_param_keys]
src_param_keys = [key.replace("fc_", "output.1.") for key in src_param_keys]
src_param_keys = [key.replace('-batchnorm_beta', '.bn.beta') for key in src_param_keys]
src_param_keys = [key.replace('-batchnorm_gamma', '.bn.gamma') for key in src_param_keys]
src_param_keys = [key.replace('-batchnorm_moving_mean', '.bn.running_mean') for key in src_param_keys]
src_param_keys = [key.replace('-batchnorm_moving_var', '.bn.running_var') for key in src_param_keys]
src_param_keys = [key.replace('-conv2d_weight', '.conv.weight') for key in src_param_keys]
src_param_keys = [key.replace('first-3x3-conv', 'features.A') for key in src_param_keys]
src_param_keys = [key.replace('last-1x1-conv', 'features.B') for key in src_param_keys]
src_param_keys = [key.replace('-exp', '.conv1') for key in src_param_keys]
src_param_keys = [key.replace('-depthwise', '.conv2') for key in src_param_keys]
src_param_keys = [key.replace('-linear', '.conv3') for key in src_param_keys]
src_param_keys = [key.replace("-block", ".block") for key in src_param_keys]
dst_param_keys = [key.replace('features.0.', 'features.A.') for key in dst_param_keys]
dst_param_keys = [key.replace('features.6.', 'features.B.') for key in dst_param_keys]
src_param_keys.sort()
src_param_keys.sort(key=lambda var: ["{:10}".format(int(x)) if
x.isdigit() else x for x in re.findall(r"[^0-9]|[0-9]+", var)])
dst_param_keys.sort()
dst_param_keys.sort(key=lambda var: ["{:10}".format(int(x)) if
x.isdigit() else x for x in re.findall(r"[^0-9]|[0-9]+", var)])
src_param_keys = [key.replace('.bn.beta', '-batchnorm_beta') for key in src_param_keys]
src_param_keys = [key.replace('.bn.gamma', '-batchnorm_gamma') for key in src_param_keys]
src_param_keys = [key.replace('.bn.running_mean', '-batchnorm_moving_mean') for key in src_param_keys]
src_param_keys = [key.replace('.bn.running_var', '-batchnorm_moving_var') for key in src_param_keys]
src_param_keys = [key.replace('.conv.weight', '-conv2d_weight') for key in src_param_keys]
src_param_keys = [key.replace('features.A', 'first-3x3-conv') for key in src_param_keys]
src_param_keys = [key.replace('features.B', 'last-1x1-conv') for key in src_param_keys]
src_param_keys = [key.replace('.conv1', '-exp') for key in src_param_keys]
src_param_keys = [key.replace('.conv2', '-depthwise', ) for key in src_param_keys]
src_param_keys = [key.replace('.conv3', '-linear') for key in src_param_keys]
src_param_keys = [key.replace("features.", "seq-") for key in src_param_keys]
src_param_keys = [key.replace("output.1.", "fc_") for key in src_param_keys]
src_param_keys = [key.replace(".block", "-block") for key in src_param_keys]
dst_param_keys = [key.replace('features.A.', 'features.0.') for key in dst_param_keys]
dst_param_keys = [key.replace('features.B.', 'features.6.') for key in dst_param_keys]
elif src_model in ["preresnet269b"]:
dst_net.features[1][0].body.conv1a.bn.initialize(ctx=ctx, verbose=True, force_reinit=True)
dst1 = list(filter(re.compile("^features.1.0.body.conv1.bn.").search, dst_param_keys))
dst_param_keys = [key for key in dst_param_keys if key not in dst1]
src_param_keys.sort()
src_param_keys.sort(key=lambda var: ["{:10}".format(int(x)) if
x.isdigit() else x for x in re.findall(r"[^0-9]|[0-9]+", var)])
src_param_keys = [re.sub('^classifier_', "output.", key) for key in src_param_keys]
src_param_keys = [re.sub('^res', "features.", key) for key in src_param_keys]
src_param_keys = [re.sub('_conv1_weight$', '_conv1_aweight', key) for key in src_param_keys]
src_param_keys = [re.sub('_conv2_weight$', '_conv2_aweight', key) for key in src_param_keys]
src_param_keys = [re.sub('_conv3_weight$', '_conv3_aweight', key) for key in src_param_keys]
src_param_keys.sort()
src_param_keys.sort(key=lambda var: ["{:10}".format(int(x)) if
x.isdigit() else x for x in re.findall(r"[^0-9]|[0-9]+", var)])
dst_param_keys.sort()
dst_param_keys.sort(key=lambda var: ["{:10}".format(int(x)) if
x.isdigit() else x for x in re.findall(r"[^0-9]|[0-9]+", var)])
src_param_keys = [re.sub("^output\.", "classifier_", key) for key in src_param_keys]
src_param_keys = [re.sub("^features\.", "res", key) for key in src_param_keys]
src_param_keys = [re.sub('_conv1_aweight$', '_conv1_weight', key) for key in src_param_keys]
src_param_keys = [re.sub('_conv2_aweight$', '_conv2_weight', key) for key in src_param_keys]
src_param_keys = [re.sub('_conv3_aweight$', '_conv3_weight', key) for key in src_param_keys]
for src_i, (src_key, dst_key) in enumerate(zip(src_param_keys, dst_param_keys)):
assert (dst_key.split('.')[-1].split('_')[-1] == src_key.split('_')[-1]), \
"src_key={}, dst_key={}, src_shape={}, dst_shape={}".format(
src_key, dst_key, src_params[src_key].shape, dst_params[dst_key].shape)
assert (dst_params[dst_key].shape == src_params[src_key].shape), \
"src_key={}, dst_key={}, src_shape={}, dst_shape={}".format(
src_key, dst_key, src_params[src_key].shape, dst_params[dst_key].shape)
dst_params[dst_key]._load_init(src_params[src_key], ctx)
for param in dst_net.collect_params().values():
if param._data is not None:
continue
print("param={}".format(param))
param.initialize(ctx=ctx)
dst_net.save_parameters(dst_params_file_path)
def convert_gl2ch(dst_net,
dst_params_file_path,
dst_params,
dst_param_keys,
src_params,
src_param_keys,
ext_src_param_keys,
ext_src_param_keys2,
src_model):
if src_model.startswith("diares") or src_model.startswith("diapreres"):
src1 = list(filter(re.compile("^features\.[0-9]*\.\d*[1-9]\d*\.attention").search, src_param_keys))
src1n = [key for key in src_param_keys if key not in src1]
src_param_keys = src1n
assert (len(src_param_keys) == len(dst_param_keys))
dst_param_keys = [key.replace("/W", "/weight") for key in dst_param_keys]
dst_param_keys = [key.replace("/post_activ/", "/stageN/post_activ/") for key in dst_param_keys]
dst_param_keys = [key.replace("/features/body/", "/features/zbody/") for key in dst_param_keys]
dst_param_keys = [key.replace("features/final_postactiv/", "features/stageN/final_postactiv/") for key in dst_param_keys]
dst_param_keys = [key.replace("features/final_block/", "features/stageN/final_block/") for key in dst_param_keys]
dst_param_keys = [key.replace("/final_block/", "/zfinal_block/") for key in dst_param_keys]
dst_param_keys = [key.replace("features/final_conv/", "features/stageN/final_conv/") for key in dst_param_keys]
dst_param_keys = [key.replace("/stem1_unit/", "/stage0/stem1_unit/") for key in dst_param_keys]
dst_param_keys = [key.replace("/stem2_unit/", "/stage0/stem2_unit/") for key in dst_param_keys]
if not src_model.startswith("ibppose_coco"):
dst_param_keys = [key.replace("/hg/", "/stage1_hg/") for key in dst_param_keys]
if src_model.startswith("centernet"):
dst_param_keys = [key.replace("/unit", "/a_unit") for key in dst_param_keys]
dst_param_keys = [key.replace("/reg_block/", "/z_reg_block/") for key in dst_param_keys]
src_param_keys.sort()
src_param_keys.sort(key=lambda var: ["{:10}".format(int(x)) if
x.isdigit() else x for x in re.findall(r"[^0-9]|[0-9]+", var)])
dst_param_keys.sort()
dst_param_keys.sort(key=lambda var: ["{:10}".format(int(x)) if
x.isdigit() else x for x in re.findall(r"[^0-9]|[0-9]+", var)])
dst_param_keys = [key.replace("/weight", "/W") for key in dst_param_keys]
dst_param_keys = [key.replace("/zfinal_block/", "/final_block/") for key in dst_param_keys]
dst_param_keys = [key.replace("/stageN/post_activ/", "/post_activ/") for key in dst_param_keys]
dst_param_keys = [key.replace("/stageN/final_postactiv/", "/final_postactiv/") for key in dst_param_keys]
dst_param_keys = [key.replace("/stageN/final_block/", "/final_block/") for key in dst_param_keys]
dst_param_keys = [key.replace("/features/zbody/", "/features/body/") for key in dst_param_keys]
dst_param_keys = [key.replace("features/stageN/final_conv/", "features/final_conv/") for key in dst_param_keys]
dst_param_keys = [key.replace("/stage0/stem1_unit/", "/stem1_unit/") for key in dst_param_keys]
dst_param_keys = [key.replace("/stage0/stem2_unit/", "/stem2_unit/") for key in dst_param_keys]
if not src_model.startswith("ibppose_coco"):
dst_param_keys = [key.replace("/stage1_hg/", "/hg/") for key in dst_param_keys]
if src_model.startswith("centernet"):
dst_param_keys = [key.replace("/a_unit", "/unit") for key in dst_param_keys]
dst_param_keys = [key.replace("/z_reg_block/", "/reg_block/") for key in dst_param_keys]
if src_model.startswith("wrn20_10_1bit") or src_model.startswith("wrn20_10_32bit"):
ext2_src_param_keys = [key.replace('.conv.weight', '.bn.beta') for key in src_param_keys if
key.endswith(".conv.weight")]
ext2_src_param_keys.append("features.4.bn.beta")
ext2_dst_param_keys = [key.replace("/conv/W", "/bn/beta") for key in dst_param_keys if key.endswith("/conv/W")]
ext2_dst_param_keys.append("/features/post_activ/bn/beta")
ext3_src_param_keys = {".".join(v.split(".")[:-1]): i for i, v in enumerate(ext2_src_param_keys)}
ext3_dst_param_keys = list(map(lambda x: x.split("/")[1:-1], ext2_dst_param_keys))
else:
ext2_src_param_keys = [key for key in src_param_keys if key.endswith(".beta")]
ext2_dst_param_keys = [key for key in dst_param_keys if key.endswith("/beta")]
ext3_src_param_keys = {".".join(v.split(".")[:-1]): i for i, v in enumerate(ext2_src_param_keys)}
ext3_dst_param_keys = list(map(lambda x: x.split("/")[1:-1], ext2_dst_param_keys))
for i, src_key in enumerate(ext_src_param_keys):
src_key1 = src_key.split(".")[-1]
src_key2 = ".".join(src_key.split(".")[:-1])
dst_ind = ext3_src_param_keys[src_key2]
dst_path = ext3_dst_param_keys[dst_ind]
obj = dst_net
for j, sub_path in enumerate(dst_path):
obj = getattr(obj, sub_path)
if src_key1 == 'running_mean':
assert (obj.avg_mean.shape == src_params[src_key].shape), \
"src_key={}, dst_path={}, src_shape={}, obj.avg_mean.shape={}".format(
src_key, dst_path, src_params[src_key].shape, obj.avg_mean.shape)
obj.avg_mean = src_params[src_key]._data[0].asnumpy()
elif src_key1 == 'running_var':
assert (obj.avg_var.shape == src_params[src_key].shape)
obj.avg_var = src_params[src_key]._data[0].asnumpy()
if src_model in ["condensenet74_c4_g4", "condensenet74_c8_g8"]:
assert (dst_net.output.fc.index.shape == src_params["output.1.index"].shape)
dst_net.output.fc.index = src_params["output.1.index"]._data[0].asnumpy().astype(np.int32)
ext_src_param_keys2.remove("output.1.index")
ext2_src_param_keys = [key for key in src_param_keys if key.endswith(".conv1.conv.weight")]
ext2_dst_param_keys = [key for key in dst_param_keys if key.endswith("/conv1/conv/W")]
ext3_src_param_keys = {".".join(v.split(".")[:-2]): i for i, v in enumerate(ext2_src_param_keys)}
ext3_dst_param_keys = list(map(lambda x: x.split("/")[1:-2], ext2_dst_param_keys))
for i, src_key in enumerate(ext_src_param_keys2):
src_key2 = ".".join(src_key.split(".")[:-1])
dst_ind = ext3_src_param_keys[src_key2]
dst_path = ext3_dst_param_keys[dst_ind]
obj = dst_net
for j, sub_path in enumerate(dst_path):
obj = getattr(obj, sub_path)
assert (obj.index.shape == src_params[src_key].shape), \
"src_key={}, dst_path={}, src_shape={}, obj.index.shape={}".format(
src_key, dst_path, src_params[src_key].shape, obj.index.shape)
obj.index = src_params[src_key]._data[0].asnumpy().astype(np.int32)
elif src_model.startswith("xdensenet"):
ext2_src_param_keys = [key for key in src_param_keys if key.endswith(".conv1.conv.weight")] +\
[key for key in src_param_keys if key.endswith(".conv2.conv.weight")]
ext2_dst_param_keys = [key for key in dst_param_keys if key.endswith("/conv1/conv/W")] +\
[key for key in dst_param_keys if key.endswith("/conv2/conv/W")]
ext3_src_param_keys = {".".join(v.split(".")[:-1]): i for i, v in enumerate(ext2_src_param_keys)}
ext3_dst_param_keys = list(map(lambda x: x.split("/")[1:-1], ext2_dst_param_keys))
for i, src_key in enumerate(ext_src_param_keys2):
src_key2 = ".".join(src_key.split(".")[:-1])
dst_ind = ext3_src_param_keys[src_key2]
dst_path = ext3_dst_param_keys[dst_ind]
obj = dst_net
for j, sub_path in enumerate(dst_path):
obj = getattr(obj, sub_path)
assert (obj.mask.shape == src_params[src_key].shape), \
"src_key={}, dst_path={}, src_shape={}, obj.index.shape={}".format(
src_key, dst_path, src_params[src_key].shape, obj.mask.shape)
obj.mask = src_params[src_key]._data[0].asnumpy()
for i, (src_key, dst_key) in enumerate(zip(src_param_keys, dst_param_keys)):
assert (dst_params[dst_key].array.shape == src_params[src_key].shape), \
"src_key={}, dst_key={}, src_shape={}, dst_shape={}".format(
src_key, dst_key, src_params[src_key].shape, dst_params[dst_key].array.shape)
dst_params[dst_key].array = src_params[src_key]._data[0].asnumpy()
# print("src_key={}, dst_key={}, src_shape={}, dst_shape={}".format(
# src_key, dst_key, src_params[src_key].shape, dst_params[dst_key].array.shape))
from chainer.serializers import save_npz
save_npz(
file=dst_params_file_path,
obj=dst_net)
def convert_gl2gl(dst_net,
dst_params_file_path,
dst_params,
dst_param_keys,
src_params,
src_param_keys,
finetune,
src_model,
ctx):
if src_model.startswith("oth_danet_resnet"):
src6 = list(filter(re.compile("^head.sa.gamma").search, src_param_keys))
src6n = [key for key in src_param_keys if key not in src6]
src_param_keys = src6n + src6
src7 = list(filter(re.compile("^head.conv51").search, src_param_keys))
src7n = [key for key in src_param_keys if key not in src7]
src_param_keys = src7n + src7
src8 = list(filter(re.compile("^head.conv6").search, src_param_keys))
src8n = [key for key in src_param_keys if key not in src8]
src_param_keys = src8n + src8
src1 = list(filter(re.compile("^head.conv5c").search, src_param_keys))
src1n = [key for key in src_param_keys if key not in src1]
src_param_keys = src1n + src1
src2 = list(filter(re.compile("^head.sc").search, src_param_keys))
src2n = [key for key in src_param_keys if key not in src2]
src_param_keys = src2n + src2
src3 = list(filter(re.compile("^head.conv52").search, src_param_keys))
src3n = [key for key in src_param_keys if key not in src3]
src_param_keys = src3n + src3
src4 = list(filter(re.compile("^head.conv7").search, src_param_keys))
src4n = [key for key in src_param_keys if key not in src4]
src_param_keys = src4n + src4
src5 = list(filter(re.compile("^head.conv8").search, src_param_keys))
src5n = [key for key in src_param_keys if key not in src5]
src_param_keys = src5n + src5
elif src_model.startswith("oth_icnet_resnet50_citys"):
src1 = list(filter(re.compile("^conv_sub1").search, src_param_keys))
src1n = [key for key in src_param_keys if key not in src1]
src_param_keys = src1 + src1n
src2 = list(filter(re.compile("^head").search, src_param_keys))
src2n = [key for key in src_param_keys if key not in src2]
src_param_keys = src2n + src2
elif src_model.startswith("oth_fastscnn_citys"):
src1 = list(filter(re.compile("^feature_fusion").search, src_param_keys))
src1n = [key for key in src_param_keys if key not in src1]
src_param_keys = src1n + src1
dst0 = list(filter(re.compile("^fusion").search, dst_param_keys))
dst0n = [key for key in dst_param_keys if key not in dst0]
dst_param_keys = dst0n + dst0
dst1 = list(filter(re.compile("^fusion.low_pw_conv.bn").search, dst_param_keys))
dst1n = [key for key in dst_param_keys if key not in dst1]
dst_param_keys = dst1n + dst1
dst2 = list(filter(re.compile("^fusion.high_conv.bn").search, dst_param_keys))
dst2n = [key for key in dst_param_keys if key not in dst2]
dst_param_keys = dst2n + dst2
for i, (src_key, dst_key) in enumerate(zip(src_param_keys, dst_param_keys)):
if dst_params[dst_key].shape != src_params[src_key].shape:
logging.warning(
"dst_param.shape != src_param.shape, src_key={}, dst_key={}, src_shape={}, dst_shape={}".format(
src_key, dst_key, src_params[src_key].shape, dst_params[dst_key].shape))
if finetune:
continue
else:
raise ValueError
if dst_key.split('.')[-1] != src_key.split('.')[-1]:
logging.warning(
"dst_key.suff != src_key.suff, src_key={}, dst_key={}, src_shape={}, dst_shape={}".format(
src_key, dst_key, src_params[src_key].shape, dst_params[dst_key].shape))
dst_params[dst_key]._load_init(src_params[src_key]._data[0], ctx)
dst_net.save_parameters(dst_params_file_path)
def convert_gl2ke(dst_net,
dst_params_file_path,
dst_params,
dst_param_keys,
src_params,
src_param_keys):
import mxnet as mx
dst_param_keys = [key.replace("/post_activ/", "/stageN/post_activ/") for key in dst_param_keys]
dst_param_keys = [key.replace("/final_block/", "/stageN/final_block/") for key in dst_param_keys]
dst_param_keys = [key.replace("/stem1_unit/", "/stage0/stem1_unit/") for key in dst_param_keys]
dst_param_keys = [key.replace("/stem2_unit/", "/stage0/stem2_unit/") for key in dst_param_keys]
src_param_keys.sort()
src_param_keys.sort(key=lambda var: ["{:10}".format(int(x)) if
x.isdigit() else x for x in re.findall(r"[^0-9]|[0-9]+", var)])
dst_param_keys.sort()
dst_param_keys.sort(key=lambda var: ["{:10}".format(int(x)) if
x.isdigit() else x for x in re.findall(r"[^0-9]|[0-9]+", var)])
dst_param_keys = [key.replace("/stageN/post_activ/", "/post_activ/") for key in dst_param_keys]
dst_param_keys = [key.replace("/stageN/final_block/", "/final_block/") for key in dst_param_keys]
dst_param_keys = [key.replace("/stage0/stem1_unit/", "/stem1_unit/") for key in dst_param_keys]
dst_param_keys = [key.replace("/stage0/stem2_unit/", "/stem2_unit/") for key in dst_param_keys]
dst_param_keys_orig = dst_param_keys.copy()
dst_param_keys = [s[:(s.find("convgroup") + 9)] + "/" + s.split("/")[-1] if s.find("convgroup") >= 0 else s
for s in dst_param_keys]
dst_param_keys_uniq, dst_param_keys_index = np.unique(dst_param_keys, return_index=True)
dst_param_keys = list(dst_param_keys_uniq[dst_param_keys_index.argsort()])
# dst_param_keys = list(np.unique(dst_param_keys))
assert (len(src_param_keys) == len(dst_param_keys))
def process_width(src_key, dst_key, src_weight):
dst_layer = dst_params[dst_key][0]
dst_weight = dst_params[dst_key][1]
if (dst_layer.__class__.__name__ in ["Conv2D"]) and dst_key.endswith("kernel1") and\
(dst_layer.data_format == "channels_last"):
src_weight = np.transpose(src_weight, (2, 3, 1, 0))
if (dst_layer.__class__.__name__ in ["DepthwiseConv2D"]) and dst_key.endswith("kernel1") and\
(dst_layer.data_format == "channels_last"):
src_weight = np.transpose(src_weight, (2, 3, 0, 1))
if (dst_layer.__class__.__name__ in ["Dense"]) and dst_key.endswith("kernel1"):
src_weight = np.transpose(src_weight, (1, 0))
assert (dst_weight._keras_shape == src_weight.shape), \
"src_key={}, dst_key={}, src_shape={}, dst_shape={}".format(
src_key, dst_key, src_weight.shape, dst_weight._keras_shape)
# print("src_key={}, dst_key={}, src_shape={}, dst_shape={}".format(
# src_key, dst_key, src_weight.shape, dst_weight._keras_shape))
dst_weight.bind(mx.nd.array(src_weight))
for i, (src_key, dst_key) in enumerate(zip(src_param_keys, dst_param_keys)):
if dst_key.find("convgroup") >= 0:
dst_key_stem = dst_key[:(dst_key.find("convgroup") + 9)]
dst_keys = [s for s in dst_param_keys_orig if s.startswith(dst_key_stem)]
if src_key.endswith("weight"):
dst_keys = [s for s in dst_keys if s.endswith("kernel1")]
elif src_key.endswith("bias"):
dst_keys = [s for s in dst_keys if s.endswith("bias1")]
groups = len(dst_keys)
src_weight0 = src_params[src_key]._data[0]
src_weight0_list = mx.nd.split(src_weight0, axis=0, num_outputs=groups)
for gi in range(groups):
src_weight_gi = src_weight0_list[gi].asnumpy()
dst_key_gi = dst_keys[gi]
process_width(src_key, dst_key_gi, src_weight_gi)
else:
src_weight = src_params[src_key]._data[0].asnumpy()
process_width(src_key, dst_key, src_weight)
dst_net.save_weights(dst_params_file_path)
def convert_gl2tf(dst_params_file_path,
dst_params,
dst_param_keys,
src_params,
src_param_keys):
import mxnet as mx
dst_param_keys = [key.replace("/kernel:", "/weight:") for key in dst_param_keys]
dst_param_keys = [key.replace("/dw_kernel:", "/weight_dw:") for key in dst_param_keys]
dst_param_keys = [key.replace("/post_activ/", "/stageN/post_activ/") for key in dst_param_keys]
dst_param_keys = [key.replace("/final_block/", "/stageN/final_block/") for key in dst_param_keys]
dst_param_keys = [key.replace("/stem1_unit/", "/stage0/stem1_unit/") for key in dst_param_keys]
dst_param_keys = [key.replace("/stem2_unit/", "/stage0/stem2_unit/") for key in dst_param_keys]
src_param_keys.sort()
src_param_keys.sort(key=lambda var: ["{:10}".format(int(x)) if
x.isdigit() else x for x in re.findall(r"[^0-9]|[0-9]+", var)])
dst_param_keys.sort()
dst_param_keys.sort(key=lambda var: ["{:10}".format(int(x)) if
x.isdigit() else x for x in re.findall(r"[^0-9]|[0-9]+", var)])
dst_param_keys = [key.replace("/weight:", "/kernel:") for key in dst_param_keys]
dst_param_keys = [key.replace("/weight_dw:", "/dw_kernel:") for key in dst_param_keys]
dst_param_keys = [key.replace("/stageN/post_activ/", "/post_activ/") for key in dst_param_keys]
dst_param_keys = [key.replace("/stageN/final_block/", "/final_block/") for key in dst_param_keys]
dst_param_keys = [key.replace("/stage0/stem1_unit/", "/stem1_unit/") for key in dst_param_keys]
dst_param_keys = [key.replace("/stage0/stem2_unit/", "/stem2_unit/") for key in dst_param_keys]
dst_param_keys_orig = dst_param_keys.copy()
dst_param_keys = [s[:(s.find("convgroup") + 9)] + "/" + s.split("/")[-1] if s.find("convgroup") >= 0 else s
for s in dst_param_keys]
dst_param_keys_uniq, dst_param_keys_index = np.unique(dst_param_keys, return_index=True)
dst_param_keys = list(dst_param_keys_uniq[dst_param_keys_index.argsort()])
assert (len(src_param_keys) == len(dst_param_keys))
import tensorflow as tf
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
def process_width(src_key, dst_key, src_weight):
if len(src_weight.shape) == 4:
if dst_key.split("/")[-1][:-2] == "dw_kernel":
src_weight = np.transpose(src_weight, axes=(2, 3, 0, 1))
else:
src_weight = np.transpose(src_weight, axes=(2, 3, 1, 0))
elif len(src_weight.shape) == 2:
src_weight = np.transpose(src_weight, axes=(1, 0))
assert (tuple(dst_params[dst_key].get_shape().as_list()) == src_weight.shape)
sess.run(dst_params[dst_key].assign(src_weight))
# print(dst_params[dst_key].eval(sess))
for i, (src_key, dst_key) in enumerate(zip(src_param_keys, dst_param_keys)):
if dst_key.find("convgroup") >= 0:
dst_key_stem = dst_key[:(dst_key.find("convgroup") + 9)]
dst_keys = [s for s in dst_param_keys_orig if s.startswith(dst_key_stem)]
if src_key.endswith("weight"):
dst_keys = [s for s in dst_keys if s.endswith("kernel:0")]
elif src_key.endswith("bias"):
dst_keys = [s for s in dst_keys if s.endswith("bias:0")]
groups = len(dst_keys)
src_weight0 = src_params[src_key]._data[0]
src_weight0_list = mx.nd.split(src_weight0, axis=0, num_outputs=groups)
for gi in range(groups):
src_weight_gi = src_weight0_list[gi].asnumpy()
dst_key_gi = dst_keys[gi]
process_width(src_key, dst_key_gi, src_weight_gi)
else:
src_weight = src_params[src_key]._data[0].asnumpy()
process_width(src_key, dst_key, src_weight)
# saver = tf.train.Saver()
# saver.save(
# sess=sess,
# save_path=dst_params_file_path)
from tensorflow_.utils import save_model_params
save_model_params(
sess=sess,
file_path=dst_params_file_path)
def convert_gl2tf2(dst_net,
dst_params_file_path,
dst_params,
dst_param_keys,
src_params,
src_param_keys,
src_model):
if src_model.startswith("hrnet"):
src_param_keys = [key.replace(".transition.", ".atransition.") for key in src_param_keys]
src_param_keys.sort()
src_param_keys.sort(key=lambda var: ["{:10}".format(int(x)) if
x.isdigit() else x for x in re.findall(r"[^0-9]|[0-9]+", var)])
if src_model.startswith("hrnet"):
src_param_keys = [key.replace(".atransition.", ".transition.") for key in src_param_keys]
dst_param_keys = [key.replace("/kernel:", "/weight:") for key in dst_param_keys]
dst_param_keys = [key.replace("/depthwise_kernel:", "/weight_depthwise:") for key in dst_param_keys]
dst_param_keys = [key.replace("/post_activ/", "/stageN/post_activ/") for key in dst_param_keys]
if (not src_model.startswith("pspnet_")) and (not src_model.startswith("deeplabv3_")) and\
(not src_model.startswith("simplepose_")) and (not src_model.startswith("alphapose_")) and\
(not src_model.startswith("lwopenpose")):
dst_param_keys = [key.replace("/final_block/", "/stageN/final_block/") for key in dst_param_keys]
dst_param_keys = [key.replace("/final_block/", "/zfinal_block/") for key in dst_param_keys]
dst_param_keys = [key.replace("/stem1_unit/", "/stage0/stem1_unit/") for key in dst_param_keys]
dst_param_keys = [key.replace("/stem2_unit/", "/stage0/stem2_unit/") for key in dst_param_keys]
if src_model.startswith("hrnet"):
dst_param_keys = [key.replace("/transition/", "/atransition/") for key in dst_param_keys]
if src_model.startswith("hardnet"):
# dst_param_keys = [key.replace('/dw_conv/', '/z_dw_conv/') for key in dst_param_keys]
dst_param_keys = [key.replace("features/down", "features/z_down") for key in dst_param_keys]
if src_model.startswith("centernet"):
dst_param_keys = [key.replace("/unit", "/a_unit") for key in dst_param_keys]
dst_param_keys = [key.replace("/reg_block/", "/z_reg_block/") for key in dst_param_keys]
# if src_model.startswith("danet"):
# dst_param_keys = [key.replace("da_net/head/", "z_da_net/head/") for key in dst_param_keys]
dst_param_keys.sort()
dst_param_keys.sort(key=lambda var: ["{:10}".format(int(x)) if
x.isdigit() else x for x in re.findall(r"[^0-9]|[0-9]+", var)])
dst_param_keys = [key.replace("/weight:", "/kernel:") for key in dst_param_keys]
dst_param_keys = [key.replace("/weight_depthwise:", "/depthwise_kernel:") for key in dst_param_keys]
dst_param_keys = [key.replace("/zfinal_block/", "/final_block/") for key in dst_param_keys]
dst_param_keys = [key.replace("/stageN/post_activ/", "/post_activ/") for key in dst_param_keys]
if (not src_model.startswith("pspnet_")) and (not src_model.startswith("deeplabv3_")) and\
(not src_model.startswith("simplepose_")) and (not src_model.startswith("alphapose_")) and\
(not src_model.startswith("lwopenpose")):
dst_param_keys = [key.replace("/stageN/final_block/", "/final_block/") for key in dst_param_keys]
dst_param_keys = [key.replace("/stage0/stem1_unit/", "/stem1_unit/") for key in dst_param_keys]
dst_param_keys = [key.replace("/stage0/stem2_unit/", "/stem2_unit/") for key in dst_param_keys]
if src_model.startswith("hrnet"):
dst_param_keys = [key.replace("/atransition/", "/transition/") for key in dst_param_keys]
if src_model.startswith("hardnet"):
# dst_param_keys = [key.replace('/z_dw_conv/', '/dw_conv/') for key in dst_param_keys]
dst_param_keys = [key.replace("features/z_down", "features/down") for key in dst_param_keys]
if src_model.startswith("centernet"):
dst_param_keys = [key.replace("/a_unit", "/unit") for key in dst_param_keys]
dst_param_keys = [key.replace("/z_reg_block/", "/reg_block/") for key in dst_param_keys]
# if src_model.startswith("danet"):
# dst_param_keys = [key.replace("z_da_net/head/", "da_net/head/") for key in dst_param_keys]
dst_param_keys_orig = dst_param_keys.copy()
dst_param_keys = [s[:(s.find("convgroup") + 9)] + "/" + s.split("/")[-1] if s.find("convgroup") >= 0 else s
for s in dst_param_keys]
dst_param_keys_uniq, dst_param_keys_index = np.unique(dst_param_keys, return_index=True)
dst_param_keys = list(dst_param_keys_uniq[dst_param_keys_index.argsort()])
assert (len(src_param_keys) == len(dst_param_keys))
def process_width(src_key, dst_key, src_weight):
if len(src_weight.shape) == 4:
if dst_key.split("/")[-1][:-2] == "depthwise_kernel":
src_weight = np.transpose(src_weight, axes=(2, 3, 0, 1))
else:
src_weight = np.transpose(src_weight, axes=(2, 3, 1, 0))
elif len(src_weight.shape) == 2:
src_weight = np.transpose(src_weight, axes=(1, 0))
dst_weight = dst_params[dst_key]
assert (tuple(dst_weight.shape) == src_weight.shape), \
"src_key={}, dst_key={}, src_shape={}, dst_shape={}".format(
src_key, dst_key, src_weight.shape, tuple(dst_weight.shape))
dst_weight.assign(src_weight)
for i, (src_key, dst_key) in enumerate(zip(src_param_keys, dst_param_keys)):
# print("src_key={},\tsrc_key2={},\tdst_key={}".format(src_key, src_params[src_key].name, dst_key))
if dst_key.find("convgroup") >= 0:
import mxnet as mx
dst_key_stem = dst_key[:(dst_key.find("convgroup") + 9)]
dst_keys = [s for s in dst_param_keys_orig if s.startswith(dst_key_stem)]
if src_key.endswith("weight"):
dst_keys = [s for s in dst_keys if s.endswith("kernel:0")]
elif src_key.endswith("bias"):
dst_keys = [s for s in dst_keys if s.endswith("bias:0")]
groups = len(dst_keys)