forked from ysh329/darknet2caffe
-
Notifications
You must be signed in to change notification settings - Fork 0
/
net_compiler.py
1398 lines (1224 loc) · 57 KB
/
net_compiler.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
"""
net_compiler.py
Copyright 2017 Junhui Zhang <mrlittlezhu@gmail.com>
Portions Copyright 2017 Xianyi Zhang <http://xianyi.github.io> and Chaowei Wang <wangchaowei@ncic.ac.cn>
This script made to build caffe net protobuf file to inferxlite[website] .c file
"""
__author__ = "Junhui Zhang <https://mrlittlepig.github.io>"
__version__ = "0.1"
__date__ = "March 4,2017"
__copyright__ = "Copyright: 2017 Junhui Zhang; Portions: 2017 Xianyi Zhang <http://xianyi.github.io>; Portions: 2017 Chaowei Wang;"
import re
import sys
from abc import abstractmethod
DEBUG = False
def cformatparam(string_param):
cformat = ""
for cha in string_param:
if re.match('^[0-9a-zA-Z]+$', cha):
cformat += cha
return cformat
def isac(c):
"""
A simple function, which determine whether the
string element char c is belong to a decimal number
:param c: a string element type of char
:return: a bool type of determination
"""
try:
int(c)
return True
except:
if c == '.' or c == '-' or c == 'e':
return True
else:
return False
def hasannotation(string_list):
"""
Judge whether the string type parameter string_list contains annotation
"""
for c in string_list:
if c == "#":
return True
return False
def dropannotation(annotation_list):
"""
Drop out the annotation contained in annotation_list
"""
target = ""
for c in annotation_list:
if not c == "#":
target += c
else:
return target
return target
class LayerFactory(object):
"""
Layer factory used to connect layer and sublayer.
Members
----------
__layer_register: a list to store layer type, which is registered in layer system.
layer_string: contain a whole layer information.
type: all the layers type are included in __layer_register.
layer: which sotres layer object by __gen_layer__ function, using
statement exec ('self.layer = %s(self.layer_string)'%self.__type)
as self.layer = Convolution(self.layer_string) an example.
----------
"""
__layer_register = ['Input', 'Convolution', 'Deconvolution', 'Pooling',
'Crop', 'Eltwise', 'ArgMax', 'BatchNorm', 'Concat',
'Scale', 'Sigmoid', 'Softmax', 'TanH', 'ReLU', 'LRN',
'InnerProduct', 'Dropout','Reshape',
# darknet layers below
'Reorg',]
def __init__(self, layer_string=None,net_name=None):
self.layer_string = layer_string
self.type = None
self.net_name = net_name
self.layer = None
self.__init_type__()
self.__gen_layer__()
def __init_type__(self):
phase_list = self.layer_string.split('type')
phase_num = len(phase_list)
if phase_num == 1:
self.type = "Input"
elif phase_num >= 2:
self.type = phase_list[1].split('\"')[1]
def __gen_layer__(self):
if self.type in self.__layer_register:
exec ('self.layer = %s(self.layer_string,self.net_name)'%self.type)
else:
print("[WARN] Type {} layer is not in layer register".format(self.type))
type_pattern = '.*type: "(.*)"\n'
try:
layer_type = re.findall(type_pattern, self.layer_string)[0]
if DEBUG: print(layer_type)
except:
print("Can't find this layer type")
exit(-1)
class Layer(object):
"""Layer parent class"""
__phases_string = ['name', 'type', 'bottom', 'top']
modelstr="model"
datastr="data"
pdata="pdata"
context="context_id"
def __init__(self, layer_string=None,net_name=None):
self.layer_string = layer_string
self.type = None
self.name = None
self.bottom = None
self.top = None
context="context_id"
self.net_name = net_name
self.bottom_layer = None
self.num_input = None
self.num_output = None
self.interface_c = None
self.interface_criterion = None
self.other = None
self.__init_string_param__()
self.__init_top__()
self.__list_all_member__()
@abstractmethod
def __calc_ioput__(self):
"""Calculate num_input and num_output"""
pass
@abstractmethod
def __interface_c__(self):
"""Write the predestinate parameter into c type layer function"""
pass
def __debug_print__(self, string_list, printout=False):
"""Choose to print or not controled by printout"""
if printout:
print(string_list)
def __init_bottom__(self):
"""Sometimes a layer has more than one bottom, so we pull it out alone"""
bottoms_tmp = self.layer_string.split('bottom')
bottom_num = len(bottoms_tmp)
bottoms = []
if bottom_num == 1:
self.bottom = None
else:
for index in range(1, bottom_num):
bottoms.append(bottoms_tmp[index].split('\"')[1]+"_data")
self.bottom = bottoms
def __init_top__(self):
self.top += "_data"
def __init_string_param__(self):
"""
String parameters like name: "layername", key is name the value
is the string type "layername", this function finds string parameters,
which are stored in private list __phases_string, then stores the keys
values in member variables by using exec function.
"""
for phase in self.__phases_string:
if phase == 'bottom':
self.__init_bottom__()
continue
phase_list = self.layer_string.split(phase)
phase_num = len(phase_list)
if phase_num == 1:
continue
elif phase_num == 2:
exec ('self.%s=phase_list[1].split(\'\"\')[1]' % phase)
else:
member = []
for index in range(1, phase_num):
member.append(phase_list[index].split('\"')[1])
exec ('self.%s=member' % phase)
if phase == "type":
self.type = self.type[0]
self.__debug_print__("Init string param.")
def __init_number_param__(self, phases_number):
"""
Number parameters like num_output: 21, key is num_output the value
is the number 21, this function finds number parameters, which are
stored in list phases_number, then stores the keys values in member
variables by using exec function.
"""
for phase in phases_number:
phase_list = self.layer_string.split(phase)
phase_num = len(phase_list)
if phase_num == 1:
continue
elif phase_num == 2:
exec ('self.%s = self.__find_all_num__(phase_list[1])[0]' % phase)
else:
print("Error phase_num:%d" % phase_num)
self.__debug_print__("Init number param.")
def __init_decimal_param__(self, phases_decimal):
"""
Decimal parameters like eps: 0.0001, key is eps the value is the
decimal 0.0001, this function finds decimal parameters, which are
stored in list phases_decimal, then stores the keys values in member
variables by using exec function.
"""
for phase in phases_decimal:
phase_list = self.layer_string.split(phase)
phase_num = len(phase_list)
if phase_num == 1:
continue
elif phase_num >= 2:
exec ('self.%s = []' % phase)
for index in range(1, phase_num):
exec ('self.%s.append(self.__find_first_decimal__(phase_list[index].split(\':\')[1]))' % phase)
self.__debug_print__("Init decimal param.")
def __init_binary_param__(self, phase, default='false'):
"""
Binary parameters like bias_term: false, key is bias_term the value
is the bool type false, this function finds binary parameter, which
pass in as phase, then stores the keys values in member variable by
using exec function. Parameter default to set the default satus of
the phase parameter
"""
if default == 'false':
neg_default = 'true'
else:
neg_default = 'false'
phase_list = self.layer_string.split(phase)
phase_num = len(phase_list)
if phase_num == 1:
exec ('self.%s = \'%s\'' % (phase, default))
elif phase_num >= 2:
if len(phase_list[1].split(':')[1].split(default)) == 1:
exec ('self.%s = \'%s\'' % (phase, neg_default))
else:
exec ('self.%s = \'%s\'' % (phase, default))
def __find_all_num__(self, string_phase):
"""
A function to find series of numbers
:param string_phase: string type key like num_output
:return: a list stores numbers found in string_phase
"""
number = re.findall(r'(\w*[0-9]+)\w*', string_phase)
return number
def __find_first_decimal__(self, string_phase):
"""
A function to find series of decimal
:param string_phase: string type key like moving_average_fraction
:return: a list stores decimals found in string_phase
"""
decimals = ""
for index in range(len(string_phase)):
if isac(string_phase[index]):
decimals += string_phase[index]
else:
decimals += ' '
for decimal in decimals.split(' '):
if not decimal == '':
return decimal
def __list_all_member__(self, listout=False):
"""Show all member variables"""
if listout:
for name, value in vars(self).items():
if value == None:
continue
self.__debug_print__('%s = %s' % (name, value),printout=True)
class Input(Layer):
"""Input layer"""
__phases_string = ['name', 'type', 'top']
def __init__(self, layer_string=None,net_name=None):
Layer.__init__(self, layer_string,net_name)
self.dim = []
self.__init_dim__()
self.__list_all_member__()
def __init_dim__(self):
phase_list = self.layer_string.split('dim:')
phase_num = len(phase_list)
if phase_num == 1:
self.__debug_print__("Input layer %s has no input dims" % self.name, printout=True)
elif phase_num >= 2:
for index in range(1, phase_num):
self.dim.append(self.__find_all_num__(phase_list[index]))
def __init_string_param__(self):
if len(self.layer_string.split("type")) == 1 \
and len(self.layer_string.split("top")) == 1\
and len(self.layer_string.split("dim:")) >= 2:
self.name = "data"
self.type = "Input"
self.top = "data"
return
for phase in self.__phases_string:
if phase == 'bottom':
self.__init_bottom__()
continue
phase_list = self.layer_string.split(phase)
phase_num = len(phase_list)
if phase_num == 1:
continue
elif phase_num == 2:
exec ('self.%s=phase_list[1].split(\'\"\')[1]' % phase)
else:
member = []
for index in range(1, phase_num):
member.append(phase_list[index].split('\"')[1])
exec ('self.%s=member' % phase)
self.__debug_print__("Init string param.")
def __interface_c__(self):
self.interface_criterion = \
"Input(int dim1,int dim2,int dim3,int " \
"dim4,char *top,char *name)"
self.interface_c = "inferx_input("
# for d in self.dim:
# self.interface_c += "{}".format(d[0])
# self.interface_c += ','
self.interface_c += "{},".format("nchw")
self.interface_c += '{},'.format(Layer.pdata)
self.interface_c += '\"{}\",'.format(self.top)
self.interface_c += '\"{}\",'.format(self.name)
self.interface_c += '{},'.format(Layer.modelstr)
self.interface_c += '{});'.format(Layer.datastr)
def __calc_ioput__(self):
self.num_input = None
self.__debug_print__(self.name)
self.num_output = int(self.dim[1][0])
class Convolution(Layer):
"""Convolution layer"""
__phases_number = ['num_output', 'kernel_size', 'stride', 'pad',
'group', 'dilation', 'axis']
__phases_binary = ['bias_term', 'force_nd_im2col']
def __init__(self, layer_string=None,net_name=None):
self.group = 1
self.axis = 1
self.kernel_size = None
self.dilation = 1
self.stride = 1
self.pad = 0
self.bias_term = 'true'
self.force_nd_im2col = 'false'
Layer.__init__(self, layer_string,net_name)
self.__init_number_param__(self.__phases_number)
self.__init_binary_param__(self.__phases_binary[0], default='true')
self.__init_binary_param__(self.__phases_binary[1], default='false')
self.__list_all_member__()
self.kernel_h = self.kernel_size
self.kernel_w = self.kernel_size
self.stride_h = self.stride
self.stride_w = self.stride
self.pad_h = self.pad
self.pad_w = self.pad
self.activation_type = 0
def __interface_c__(self):
self.interface_criterion = \
"Convolution(int num_input,int num_output,int kernel_h,int kernel_w,int stride_h," \
"int stride_w,int pad_h,int pad_w,int group,int dilation,int axis," \
"bool bias_term,bool force_nd_im2col,char *bottom,char *top, char *name, int activation_type)"
self.interface_c = "inferx_convolution("
self.interface_c += "{},{},{},{},{},{},{},{}".\
format(self.num_input,self.num_output,self.kernel_h,self.kernel_w,
self.stride_h,self.stride_w,self.pad_h,self.pad_w)
self.interface_c += ",{},{},{}".format(self.group,self.dilation,self.axis)
self.interface_c += ",{},{}".format(self.bias_term,self.force_nd_im2col)
self.interface_c += ",\"{}\",\"{}\",\"{}\",{},{},{});".format(self.bottom_layer[0].top,self.top,self.name,Layer.modelstr,Layer.datastr, self.activation_type)
def __calc_ioput__(self):
self.num_input = self.bottom_layer[0].num_output
class Deconvolution(Convolution):
"""Deconvolution layer"""
__phases_number = ['num_output', 'kernel_size', 'stride', 'pad', 'dilation']
def __init__(self, layer_string=None,net_name=None):
Convolution.__init__(self, layer_string,net_name=None)
def __interface_c__(self):
self.interface_criterion = \
"Deconvolution(int num_input,int num_output,int kernel_h,int kernel_w," \
"int stride_h,int stride_w,int pad_h,int pad_w,int group,int dilation,int axis," \
"bool bias_term,bool force_nd_im2col,char *bottom,char *top,char *name)"
self.interface_c = "inferx_deconvolution("
self.interface_c += "{},{},{},{},{},{},{},{}". \
format(self.num_input, self.num_output, self.kernel_h, self.kernel_w,
self.stride_h, self.stride_w, self.pad_h, self.pad_w)
self.interface_c += ",{},{},{}".format(self.group, self.dilation, self.axis)
self.interface_c += ",{},{}".format(self.bias_term, self.force_nd_im2col)
self.interface_c += ",\"{}\",\"{}\",\"{}\",{},{});".format(self.bottom_layer[0].top, self.top, self.name,Layer.modelstr,Layer.datastr)
class Pooling(Layer):
"""Pooling layer"""
__phases_number = ['kernel_size', 'stride', 'pad']
__phases_binary = ['global_pooling']
__pool_phases = ['MAX', 'AVE', 'STOCHASTIC']
def __init__(self, layer_string=None,net_name=None):
Layer.__init__(self, layer_string,net_name)
self.kernel_size = None
self.stride = 1
self.pool = 'MAX'
self.global_pooling = 'false'
self.pad = 0
self.__init_number_param__(self.__phases_number)
self.__init_binary_param__(self.__phases_binary[0], default='false')
self.__init_pool__()
self.__list_all_member__()
self.kernel_h = self.kernel_size
self.kernel_w = self.kernel_size
self.stride_h = self.stride
self.stride_w = self.stride
self.pad_h = self.pad
self.pad_w = self.pad
def __init_pool__(self):
for phase in self.__pool_phases:
phase_list = self.layer_string.split(phase)
phase_num = len(phase_list)
if phase_num == 1:
self.__debug_print__("Pooling layer %s has no pool method %s." % (self.name, phase))
continue
elif phase_num == 2:
self.pool = phase
self.__debug_print__("Pooling layer %s has pool method %s." % (self.name, self.pool))
else:
self.__debug_print__("Pool layer method error.",printout=True)
def __calc_ioput__(self):
self.num_input = self.bottom_layer[0].num_output
self.num_output = self.num_input
def __interface_c__(self):
if self.global_pooling == 'true':
self.interface_criterion = \
"inferx_globalpooling(enum PoolMethod pool,char *bottom,char *top,char *name)"
self.interface_c = "inferx_globalpooling("
else:
self.interface_criterion = \
"inferx_pooling(int kernel_h,int kernel_w,int stride_h,int stride_w,int pad_h," \
"int pad_w,enum PoolMethod pool,char *bottom,char *top,char *name)"
self.interface_c = "inferx_pooling("
if (str(self.stride_h) == "1") and (str(self.stride_w) == "1"):
self.interface_c = "inferx_pooling_yolo("
self.interface_c += "{},{},{},{},{},{},". \
format(self.kernel_h,self.kernel_w,
self.stride_h,self.stride_w,self.pad_h,self.pad_w)
self.interface_c += "{}".format(self.pool)
self.interface_c += ",\"{}\",\"{}\",\"{}\",{},{});".format(self.bottom_layer[0].top, self.top, self.name,Layer.modelstr,Layer.datastr)
class Crop(Layer):
"""Crop layer"""
__phases_number = ['axis', 'offset']
def __init__(self, layer_string=None,net_name=None):
Layer.__init__(self, layer_string,net_name)
self.axis = 2
self.offset = 0
self.__init_number_param__(self.__phases_number)
self.__list_all_member__()
def __calc_ioput__(self):
self.num_input = self.bottom_layer[0].num_output
self.num_output = self.num_input
def __interface_c__(self):
self.interface_criterion = \
"Crop(int axis,int offset,char* bottom, char* bottom_mode,char *top,char *name)"
self.interface_c = "inferx_crop("
self.interface_c += "{},{}".format(self.axis, self.offset)
for index in range(len(self.bottom_layer)):
self.interface_c += ",\"{}\"".format(self.bottom_layer[index].top)
#self.interface_c += ",%d,bottom_vector" % len(self.bottom_layer)
self.interface_c += ",\"{}\"".format(self.top)
self.interface_c += ",\"{}\"".format(self.name)
self.interface_c += ",{}".format(Layer.modelstr)
self.interface_c += ",{});".format(Layer.datastr)
class Eltwise(Layer):
"""Eltwise layer"""
__eltwise_phases = ['PROD', 'SUM', 'MAX']
__phases_decimal = ['coeff']
__phases_binary = ['stable_prod_grad']
def __init__(self, layer_string=None,net_name=None):
Layer.__init__(self, layer_string,net_name)
self.operation = 'SUM'
self.stabel_prod_grad = 'true'
self.coeff = [1,1]
self.__init_eltwise__()
self.__init_binary_param__(self.__phases_binary[0], default='true')
self.__init_decimal_param__(self.__phases_decimal)
self.__list_all_member__()
def __init_eltwise__(self):
for phase in self.__eltwise_phases:
phase_list = self.layer_string.split(phase)
phase_num = len(phase_list)
if phase_num == 1:
self.__debug_print__("Eltwise layer %s has no eltwise operations named %s." % (self.name, phase))
elif phase_num == 2:
self.operation = phase
self.__debug_print__("Eltwise layer %s has eltwise operations %s." % (self.name, self.operation))
else:
self.__debug_print__("Eltwise layer %s layer method error." % self.name)
def __calc_ioput__(self):
self.num_input = self.bottom_layer[0].num_output
self.num_output = self.num_input
def __interface_c__(self):
self.interface_criterion = \
"Eltwise(int coeffs_num, float* coeffs,enum EltwiseOp operation," \
"bool stabel_prod_grad,int bottom_num,char **bottoms,char *top, char *name)"
self.interface_c = ""
for index in range(len(self.coeff)):
self.interface_c += "coeffs[%d]=%f; " % (index,self.coeff[index])
self.interface_c += "\n\tinferx_eltwise("
# for index in range(len(self.coeff)):
# self.interface_c += "{}".format(self.coeff[index])
self.interface_c += "%d,coeffs" % len(self.coeff)
self.interface_c += ",{}".format(self.operation)
self.interface_c += ",{}".format(self.stabel_prod_grad)
# for index in range(len(self.bottom_layer)):
# self.interface_c += ",\"{}\"".format(self.bottom_layer[index].top)
self.interface_c += ",%d,bottom_vector" % len(self.bottom_layer)
self.interface_c += ",\"{}\"".format(self.top)
self.interface_c += ",\"{}\"".format(self.name)
self.interface_c += ",{}".format(Layer.modelstr)
self.interface_c += ",{});".format(Layer.datastr)
class ReLU(Layer):
"""ReLU layer"""
def __init__(self, layer_string=None,net_name=None):
Layer.__init__(self, layer_string,net_name)
self.__list_all_member__()
def __calc_ioput__(self):
self.num_input = self.bottom_layer[0].num_output
self.num_output = self.num_input
def __interface_c__(self):
self.interface_criterion = \
"ReLU(char *bottom,char *top,char *name)"
self.interface_c = "inferx_relu("
for index in range(len(self.bottom_layer)):
self.interface_c += "\"{}\"".format(self.bottom_layer[index].top)
self.interface_c += ",\"{}\"".format(self.top)
self.interface_c += ",\"{}\"".format(self.name)
self.interface_c += ",{}".format(Layer.modelstr)
self.interface_c += ",{});".format(Layer.datastr)
class InnerProduct(Layer):
"""InnerProduct layer"""
__phases_number = ['num_output', 'axis']
__phases_binary = ['bias_term', 'transpose']
def __init__(self, layer_string=None,net_name=None):
Layer.__init__(self, layer_string,net_name)
self.axis = 1
self.bias_term = 'true'
self.transpose = 'false'
self.__init_binary_param__(self.__phases_binary[0], default='true')
self.__init_binary_param__(self.__phases_binary[1], default='false')
self.__init_number_param__(self.__phases_number)
def __calc_ioput__(self):
self.num_input = self.bottom_layer[0].num_output
def __interface_c__(self):
self.interface_criterion = \
"InnerProduct(int num_input,int num_output,bool bias_term," \
"bool transpose,char *bottom,char *top,char *name)"
self.interface_c = "inferx_innerproduct("
self.interface_c += "{},{}".format(self.num_input, self.num_output)
self.interface_c += ",{}".format(self.bias_term)
self.interface_c += ",{}".format(self.transpose)
for index in range(len(self.bottom_layer)):
self.interface_c += ",\"{}\"".format(self.bottom_layer[index].top)
self.interface_c += ",\"{}\"".format(self.top)
self.interface_c += ",\"{}\"".format(self.name)
self.interface_c += ",{}".format(self.modelstr)
self.interface_c += ",{});".format(Layer.datastr)
class ArgMax(Layer):
"""ArgMax layer"""
__phases_number = ['top_k', 'axis']
__phases_binary = ['out_max_val']
def __init__(self, layer_string=None,net_name=None):
Layer.__init__(self, layer_string,net_name)
self.out_max_val = 'false'
self.top_k = 1
self.axis = None
self.__init_binary_param__(self.__phases_binary[0], default='false')
self.__init_number_param__(self.__phases_number)
self.__list_all_member__()
def __calc_ioput__(self):
self.num_input = self.bottom_layer[0].num_output
self.num_output = self.num_input
def __interface_c__(self):
self.interface_criterion = \
"ArgMax(int top_k,int axis,bool out_max_val,char *bottom,char *top,char *name)"
self.interface_c = "inferx_argmax("
self.interface_c += "{},{}".format(self.top_k, self.axis)
self.interface_c += ",{}".format(self.out_max_val)
for index in range(len(self.bottom_layer)):
self.interface_c += ",\"{}\"".format(self.bottom_layer[index].top)
self.interface_c += ",\"{}\"".format(self.top)
self.interface_c += ",\"{}\"".format(self.name)
self.interface_c += ",{}".format(Layer.modelstr)
self.interface_c += ",{});".format(Layer.datastr)
class BatchNorm(Layer):
"""BatchNorm layer"""
__phases_decimal = ['moving_average_fraction', 'eps']
__phases_binary = ['use_global_stats']
def __init__(self, layer_string=None,net_name=None):
Layer.__init__(self, layer_string,net_name)
self.use_global_stats = 'true'
self.moving_average_fraction = ['0.999']
self.eps = ['1e-9']
self.__init_decimal_param__(self.__phases_decimal)
self.__init_binary_param__(self.__phases_binary[0], default='true')
self.__list_all_member__()
def __calc_ioput__(self):
self.__debug_print__(self.name)
self.num_input = self.bottom_layer[0].num_output
self.num_output = self.num_input
def __interface_c__(self):
self.interface_criterion = \
"BatchNorm(float moving_average_fraction,float eps," \
"bool use_global_stats,char *bottom,char *top,char *name)"
self.interface_c = "inferx_batchnorm("
self.interface_c += "{},{}".format(self.moving_average_fraction[0],self.eps[0])
self.interface_c += ",{}".format(self.use_global_stats)
for index in range(len(self.bottom_layer)):
self.interface_c += ",\"{}\"".format(self.bottom_layer[index].top)
self.interface_c += ",\"{}\"".format(self.top)
self.interface_c += ",\"{}\"".format(self.name)
self.interface_c += ",{}".format(Layer.modelstr)
self.interface_c += ",{});".format(Layer.datastr)
class Concat(Layer):
"""Concat layer"""
__phases_number = ['axis', 'concat_dim']
def __init__(self, layer_string=None,net_name=None):
Layer.__init__(self, layer_string,net_name)
self.axis = 1
self.concat_dim = 1
self.__init_number_param__(self.__phases_number)
self.__list_all_member__()
def __calc_ioput__(self):
self.num_input = []
self.num_output = 0
for bottom in self.bottom_layer:
self.num_input.append(bottom.num_output)
for input in self.num_input:
self.num_output += int(input)
def __interface_c__(self):
self.interface_criterion = \
"Concat(int num_output,int axis,int concat_dim," \
"int bottom_num,char **bottoms,char *top,char *name)"
self.interface_c = "inferx_concat("
self.interface_c += "{},".format(self.num_output)
self.interface_c += "{},{}".format(self.axis,self.concat_dim)
# for index in range(len(self.bottom_layer)):
# self.interface_c += ",\"{}\"".format(self.bottom_layer[index].top)
self.interface_c += ",%d,bottom_vector"%len(self.bottom_layer)
self.interface_c += ",\"{}\"".format(self.top)
self.interface_c += ",\"{}\"".format(self.name)
self.interface_c += ",{}".format(Layer.modelstr)
self.interface_c += ",{});".format(Layer.datastr)
class Scale(Layer):
"""Scale layer"""
__phases_number = ['axis', 'num_axes']
__phases_binary = ['bias_term']
def __init__(self, layer_string=None,net_name=None):
Layer.__init__(self, layer_string,net_name)
self.axis = 1
self.num_axes = 1
self.bias_term = 'false'
self.__init_number_param__(self.__phases_number)
self.__init_binary_param__(self.__phases_binary[0], default='false')
self.__list_all_member__()
def __calc_ioput__(self):
self.num_input = self.bottom_layer[0].num_output
self.num_output = self.num_input
def __interface_c__(self):
self.interface_criterion = \
"Scale(int axis,int num_axes,bool bias_term,char *bottom,char *top,char *name)"
self.interface_c = "inferx_scale("
self.interface_c += "{},{}".format(self.axis, self.num_axes)
self.interface_c += ",{}".format(self.bias_term)
for index in range(len(self.bottom_layer)):
self.interface_c += ",\"{}\"".format(self.bottom_layer[index].top)
self.interface_c += ",\"{}\"".format(self.top)
self.interface_c += ",\"{}\"".format(self.name)
self.interface_c += ",{}".format(Layer.modelstr)
self.interface_c += ",{});".format(Layer.datastr)
class Sigmoid(Layer):
"""Sigmoid layer"""
def __init__(self, layer_string=None,net_name=None):
Layer.__init__(self, layer_string,net_name)
self.__list_all_member__()
def __calc_ioput__(self):
self.num_input = self.bottom_layer[0].num_output
self.num_output = self.num_input
def __interface_c__(self):
self.interface_criterion = \
"Sigmoid(char *bottom,char *top,char *name)"
self.interface_c = "inferx_sigmoid("
for index in range(len(self.bottom_layer)):
self.interface_c += "\"{}\"".format(self.bottom_layer[index].top)
self.interface_c += ",\"{}\"".format(self.top)
self.interface_c += ",\"{}\"".format(self.name)
self.interface_c += ",{}".format(Layer.modelstr)
self.interface_c += ",{});".format(Layer.datastr)
class Softmax(Layer):
"""Softmax layer"""
__phases_number = ['axis']
def __init__(self, layer_string=None,net_name=None):
Layer.__init__(self, layer_string,net_name)
self.axis = 1
self.__init_number_param__(self.__phases_number)
self.__list_all_member__()
def __calc_ioput__(self):
self.num_input = self.bottom_layer[0].num_output
self.num_output = self.num_input
def __interface_c__(self):
self.interface_criterion = \
"Softmax(int axis,char *bottom,char *top,char *name)"
self.interface_c = "inferx_softmax("
self.interface_c += "{}".format(self.axis)
for index in range(len(self.bottom_layer)):
self.interface_c += ",\"{}\"".format(self.bottom_layer[index].top)
self.interface_c += ",\"{}\"".format(self.top)
self.interface_c += ",\"{}\"".format(self.name)
self.interface_c += ",{}".format(Layer.modelstr)
self.interface_c += ",{});".format(Layer.datastr)
class TanH(Layer):
"""TanH layer"""
def __init__(self, layer_string=None,net_name=None):
Layer.__init__(self, layer_string,net_name)
self.__list_all_member__()
def __calc_ioput__(self):
self.num_input = self.bottom_layer[0].num_output
self.num_output = self.num_input
def __interface_c__(self):
self.interface_criterion = \
"TanH(char *bottom,char *top,char *name)"
self.interface_c = "inferx_tanh("
for index in range(len(self.bottom_layer)):
self.interface_c += "\"{}\"".format(self.bottom_layer[index].top)
self.interface_c += ",\"{}\"".format(self.top)
self.interface_c += ",\"{}\"".format(self.name)
self.interface_c += ",{}".format(Layer.modelstr)
self.interface_c += ",{});".format(Layer.datastr)
class LRN(Layer):
"""LRN layer"""
__phases_decimal = ['alpha', 'beta', 'k']
__phases_number = ['local_size']
def __init__(self, layer_string=None,net_name=None):
Layer.__init__(self, layer_string,net_name)
self.local_size = 5
self.alpha = [1.0]
self.beta = [0.75]
self.k = [1.0]
self.__init_number_param__(self.__phases_number)
self.__init_decimal_param__(self.__phases_decimal)
def __calc_ioput__(self):
self.num_input = self.bottom_layer[0].num_output
self.num_output = self.num_input
def __interface_c__(self):
self.interface_criterion = \
"LRN(int local_size,float alpha,float beta,float k,char *bottom,char *top,char *name)"
self.interface_c = "inferx_LRN("
self.interface_c += "{},{},{},{}".format(self.local_size, self.alpha[0], self.beta[0],self.k[0])
for index in range(len(self.bottom_layer)):
self.interface_c += ",\"{}\"".format(self.bottom_layer[index].top)
self.interface_c += ",\"{}\"".format(self.top)
self.interface_c += ",\"{}\"".format(self.name)
self.interface_c += ",{}".format(Layer.modelstr)
self.interface_c += ",{});".format(Layer.datastr)
class Dropout(Layer):
"""Dropout layer"""
def __init__(self, layer_string,net_name=None):
Layer.__init__(self, layer_string,net_name)
class Reshape(Layer):
"""Reshape layer"""
__phases_number = ['dim']
def __init__(self, layer_string,net_name=None):
Layer.__init__(self, layer_string,net_name)
self.dim= []
self.__init_dim__()
self.__list_all_member__()
self.batch_size = self.dim[0]
self.channels = self.dim[1]
self.height = self.dim[2]
self.width = self.dim[3]
def __init_dim__(self):
phase_list = self.layer_string.split('dim:')
phase_num = len(phase_list)
if phase_num == 1:
self.__debug_print__("Input layer %s has no input dims" % self.name, printout=True)
elif phase_num >= 2:
if DEBUG: print("phase_num".format(phase_num))
if DEBUG: print(phase_list[1])
for index in range(1, phase_num):
self.dim.extend(self.__find_all_num__(phase_list[index]))
def __calc_ioput__(self):
self.num_input = self.bottom_layer[0].num_output
self.num_output = self.channels
def __interface_c__(self):
self.interface_criterion = \
"Reshape(int batch_size, int channels, int height, int weidth char *bottom, char *top char *name)"
self.interface_c = "inferx_reshape("
self.interface_c +="{},{},{},{}".\
format(self.batch_size,self.channels,self.height,self.width)
self.interface_c +=",\"{}\",\"{}\",\"{}\",{},{});".format(self.bottom_layer[0].top,self.top,self.name,Layer.modelstr,Layer.datastr)
class Reorg(Layer):
"""Reorg layer from Darknet"""
__phases_number = ['dim']
def __init__(self, layer_string,net_name=None):
Layer.__init__(self, layer_string,net_name)
self.dim= []
self.__init_dim__()
self.__list_all_member__()
self.batch_size = self.dim[0]
self.channels = self.dim[1]
self.height = self.dim[2]
self.width = self.dim[3]
def __init_dim__(self):
phase_list = self.layer_string.split('dim:')
phase_num = len(phase_list)
if phase_num == 1:
self.__debug_print__("Input layer %s has no input dims" % self.name, printout=True)
elif phase_num >= 2:
if DEBUG: print("phase_num".format(phase_num))
if DEBUG: print(phase_list[1])
for index in range(1, phase_num):
self.dim.extend(self.__find_all_num__(phase_list[index]))
def __calc_ioput__(self):
self.num_input = self.bottom_layer[0].num_output
self.num_output = self.num_input
def __interface_c__(self):
self.interface_criterion = \
"Reorg(int batch_size, int channels, int height, int weidth char *bottom, char *top char *name)"
self.interface_c = "inferx_reshape("
self.interface_c +="{},{},{},{}".\
format(self.batch_size,self.channels,self.height,self.width)
self.interface_c +=",\"{}\",\"{}\",\"{}\",{},{});".format(self.bottom_layer[0].top,self.top,self.name,Layer.modelstr,Layer.datastr)
class Net(object):
"""Convert caffe net protobuf file to inferxlite's *.c and *.h files"""
def __init__(self, proto=None):
self.__loaded = False
self.__proto = proto
self.__merge_bn=False
# this name from model ile name, special charactors removed
self.__name = None
# file name, used to save *.c, *.h files
self.__file_name = proto.replace(".prototxt", "")
self.__layers_string = None
self.__layers = []
self.non_layer_idx_list = []
self.__layernum = None
self.__log = []
self.__net = ""
self.__cfile = []
self.__read_proto__()
self.__init_layers_()
self.__link_layers__()
self.__all_layers_type = self.__all_layers_type__()
self.__write_c_format__(annotation=True)
self.__write_h_format__(annotation=True)
self.__write_non_layer_h_format__()
def __update_log__(self, log, printout=False):
"""Print log from here"""
if printout:
print(log)
self.__log.append(log)
def __update_line__(self, line, outlines, printout=False):
"""Print line from here"""
if printout:
print(line)
outlines.append(line)
def __read_proto__(self):
"""Read caffe net protobuf file"""
try:
net_lines = open(self.__proto, "r").readlines()
for line in net_lines:
if not hasannotation(line):
self.__net += line
else: