-
Notifications
You must be signed in to change notification settings - Fork 9
/
dnn_to_spatial.py
3964 lines (3552 loc) · 185 KB
/
dnn_to_spatial.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
#!/usr/bin/python
# ------------------------------------------------------------------------------
#
# dnn_to_spatial.py /path/to/model.[pb, graph, or pbtxt]
#
# Converts from TensorFlow to a Spatial Language program. Support for other
# frameworks is also planned.
#
# ------------------------------------------------------------------------------
# ========================================================================================================
# Imports
# ========================================================================================================
import tensorflow as tf
from tensorflow.python.framework import tensor_util
from tensorflow.core.framework import graph_pb2
import utils
import os
# ========================================================================================================
# Parse arguments
# ========================================================================================================
args = utils.get_args(1, 'dnn_to_spatial.py /path/to/model.[pb, graph, or pbtxt]')
model = args[0]
# ========================================================================================================
# Other Parameters
# ========================================================================================================
include_imagenet_classification = False # Can set true for CNNs using ImageNet to print classification ranking
# ========================================================================================================
# Read Model
# ========================================================================================================
input_format = model.split('.')[-1]
if input_format == 'pb':
output_graph_def = graph_pb2.GraphDef()
with open(model, "rb") as f:
output_graph_def.ParseFromString(f.read())
elif input_format in ['graph', 'pbtxt']:
output_graph_def = graph_pb2.GraphDef()
from google.protobuf import text_format
with open(model, "r") as f:
text_format.Merge(f.read(), output_graph_def)
# Make a session for the frozen graph
tf.import_graph_def(output_graph_def)
frz_sess = tf.Session()
print
summary_filename = model + '.node_list.final'
print 'Writing a graph summary to ' + summary_filename
utils.write_summary_file(summary_filename, frz_sess, output_graph_def, imported=True)
# ========================================================================================================
# Initialize Device Parameters
# ========================================================================================================
device = 'vu9p' # In the future, support other devices and read this as an input to the script
device_params = utils.read_config_file('devices/' + device + '.cfg')
# ========================================================================================================
# Initialize Design Parameters
# ========================================================================================================
reuse = True
reuse_FC = False
reuse_schedule = {}
reuse_args = {} # Map layer to arg list, and each arg in that arg list to a value list
reuse_weight_dram = {} # Map layer to weight dram list, and each dram in that list to a file list
reuse_fc_weight_dram = {} # Map layer to weight dram list, and each dram in that list to a file list
reuse_tmp_dram_dims = {} # Map tmp DRAM to dims
reuse_tmp_dram_ordered = []
reuse_tmp_dram_children = {}
reuse_tmp_dram_parents = {}
reuse_layer_list = []
reuse_layer_to_ops = {}
reuse_layer_to_IP = {}
reuse_layer_to_kxk = {}
reuse_FC_name = ''
include_sigmoid_initialization = False
fc_section = False
max_depthwise_conv_input = None
processed_softmax = False
# ========================================================================================================
# Initialize each code block
# ========================================================================================================
app_name = model.split('/')[-1].split('.')[0].replace('_', '').replace('-', '').lower()
if include_imagenet_classification:
args_help = '"/path/to/input.csv /path/to/classes.csv /path/to/weights/directory/"'
else:
args_help = '"/path/to/input.csv /path/to/weights/directory/"'
file_opening = '''package spatial.tests.apps
import spatial.dsl._
import utils.math._
@spatial class ''' + app_name + ''' extends SpatialTest {
// override def compileArgs: Args = super.compileArgs and "--forceFuseFMA" and "--noBindParallels"
override def runtimeArgs: Args = ''' + args_help + '''
type T = FixPt[TRUE,_10,_22]
'''
var_declarations = ''
accel_global_LUTs = ''
accel_defs = ''
accel_function = ''
data_mem_declarations = ''
data_mem_set = ''
tmp_mem_declarations = ''
tmp_mem_declarations_no_reuse = ''
weight_mem_declarations = ''
weight_mem_declarations_no_reuse = ''
# accel_function_args = []
host_before_accel = ''' def main(args: Array[String]): Unit = {
val debug:scala.Boolean = false
'''
# ========================================================================================================
# Global Data Structures
# ========================================================================================================
# Now that we've read the graph, we can go over the nodes. Each node is a NodeDef object.
# Contents of proto objects (node, op and attr) are here:
# https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/framework/node_def.proto
# https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/framework/op_def.proto
# https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/framework/attr_value.proto
global_i_number = 0
global_c_number = 0
global_val_number = 0
name_to_tmpvar = {} # Instead of tmp, could use a legalized version of node.name (e.g. '/' -> '_')
# Refactor: name_to_node is only needed when we do not write the output for a node until we have gone through more of
# the graph. Currently this is done only for consts, which either (1) are written to disk after the graph is processed
# or (2) are scalars used by later nodes. (1) already exists in constants_to_write_to_disk, so name_to_node could be renamed
# "tmpvar to scalars" and store only that case. Also, that map for (2) could be combined with extra_paddings,
# since that is a special-case of (2)
name_to_node = {} # only used to get constant values
extra_paddings = {}
unpadded_dims = {}
# This is like name to node but tmpvar to node, for consts.
# Could use name to node but this is more specialized and can replace name_to_node
# by going name -> tmpvar then tmpvar -> node
constants_to_write_to_disk = {}
weight_files_to_concat = []
input_ops = ['Placeholder', 'DecodeJpeg']#, 'RandomUniform']
ops_to_skip = ['Softmax', 'Identity', 'NoOp', 'Squeeze', 'Shape']
# If we see these and they connect to a jpeg, skip them in Accel and do the op
# on host instead (e.g. decode, resize + interpolate using a Scala library)
jpeg_processing_ops = ['Cast', 'ExpandDims', 'ResizeBilinear', 'Sub', 'Mul']
nodes_used_for_jpeg_read = set()
# Same as above, but for preprocessing
preprocessing_ops = ['Mul', 'Split', 'Sub', 'Concat', 'ConcatV2', 'Pad']
nodes_used_for_preprocessing = set()
# Information across nodes, e.g. for fusion and whether an output is in SRAM and is 2D
conv_input_output_from_DRAM = True
# output_to_SRAM_or_DRAM = {} # Can also make this a map
input_dram_already_created = set()
# Fusion
nodes_already_processed_through_fusion = set()
# Skip nodes for inference
# "Add a 50% dropout during training only. Dropout also scales
# activations such that no rescaling is needed at evaluation time."
superops_to_skip = ['dropout']
current_dropout_input = ''
# Store reshape information per node
tmpvar_to_reshape_string = {}
# Proto to Spatial type translation map
# https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/framework/types.proto
proto_type_to_spatial_type = {}
proto_type_to_spatial_type[1] = 'T'
proto_type_to_spatial_type[3] = 'Int32'
proto_type_to_spatial_type[10] = 'Bool'
proto_type_to_spatial_type[12] = 'UInt8'
num_classes = None # result of final add / softmax
final_node = None
final_node_SRAM = None
# ========================================================================================================
# Global helper functions
# ========================================================================================================
def closest_pow_2(n):
closest = 1
while True:
if closest*2 > n:
break
closest = closest*2
return int(closest)
# Return dimensions of a Const node
def get_const_dims(node):
input_sizes = []
for dim in node.attr['value'].tensor.tensor_shape.dim:
input_sizes.append(str(dim.size))
return input_sizes
# There are cases where large blocking of weights is not needed to reduce data
# read bandwidth, e.g. when data is in SRAM or inCh is small so data is small.
# In such cases there is no need to load B*k*k in kxk convolution since B is small
# and usually W load par is too. In these cases it is better to skip the reshape.
def skip_weight_reshape(dims):
global conv_input_output_from_DRAM
if conv_input_output_from_DRAM:
# If data is small, B is also small so no need to reshape
return int(dims[2]) <= 3
else:
# Since data in SRAM is smaller, use blocking for all but
# grayscale to reduce overhead of pipeline iterations
return int(dims[2]) == 1
def reformat_memory(dims):
if len(dims) == 4:
# 1x1 convolution weights are 4D but can be represented as 2D
if dims[0] == '1':
assert dims[1] == '1'
return [dims[3], dims[2]]
# elif skip_weight_reshape(dims):
# Concat if small data since little compute, i.e. loads must be fast
# (vs. if large data then we could save cycles by doing 3,49 as 3*49
# but not bottleneck so that way can save a reshape)
elif not conv_input_output_from_DRAM:
return [dims[3], dims[2] + '*' + dims[0] + '*' + dims[1]]
return [dims[3], dims[2], dims[0] + '*' + dims[1]]
elif len(dims) == 3:
return [dims[2], dims[0], dims[1]]
elif len(dims) == 2:
return [dims[1], dims[0]]
else:
return dims
# ========================================================================================================
# Generate Spatial for each node
# ========================================================================================================
# Initial traversal: Count number of FC layers
num_matmul = 0
for node in output_graph_def.node:
if node.op == 'MatMul':
num_matmul += 1
# Alternatively can always re-use (i.e. >1)
if num_matmul > device_params['num_SLR_regions']:
reuse_FC = True
# Initial traversal: If Relu is used, see if Relu or Relu6
num_relu = 0
num_relu6 = 0
for node in output_graph_def.node:
if node.op == 'Relu':
num_relu += 1
elif node.op == 'Relu6':
num_relu6 += 1
# For now assuming only one type is used, but not hard to support both,
# just need to add another mux.
assert num_relu == 0 or num_relu6 == 0
if num_relu6 > 0:
use_relu6 = True
else:
use_relu6 = False
# Initial traversal: ops with no inputs
# Make a directory for weights
weight_path = '.'.join(model.split('.')[0:-1]) + '_spatial_weights/'
if not os.path.exists(weight_path):
os.mkdir(weight_path)
node_idx = 0
while(True):
if node_idx >= len(output_graph_def.node):
break
node = output_graph_def.node[node_idx]
node_idx += 1
name_to_node[node.name] = node
# ------------------------------------------------------------------------------------------------------
# Skip certain nodes
# ------------------------------------------------------------------------------------------------------
# Do superop check first since it might contain other nodes to skip
if node.name.split('/')[0] in superops_to_skip:
continue
# ------------------------------------------------------------------------------------------------------
# Input or constant
# ------------------------------------------------------------------------------------------------------
# Check if input op or constant
if node.op in input_ops:
# See if we want to skip this
if node.attr["shape"].shape.unknown_rank:
continue
tmpvar = 'i' + str(global_i_number)
name_to_tmpvar[node.name] = tmpvar
if node.op == 'Placeholder':
nodes_used_for_preprocessing.add(node.name)
input_sizes = []
# Can use get_tensor_dims_from_input_name for this
for dim in node.attr["shape"].shape.dim[1:]: # Recall Tensorflow stores in NHWC
input_sizes.append(str(dim.size))
assert len(node.input) == 0
host_before_accel += ' val ' + tmpvar + ' = loadCSV1D[T](args(' + str(global_i_number) + '), "\\n")'
if len(input_sizes) > 1:
host_before_accel += '.reshape(' + ','.join(reformat_memory(input_sizes)) + ')'
# Omit reshape string for this because we just reshaped it above if it needed reshaping.
# If there is an explicit Reshape called on it, it will be added back here later.
# tmpvar_to_reshape_string[tmpvar] = ','.join(reformat_memory(input_sizes))
# Check: if this input is small, keep in SRAM
total_input_size = 1
for dim in node.attr["shape"].shape.dim[1:]:
total_input_size = total_input_size * dim.size
if total_input_size < device_params['image_buffer_size']:
conv_input_output_from_DRAM = False
reuse = False # Can also check number of layers directly. Smaller input tends to = fewer layers.
# reuse_FC = False # Can also check size of 1st FC, but if conv is in SRAM then FC data will also be small
elif node.op == 'DecodeJpeg':
assert len(node.input) == 1
nodes_used_for_jpeg_read.add(node.name)
host_before_accel += ' val ' + tmpvar + ' = DecodeJPEG("input' + str(global_i_number) + '.jpg")'
host_before_accel += "\n"
global_i_number += 1
# accel_function_args.append(tmpvar)
continue
# Constants
elif node.op == 'Const':
assert len(node.input) == 0
dtype = proto_type_to_spatial_type[node.attr['value'].tensor.dtype]
# Check if we should store these weights as a file or hard-code them
# E.g. sometimes there is a tensor content but it is only 1 word
store_weights_as_file = False
scalar_weight_is_in_tensor = False
pads_are_in_tensor = False
if node.attr['value'].tensor.tensor_content:
store_weights_as_file = True
# dtype 1 means tf DT_FLOAT
if len(node.attr['value'].tensor.tensor_content) == 4 and node.attr['value'].tensor.dtype in [1,3]:
store_weights_as_file = False
scalar_weight_is_in_tensor = True
elif len(node.attr['value'].tensor.tensor_content) == 4*8 and node.attr['value'].tensor.dtype in [3]: # Paddings
assert 'paddings' in node.name
store_weights_as_file = False
pads_are_in_tensor = True
if store_weights_as_file:
tmpvar = 'c' + str(global_c_number)
name_to_tmpvar[node.name] = tmpvar
# Store this node and later save it to file
if not '/shape' in node.name and not '/reduction_indices' in node.name:
constants_to_write_to_disk[tmpvar] = node
input_sizes = get_const_dims(node)
tmpvar_to_reshape_string[tmpvar] = ','.join(reformat_memory(input_sizes))
global_c_number += 1
# accel_function_args.append(tmpvar)
elif pads_are_in_tensor:
tmp_file = open('TMP_FILE_CONST', 'wb')
tmp_file.write(node.attr['value'].tensor.tensor_content)
tmp_file.close()
import numpy as np
tmp_in = np.fromfile('TMP_FILE_CONST', dtype=np.int32, count=-1)
assert tmp_in.size == 8
# print 'extra_paddings[' + node.name + '] = ' + str(tmp_in.tolist())
extra_paddings[node.name] = tmp_in.tolist()
name_to_tmpvar[node.name] = None
else:
val = ''
if scalar_weight_is_in_tensor:
tmp_file = open('TMP_FILE_CONST', 'wb')
tmp_file.write(node.attr['value'].tensor.tensor_content)
tmp_file.close()
import numpy as np
tmp_in = np.fromfile('TMP_FILE_CONST', dtype=np.float32, count=-1)
assert tmp_in.size == 1
val = str(tmp_in[0])
elif node.attr['value'].tensor.float_val:
val = str(node.attr['value'].tensor.float_val[0])
elif node.attr['value'].tensor.int_val:
val = str(node.attr['value'].tensor.int_val[0])
#elif node.attr['value'].tensor.bool_val:
# val = str(node.attr['value'].tensor.bool_val[0])
assert val
name_to_tmpvar[node.name] = val + '.to[' + dtype + ']'
# print node.name + ' = ' + str(val)
continue
# Next traversal: remaining ops with inputs
node_idx = 0
while(True):
# Define helpers used by various ops
def burst_align(dim):
import math
burst_size = 16
return int(math.ceil(float(dim)/float(burst_size))*int(burst_size))
def get_tensor_dims_from_input_name(tensor_name, frz_sess):
if ':' in tensor_name:
tensor_name = 'import/' + tensor_name
else:
tensor_name = 'import/' + tensor_name + ':0'
tensor = frz_sess.graph.get_tensor_by_name(tensor_name)
"""
print tf.shape(tensor)
with tf.Session() as sess:
print sess.run(tf.shape(tensor))
"""
assert tensor.get_shape()
return tensor.get_shape()
def get_dims_str(tensor_name, frz_sess, ignore_initial=0):
dims_tensor = get_tensor_dims_from_input_name(tensor_name, frz_sess)[ignore_initial:]
if not dims_tensor.dims:
# Sometimes an input to a node has no dims, but we
# can infer them from the sizes of later ops
return None
dims = dims_tensor.as_list()
dims_str = []
for dim in dims:
if dim:
dims_str.append(str(dim))
else:
dims_str.append(None)
# print dims_str
return dims_str
if node_idx >= len(output_graph_def.node):
# Done processing nodes, so make output the last node's output
assert num_classes
data_mem_declarations += ' val ' + final_node + '_DRAM = DRAM[T](' + str(burst_align(num_classes)) + ')' + "\n"
accel_function += ' ' + final_node + '_DRAM(0::' + str(burst_align(num_classes)) + ') store ' + final_node_SRAM + '_SRAM' + "\n"
break
node = output_graph_def.node[node_idx]
node_idx += 1
name_to_node[node.name] = node
# ------------------------------------------------------------------------------------------------------
# Skip certain nodes
# ------------------------------------------------------------------------------------------------------
# Do superop check first since it might contain other nodes to skip
if node.name.split('/')[0] in superops_to_skip:
superop = node.name.split('/')[0]
if superop == 'dropout':
if node.name in ['dropout/truediv', 'dropout/div', 'dropout/dropout/div']:
assert len(node.input) == 2
current_dropout_input = node.input[0]
elif node.name in ['dropout/mul', 'dropout/dropout/mul']:
assert current_dropout_input
name_to_tmpvar[node.name] = name_to_tmpvar[current_dropout_input]
continue
if node.name in nodes_already_processed_through_fusion:
continue
if node.op in jpeg_processing_ops:
if node.input[0] in nodes_used_for_jpeg_read:
nodes_used_for_jpeg_read.add(node.name)
name_to_tmpvar[node.name] = name_to_tmpvar[node.input[0]]
host_before_accel += ' // Apply ' + node.name + ' to ' + name_to_tmpvar[node.name]
if len(node.input) > 1:
host_before_accel += ' (with value = ' + str( tensor_util.MakeNdarray(name_to_node[node.input[1]].attr['value'].tensor) ) + ')'
host_before_accel += "\n"
continue
"""
Preprocessing node pattern example:
images
op = Placeholder
mul/y
op = Const
mul
op = Mul
in0 = images
in1 = mul/y
split/split_dim
op = Const
split
op = Split
output size = (1, 224, 224, 1)
in0 = split/split_dim
in1 = mul
concat/concat_dim
op = Const
concat
op = Concat
output size = (1, 224, 224, 3)
in0 = concat/concat_dim
in1 = split:2
in2 = split:1
in3 = split
sub/y
op = Const
output size = (3,)
sub
op = Sub
output size = (1, 224, 224, 3)
in0 = concat
in1 = sub/y
"""
if node.op in preprocessing_ops:
# We have found a node type associated with preprocessing. Now check that this node is part of the initial
# preprocessing of the input, and check for all inputs (any could be a preprocessing node)
preprocessing_input_node = None
for input_name in node.input:
# For split
if ':' in input_name:
input_name = ''.join(input_name.split(':')[:-1])
if input_name in nodes_used_for_preprocessing:
preprocessing_input_node = input_name
break
# If the parent is also a preprocessing node, apply this preprocessing operation.
# Can also fuse these like this:
"""
val i0_preprocessed = (0::3, 0::224, 0::224){(i,j,k) =>
if (i == 0) { i0(2,j,k)*255.0.to[T] - 103.06262207.to[T] }
else if (i == 1) { i0(1,j,k)*255.0.to[T] - 115.90288544.to[T] }
else { i0(0,j,k)*255.0.to[T] - 123.15163422.to[T] }
};
"""
# When there is no preprocessing in the graph, it can be done as an extra input from the user when converting image -> csv, or if input to
# Spatial is later a jpg it can be done in fused way above based on user input.
# Can also support more cases, e.g. in the case of split -> sub -> concat, there are 3 subs, not 1 (above example is split -> concat -> sub).
if preprocessing_input_node:
# Get the remaining inputs
other_inputs = []
for input_name in node.input:
if ':' in input_name:
input_name = ''.join(input_name.split(':')[:-1])
if input_name != preprocessing_input_node:
other_inputs.append(input_name)
assert len(other_inputs) == 1
# Add the current node to the preprocessing nodes
nodes_used_for_preprocessing.add(node.name)
input_dims = reformat_memory(get_dims_str(preprocessing_input_node, frz_sess, 1))
assert len(input_dims) in [2,3]
num_input_channels = 1
if len(input_dims) == 3:
num_input_channels = int(input_dims[0])
output_dims = reformat_memory(get_dims_str(node.name, frz_sess, 1))
assert len(output_dims) in [2,3]
num_output_channels = 1
if len(output_dims) == 3:
num_output_channels = int(output_dims[0])
tmpvar_input = name_to_tmpvar[preprocessing_input_node]
# Perform this node's operation on current input
if node.op == 'Mul':
tmpvar = tmpvar_input + '_scale'
name_to_tmpvar[node.name] = tmpvar
assert num_input_channels in [1,3]
assert num_input_channels == num_output_channels
host_before_accel += ' val ' + tmpvar + ' = (0::' + ', 0::'.join(input_dims) + ')'
if num_input_channels == 1:
host_before_accel += '{i => ' + tmpvar_input + '(i)'
else:
host_before_accel += '{(i,j,k) => ' + tmpvar_input + '(i,j,k)'
host_before_accel += '*' + str( tensor_util.MakeNdarray(name_to_node[other_inputs[0]].attr['value'].tensor) ) + '.to[T]};' + "\n"
elif node.op == 'Sub':
tmpvar = tmpvar_input + '_meansub'
name_to_tmpvar[node.name] = tmpvar
assert num_input_channels in [1,3]
assert num_input_channels == num_output_channels
host_before_accel += ' val ' + tmpvar + ' = (0::' + ', 0::'.join(input_dims) + ')'
subtraction_values = tensor_util.MakeNdarray(name_to_node[other_inputs[0]].attr['value'].tensor)
if num_input_channels == 1:
assert subtraction_values.size == 1
host_before_accel += '{i => ' + tmpvar_input + '(i) - ' + str(subtraction_values) + '.to[T]};'
else:
assert subtraction_values.size == 3
host_before_accel += '''{(i,j,k) =>
if (i == 0) { ''' + tmpvar_input + '''(0,j,k) - ''' + str(subtraction_values[0]) + '''.to[T] }
else if (i == 1) { ''' + tmpvar_input + '''(1,j,k) - ''' + str(subtraction_values[1]) + '''.to[T] }
else { ''' + tmpvar_input + '''(2,j,k) - ''' + str(subtraction_values[2]) + '''.to[T] }
};'''
host_before_accel += "\n"
elif node.op == 'Split':
tmpvar = tmpvar_input + '_split'
name_to_tmpvar[node.name] = tmpvar
split_axis = tensor_util.MakeNdarray(name_to_node[other_inputs[0]].attr['value'].tensor)
assert split_axis.size == 1
assert split_axis == 3
assert num_input_channels == 3
assert num_output_channels == 1
host_before_accel += ' val ' + tmpvar + '_0 = (0::' + ', 0::'.join(input_dims[1:]) + ')'
host_before_accel += '{(j,k) => ' + tmpvar_input + '(0,j,k)};' + "\n"
host_before_accel += ' val ' + tmpvar + '_1 = (0::' + ', 0::'.join(input_dims[1:]) + ')'
host_before_accel += '{(j,k) => ' + tmpvar_input + '(1,j,k)};' + "\n"
host_before_accel += ' val ' + tmpvar + '_2 = (0::' + ', 0::'.join(input_dims[1:]) + ')'
host_before_accel += '{(j,k) => ' + tmpvar_input + '(2,j,k)};' + "\n"
elif node.op == 'Concat':
tmpvar = tmpvar_input + '_concat'
name_to_tmpvar[node.name] = tmpvar
concat_axis = tensor_util.MakeNdarray(name_to_node[other_inputs[0]].attr['value'].tensor)
assert concat_axis.size == 1
assert concat_axis == 3
assert num_input_channels == 1
assert num_output_channels == 3
# Get the concat order
concat_order = []
for input_name in node.input:
if input_name == other_inputs[0]:
continue
elif ':' not in input_name:
concat_order.append('0')
else:
concat_order.append(input_name.split(':')[-1])
assert len(concat_order) == 3
# Concat
host_before_accel += ' val ' + tmpvar + ' = (0::' + ', 0::'.join(output_dims) + ')'
host_before_accel += '''{(i,j,k) =>
if (i == 0) { ''' + tmpvar_input + '_' + concat_order[0] + '''(j,k) }
else if (i == 1) { ''' + tmpvar_input + '_' + concat_order[1] + '''(j,k) }
else { ''' + tmpvar_input + '_' + concat_order[2] + '''(j,k) }
};'''
host_before_accel += "\n"
elif node.op == 'Pad':
tmpvar = tmpvar_input + '_pad'
name_to_tmpvar[node.name] = tmpvar
assert num_input_channels in [1,3]
host_before_accel += ' val ' + tmpvar + ' = (0::' + ', 0::'.join(output_dims) + ')'
assert node.input[1] in extra_paddings.keys()
padding = int(extra_paddings[node.input[1]][2])
start = str(padding)
end = str(int(output_dims[1]) - padding)
if num_input_channels == 1:
host_before_accel += '{(j,k) => if (j>=' + start + ' && j<' + end + ' && k>=' + start + ' && k<' + end + ') ' + tmpvar_input + '(j-' + start + ',k-' + start + ') else 0.to[T]'
else:
host_before_accel += '{(i,j,k) => if (j>=' + start + ' && j<' + end + ' && k>=' + start + ' && k<' + end + ') ' + tmpvar_input + '(i,j-' + start + ',k-' + start + ') else 0.to[T]'
host_before_accel += '};' + "\n"
else:
assert False
continue
if node.op in ops_to_skip:
# Skip this op by short-circuiting names
# Reshape also short-circuits below when 1D to 1D
if node.input[0] in name_to_tmpvar.keys():
name_to_tmpvar[node.name] = name_to_tmpvar[node.input[0]]
if node.op == 'Softmax':
processed_softmax = True
continue
# Alternatively, could require the user to specify the output as the Softmax or something before
if processed_softmax:
continue
# ------------------------------------------------------------------------------------------------------
# Input or constant (already processed by iteration 1)
# ------------------------------------------------------------------------------------------------------
# Check if input op or constant
if node.op in input_ops:
continue
elif node.op == 'Const':
continue
# ------------------------------------------------------------------------------------------------------
# Computation node
# ------------------------------------------------------------------------------------------------------
# Otherwise we have an op
# Define helpers specific to compute nodes
def get_inputs(node, name_to_tmpvar):
node_tmpvar_inputs = []
for input in node.input:
if ':' in input:
input = ''.join(input.split(':')[:-1])
if input in name_to_tmpvar.keys():
node_tmpvar_inputs.append(name_to_tmpvar[input])
else:
# node_tmpvar_inputs.append(input)
print 'ERROR: Could not get input tmpvar for node ' + node.name + ', input ' + input
assert False
return node_tmpvar_inputs
def get_data_dims_str(node, frz_sess):
return get_dims_str(node.input[0], frz_sess, 1)
def get_kernel_dims_str(node, frz_sess):
return get_dims_str(node.input[1], frz_sess, 0)
# Return the window size for a pool node
# For a conv this isn't needed since the kernel is inputs[1]
def get_pool_kernel_dims(node):
kernel_dims = []
for k in node.attr['ksize'].list.i:
kernel_dims.append(str(int(k)))
assert len(kernel_dims) == 4
assert kernel_dims[0] == kernel_dims[3]
assert kernel_dims[1] == kernel_dims[2]
return kernel_dims
# Return output dims and stride/padding for a conv or pool node
# Can also see node_list.final, this information is within the tensor already.
# E.g. call get_dims_str() on the node to get the output shape.
# https://www.tensorflow.org/api_docs/python/tf/nn/convolution
def get_output_dim(node, kernel_dims, input_dims, out_channels):
padding = node.attr['padding'].s
strides = []
for s in node.attr['strides'].list.i:
strides.append(str(int(s)))
assert len(strides) == 4
assert strides[0] == strides[3]
assert strides[1] == strides[2] # Eventually not needed
# For SAME, padding can also be forced by a fused tf.pad
if padding == 'SAME':
import math
out_height = int(math.ceil(float(int(input_dims[0])) / float(strides[1])))
out_width = int(math.ceil(float(int(input_dims[1])) / float(strides[2])))
out_size = str(out_height) + ',' + str(out_width) + ',' + str(out_channels)
else:
assert padding == 'VALID'
import math
out_height = int(math.ceil(float(int(input_dims[0]) - int(kernel_dims[0]) + 1) / float(strides[1])))
out_width = int(math.ceil(float(int(input_dims[1]) - int(kernel_dims[1]) + 1) / float(strides[2])))
out_size = str(out_height) + ',' + str(out_width) + ',' + str(out_channels)
return out_height, out_width, out_size, strides, padding
def get_reshape_string(name):
if name in tmpvar_to_reshape_string.keys():
reshape_string = '.reshape(' + tmpvar_to_reshape_string[name] + ')'
if len(reshape_string.split(',')) > 1:
return reshape_string
return ''
# Return the nodes in the pattern if they exist
# Can also make this depend on graph not topological sort
def fusion_optimization_match(fusion_pattern, node_list, curr_idx):
# Now go over the fusion pattern and check if there is a mismatch
curr_fusion_pattern_op = 0
fusion_nodes = []
while True:
# If exhausted fusion ops, pattern found
if curr_fusion_pattern_op >= len(fusion_pattern):
break
# If not exhausted fusion ops but exhausted nodes, pattern not found
if curr_idx >= len(node_list):
return False
node = node_list[curr_idx]
# If constant or input, skip
if node.op in input_ops or node.op == 'Const':
curr_idx += 1
continue
# If match, add to list
# Can refactor this
if node.op == fusion_pattern[curr_fusion_pattern_op]:
fusion_nodes.append(node)
curr_fusion_pattern_op += 1
curr_idx += 1
elif node.op in ['Add', 'BiasAdd'] and fusion_pattern[curr_fusion_pattern_op] in ['Add', 'BiasAdd']:
fusion_nodes.append(node)
curr_fusion_pattern_op += 1
curr_idx += 1
elif node.op in ['Relu', 'Relu6'] and fusion_pattern[curr_fusion_pattern_op] in ['Relu', 'Relu6']:
fusion_nodes.append(node)
curr_fusion_pattern_op += 1
curr_idx += 1
# If mismatch, pattern not found
else:
return False
return fusion_nodes
# Register a new layer to reuse
def register_new_reused_processor(op_name, def_arg_values, hw_block, \
dse_string='', has_weights=False, bias_name=None, weight_name=None):
global reuse_layer_list
global accel_function
global reuse_schedule
global reuse_args
global reuse_weight_dram
global weight_files_to_concat
global file_opening
global accel_defs
# If this is the first reuse layer, initiate this code block
if not reuse_layer_list:
accel_function += '''
{{{INSERT_REUSE_LOOP_HERE}}}
'''
# If this is the first time for this op name, create a new entry
if op_name not in reuse_layer_list:
# Could also make check a single LUT with values for layer type (e.g. 1 2 3)
reuse_schedule[op_name] = []
# Add args map for this function as well
new_map = {}
for arg in def_arg_values.keys():
new_map[arg] = []
reuse_args[op_name] = new_map
if has_weights:
new_dram_map = {}
new_dram_map['bias'] = []
new_dram_map['weights'] = []
reuse_weight_dram[op_name] = new_dram_map
# Print the def header
file_opening += dse_string
accel_defs += ' def ' + op_name + '(' + ', '.join(sorted(def_arg_values.keys())) \
+ ', L : Int) : Unit = {' + "\n" + hw_block + ' }' + "\n\n"
# Now register this occurence of the layer in the entry
# LUTs can also be local to the def
for arg in def_arg_values.keys():
# if def_arg_values[arg]:
reuse_args[op_name][arg].append(def_arg_values[arg])
if has_weights:
reuse_weight_dram[op_name]['bias'].append(bias_name)
reuse_weight_dram[op_name]['weights'].append(weight_name)
weight_files_to_concat.append(bias_name)
weight_files_to_concat.append(weight_name)
reuse_schedule[op_name].append(str(len(reuse_layer_list)))
# Append this layer to the list
reuse_layer_list.append(op_name)
# Register a new layer for static model
def register_layer_ops(op_name, total_ops, ip, kxk):
global reuse_layer_to_ops
global reuse_layer_to_IP
global reuse_layer_to_kxk
if op_name not in reuse_layer_to_ops.keys():
reuse_layer_to_ops[op_name] = 0
reuse_layer_to_ops[op_name] += total_ops
reuse_layer_to_IP[op_name] = ip
reuse_layer_to_kxk[op_name] = kxk
# From https://www.tensorflow.org/versions/r1.12/api_guides/python/nn#Convolution
# Can also first check special-case of forced padding from a fused tf.pad. If not, then return this calculation.
def get_same_padding(in_height, in_width, strides, filter_height, filter_width):
if in_height % int(strides[1]) == 0:
pad_along_height = max(filter_height - int(strides[1]), 0)
else:
pad_along_height = max(filter_height - (in_height % strides[1]), 0)
if in_width % int(strides[2]) == 0:
pad_along_width = max(filter_width - int(strides[2]), 0)
else:
pad_along_width = max(filter_width - (in_width % int(strides[2])), 0)
pad_top = int(pad_along_height) / int(2)
pad_left = int(pad_along_width) / int(2)
pad_bottom = pad_along_height - pad_top
pad_right = pad_along_width - pad_left
return pad_top, pad_left, pad_bottom, pad_right
# For 1x1 convolution the weights are small so we can load a block of weights for multiple in channels
# Instead of a LUT this can also be calculated dynamically using e.g. MAX__in2D_aligned / (nr*nc),
# or statically in a LUT using MAX__in2D_aligned at the end
def block_input_channels(kernel_dims_str):
return kernel_dims_str[0] == '1' and kernel_dims_str[1] == '1'
# Given the max buffer size for an image, check if the entire image can fit inside a buffer
# or if e.g. a Line Buffer is needed.
# The image buffer size may be e.g. 4096 (in words) for the VU9P which has URAMs (4096 words deep).
# The SRAM may be banked so fitting inputs in 1 Block RAM may not be the outcome, but this buffer
# size also applies to the output partial sums.
def get_max_img_side_size_for_single_buffer():
import math
return int(math.sqrt(device_params['image_buffer_size']))
def use_line_buffer(data_dims_str):
return int(data_dims_str[0]) > get_max_img_side_size_for_single_buffer()
# Helper to conv_before_fusion
# Note: Some of these optimizations, e.g. for VALID padding, make the generated code simpler but would not impact performance
# because Spatial would e.g. optimize constant checks anyway. So it may not be worth keeping all the optimizations below,
# since they make the function more complicated in order to make the generated code simpler, but performance is not impacted.
def generate_sliding_window(in_name, out_name, padding, out_compute_rows, out_compute_cols, weight_read_str, half_kernel_size, B_par, \
load_data_from_dram=True, weight_blocking=True, use_linebuf=False):
conv_loop = ''
# Find proper indentation
if not load_data_from_dram:
indent = ' '
elif not use_linebuf:
indent = ' ' # One more loop since can't fuse in_channels loop
else:
indent = ' ' # One more loop for loading rows
# Check if weights are loaded in blocks
if weight_blocking:
b_idx_end = ', b'
else:
b_idx_end = ''
# Data is in DRAM so we could not fuse the in_channels loop with the rows/columns loop
# Print the extra loop here
if load_data_from_dram:
conv_loop += '''
''' + indent
if use_linebuf:
conv_loop += '''
''' + indent + '''Pipe.II(1).Foreach(0 until ''' + out_compute_cols + ''', 0 until B par ''' + B_par + ''') { (c,b) =>'''
else:
conv_loop += '''
''' + indent + '''Pipe.II(1).Foreach(0 until ''' + out_compute_rows + ''', 0 until ''' + out_compute_cols + ''', 0 until B par ''' + B_par + ''') { (r,c,b) =>'''
conv_loop += '''
''' + indent
# Can use mux here instead of *s
# For VALID padding, row_start, row_end, col_start, col_end, can be simplified
# But this might not affect performance or util, only make the generated code simpler, so maybe not
# worth making this function more complicated. If this is always set to True, correctness should not
# change (it makes this function simpler but generated code will be longer than necessary for VALID padding)
check_bounds = True
if padding == 'VALID':
check_bounds = False
# Initialize data loading bounds
if check_bounds:
if use_linebuf:
conv_loop += '''
''' + indent + ''' val row_start = min((kr-1).to[Int], max(0.to[Int], (kr-1-r.to[Int]*s.to[Int] ).to[Int]) )
''' + indent + ''' val row_end = min((kr ).to[Int], max(1.to[Int], (kr+nr-1-r.to[Int]*s.to[Int]).to[Int]) )'''
else:
conv_loop += '''
''' + indent + ''' val row_start = min((kr-1).to[Int], max(0.to[Int], (kr_ignore-r.to[Int]*s.to[Int] ).to[Int]) )
''' + indent + ''' val row_end = min((kr ).to[Int], max(1.to[Int], (nr+kr_ignore-r.to[Int]*s.to[Int]).to[Int]) )'''
conv_loop += '''
''' + indent + ''' val col_start = min((kc-1).to[Int], max(0.to[Int], (kc_ignore-c.to[Int]*s.to[Int] ).to[Int]) )
''' + indent + ''' val col_end = min((kc ).to[Int], max(1.to[Int], (nc+kc_ignore-c.to[Int]*s.to[Int]).to[Int]) )'''
# If line buffers are used, row_start check is still needed
elif use_linebuf:
conv_loop += '''
''' + indent + ''' val row_start = max(0.to[Int], (kr-1-r.to[Int]*s.to[Int] ).to[Int])'''
# Print weight load
conv_loop += '''
''' + indent + '''
''' + indent + ''' val kernel: List[T] = List.tabulate(kr){i => List.tabulate(kc){j =>
''' + indent + ''' ''' + weight_read_str + '''
''' + indent + ''' }}.flatten
''' + indent + ''' '''
# Get data read string
column_skip_str = ''
if check_bounds:
column_skip_str = '-kc_ignore'
if not load_data_from_dram:
data_idx_str = in_name + '_SRAM(inCh_i, i.to[Int]-kr_ignore+r.to[Int], j.to[Int]' + column_skip_str + '+c.to[Int])'
elif use_linebuf:
data_idx_str = in_name + '(kr-i,j.to[Int]' + column_skip_str + '+c.to[Int]*s.to[Int])' # Can use mux here
else:
data_idx_str = in_name + '((i.to[Int]-kr_ignore+mux(s==1,r,r*2))*nc + j.to[Int]' + column_skip_str + '+mux(s==1,c,c*2))'
# Specialize data read for different paddings
if check_bounds:
conv_loop += '''
''' + indent + ''' val data: List[T] = List.tabulate(kr){i => List.tabulate(kc){j =>
''' + indent + '''
''' + indent + ''' if (i < ''' + str(half_kernel_size) + ''' && j < ''' + str(half_kernel_size) + ''') {
''' + indent + ''' mux((i < row_start || j < col_start),
''' + indent + ''' 0.to[T],
''' + indent + ''' ''' + data_idx_str + '''
''' + indent + ''' )
''' + indent + ''' }
''' + indent + ''' else if (i == ''' + str(half_kernel_size) + ''' && j < ''' + str(half_kernel_size) + ''') {
''' + indent + ''' mux((j < col_start),
''' + indent + ''' 0.to[T],
''' + indent + ''' ''' + data_idx_str + '''