forked from analogdevicesinc/ai8x-synthesis
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathai8xize.py
executable file
·2620 lines (2422 loc) · 111 KB
/
ai8xize.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/env python3
###################################################################################################
# Copyright (C) Maxim Integrated Products, Inc. All Rights Reserved.
#
# Maxim Integrated Products, Inc. Default Copyright Notice:
# https://www.maximintegrated.com/en/aboutus/legal/copyrights.html
###################################################################################################
"""
Embedded network and simulation test generator program for Tornado CNN
"""
import hashlib
import os
import signal
import sys
import numpy as np
import apbaccess
import assets
import checkpoint
import cmsisnn
import commandline
import compute
import devices
import kbias
import kernels
import load
import onnxcp
import op
import rtlsim
import sampledata
import sampleweight
import stats
import tornadocnn as tc
import yamlcfg
from eprint import eprint
from simulate import conv1d_layer, conv2d_layer, convtranspose2d_layer, \
linear_layer, passthrough_layer, eltwise_layer, \
pooling_layer, show_data
from utils import ffs, fls, popcount
def create_net( # pylint: disable=too-many-arguments,too-many-locals,too-many-branches
prefix,
verbose,
verbose_all,
debug,
debug_computation,
no_error_stop,
overwrite_ok,
log,
apb_base,
layers,
operator,
input_dim,
pooled_dim,
output_dim,
processor_map,
output_processor_map,
kernel_size,
quantization,
output_shift,
input_chan,
output_chan,
conv_groups,
output_width,
padding,
dilation,
stride,
pool,
pool_stride,
pool_average,
activation,
data,
kernel,
bias,
big_data,
fc_weights,
fc_bias,
split,
in_offset,
out_offset,
streaming,
flatten,
operands,
eltwise,
pool_first,
in_sequences,
input_filename,
output_filename,
c_filename,
base_directory,
runtest_filename,
log_filename,
zero_unused,
timeout,
block_mode,
verify_writes=False,
verify_kernels=False,
embedded_code=False,
compact_weights=False,
compact_data=False,
write_zero_regs=False,
weight_filename=None,
sample_filename=None,
device=84,
init_tram=False,
avg_pool_rounding=False,
fifo=False,
fast_fifo=False,
fast_fifo_quad=False,
zero_sram=False,
mlator=False,
oneshot=0,
stopstart=False,
mexpress=False,
riscv=False,
riscv_exclusive=False,
riscv_flash=False,
riscv_cache=False,
riscv_debug=False,
riscv_debugwait=True,
override_start=None,
increase_start=0,
override_rollover=None,
override_delta1=None,
increase_delta1=0,
override_delta2=None,
increase_delta2=0,
slow_load=False,
synthesize_input=None,
mlator_noverify=False,
input_csv=None,
input_csv_period=None,
input_csv_format=None,
input_csv_retrace=None,
input_fifo=False,
input_sync=False,
sleep=False,
powerdown=False,
simple1b=False,
legacy_test=True,
log_intermediate=False,
log_pooling=False,
allow_streaming=False,
softmax=False,
unload=False,
clock_trim=None,
repeat_layers=1,
fixed_input=False,
max_count=None,
boost=None,
forever=False,
write_gap=None,
):
"""
Chain multiple CNN layers, create and save input and output
"""
in_expand = [0] * layers
out_expand = [0] * layers
in_expand_thresh = [0] * layers
out_expand_thresh = [0] * layers
tram_max = [0] * layers
input_dim_str = [None] * layers
output_dim_str = [None] * layers
kernel_size_str = [None] * layers
pool_str = [None] * layers
padding_str = [None] * layers
pool_stride_str = [None] * layers
stride_str = [None] * layers
if riscv_debug:
riscv = True
if riscv_cache:
riscv = True
riscv_flash = True
if riscv_flash or riscv_exclusive:
riscv = True
# Check streaming and FIFO constraints
if fast_fifo_quad:
fast_fifo = True
if fast_fifo:
fifo = True
fifo_group = True
else:
fifo_group = False
if fifo:
if input_chan[0] > 16 or big_data[0] and input_chan[0] > 4:
eprint("Using the FIFO is restricted to a maximum of 4 input channels (CHW) or "
f"16 channels (HWC); this test is using {input_chan[0]} channels.")
sys.exit(1)
if big_data[0] and processor_map[0] & ~0x0001000100010001 != 0 \
or not big_data[0] and processor_map[0] & ~0x000f000f000f000f != 0:
eprint("The FIFO is restricted to processors 0, 16, 32, 48 (CHW) or "
"0-3, 16-19, 32-35, 48-51 (HWC).")
sys.exit(1)
if fast_fifo:
if big_data[0] and input_chan[0] > 1:
eprint("Fast FIFO supports only a single CHW input channel; "
f"this test is using {input_chan[0]} channels.")
sys.exit(1)
elif not big_data[0] and input_chan[0] > 4:
eprint("Fast FIFO supports up to four HWC input channels; "
f"this test is using {input_chan[0]} channels.")
sys.exit(1)
if processor_map[0] != 1 and processor_map[0] & 0x0e == 0:
fifo_group = False
if output_width[0] != 8:
eprint('Single-layer fast FIFO setup requires output width of 8.')
sys.exit(1)
if operator[0] not in [op.CONV1D, op.CONV2D, op.CONVTRANSPOSE2D]:
eprint('Fast FIFO requies a convolution operation in the first layer.')
sys.exit(1)
elif streaming[0] and not allow_streaming:
eprint('Streaming in the first layer requires use of a FIFO.')
sys.exit(1)
if mlator and (output_dim[-1][0] * output_dim[-1][1] < 4 or output_width[-1] > 8):
eprint('--mlator should only be used with 4 or more 8-bit outputs per channel; ignoring.',
error=False)
mlator = False
processor_map_0 = processor_map[0]
if fast_fifo_quad:
processor_map[0] = processor_map_0 << 48 | processor_map_0 << 32 \
| processor_map_0 << 16 | processor_map_0
# Check that input channels are in separate memory instances if CHW (big) data format is used,
# and calculate input and output expansion
for ll in range(layers):
if quantization[ll] is None:
quantization[ll] = 8 # Set default
if output_shift[ll] is None:
output_shift[ll] = 0 # Set default
if output_shift[ll] < -15 or output_shift[ll] > 15:
implicit_shift = 8 - quantization[ll]
eprint(f"Layer {ll} with {quantization[ll]}-bit weight quantization supports an "
f"output_shift range of [{-15 - implicit_shift}, +{15 - implicit_shift}]. "
f"The specified value of output_shift is {output_shift[ll] - implicit_shift} "
"which exceeds the system limits.")
sys.exit(1)
if big_data[ll]:
p = processor_map[ll] >> (ffs(processor_map[ll]) & ~(tc.dev.P_SHARED-1))
while p:
if popcount(p & (tc.dev.P_SHARED-1)) > 1:
eprint(f"Layer {ll} uses CHW (big data) input format, but multiple channels "
"share the same memory instance. Modify the processor map for "
f"layer {ll}.")
sys.exit(1)
p >>= tc.dev.P_SHARED
out_expand[ll] = (output_chan[ll] + tc.dev.MAX_PROC-1) // tc.dev.MAX_PROC
out_expand_thresh[ll] = (output_chan[ll] + out_expand[ll]-1) // out_expand[ll]
if output_chan[ll] > tc.dev.MAX_PROC:
out_expand_thresh[ll] = \
min((out_expand_thresh[ll] + tc.dev.P_SHARED-1) & ~(tc.dev.P_SHARED-1),
tc.dev.MAX_PROC)
in_expand[ll] = (input_chan[ll] + tc.dev.MAX_PROC-1) // tc.dev.MAX_PROC
in_expand_thresh[ll] = (input_chan[ll] + in_expand[ll]-1) // in_expand[ll]
if input_chan[ll] > tc.dev.MAX_PROC:
in_expand_thresh[ll] = \
min((in_expand_thresh[ll] + tc.dev.P_SHARED-1) & ~(tc.dev.P_SHARED-1),
tc.dev.MAX_PROC)
assert input_dim[ll][0] * input_dim[ll][1] * in_expand[ll] < tc.dev.FRAME_SIZE_MAX
# Data memory size check - 4 channels share one instance unless CHW format
in_size = input_dim[ll][0] * input_dim[ll][1] * in_expand[ll] * operands[ll] \
* (1 if big_data[ll] else 4)
if not streaming[ll] and in_size + in_offset[ll] > tc.dev.INSTANCE_SIZE*16:
eprint(f'Layer {ll}: {1 if big_data[ll] else 4}-channel input size {in_size} '
f'with input offset 0x{in_offset[ll]:04x} and expansion {in_expand[ll]}x '
f'exceeds data memory instance size of {tc.dev.INSTANCE_SIZE*16}.')
sys.exit(1)
out_size = output_dim[ll][0] * output_dim[ll][1] * out_expand[ll] \
* 4 * output_width[ll] // 8
if (not streaming[ll] or ll == layers - 1) \
and out_size + out_offset[ll] > tc.dev.INSTANCE_SIZE*16:
eprint(f'Layer {ll}: 4-channel, {output_width[ll]}-bit output size {out_size} '
f'with output offset 0x{out_offset[ll]:04x} and expansion {out_expand[ll]}x '
f'exceeds data memory instance size of {tc.dev.INSTANCE_SIZE*16}.')
sys.exit(1)
if operator[ll] != op.CONV1D:
input_dim_str[ll] = f'{input_dim[ll][0]}x{input_dim[ll][1]}'
output_dim_str[ll] = f'{output_dim[ll][0]}x{output_dim[ll][1]}'
kernel_size_str[ll] = f'{kernel_size[ll][0]}x{kernel_size[ll][1]}'
pool_str[ll] = f'{pool[ll][0]}x{pool[ll][1]}' \
if pool[ll][0] > 1 or pool[ll][1] > 1 else '0x0'
padding_str[ll] = f'{padding[ll][0]}/{padding[ll][1]}'
pool_stride_str[ll] = f'{pool_stride[ll][0]}/{pool_stride[ll][1]}'
stride_str[ll] = f'{stride[ll][0]}/{stride[ll][1]}'
else:
input_dim_str[ll] = f'{input_dim[ll][0]}'
output_dim_str[ll] = f'{output_dim[ll][0]}'
kernel_size_str[ll] = f'{kernel_size[ll][0]}'
pool_str[ll] = f'{pool[ll][0]}' \
if pool[ll][0] > 1 or pool[ll][1] > 1 else '0'
padding_str[ll] = f'{padding[ll][0]}'
pool_stride_str[ll] = f'{pool_stride[ll][0]}'
stride_str[ll] = f'{stride[ll][0]}'
if operator[ll] == op.NONE:
tram_max[ll] = 1
else:
tram_max[ll] = max(0, pooled_dim[ll][1] + 2*padding[ll][1] - kernel_size[ll][1]) + 1
if operator[ll] == op.CONVTRANSPOSE2D:
tram_max[ll] *= stride[ll][1]
if input_chan[ll] % conv_groups[ll] != 0 or output_chan[ll] % conv_groups[ll] != 0:
eprint(f'Layer {ll}: convolution groups {conv_groups[ll]} does not divide'
f' the input channels {input_chan[ll]} or output channels {output_chan[ll]}.')
sys.exit(1)
# Create comment of the form "k1_b0-1x32x32b_2x2s2p14-..."
test_name = prefix
if not embedded_code:
for ll in range(layers):
test_name += f'-{input_chan[ll]}x{input_dim_str[ll]}' \
f'{"b" if big_data[ll] else "l"}' \
f'{"f" if flatten[ll] else ""}_' \
+ ("avg" if pool_average[ll]
and (pool[ll][0] > 1 or pool[ll][1] > 1) else "") \
+ ("max" if not pool_average[ll]
and (pool[ll][0] > 1 or pool[ll][1] > 1) else "") \
+ f'{pool_str[ll]}s{pool_stride[ll][0]}' \
f'p{padding[ll][0]}' \
f'm{output_chan[ll]}'
if activation[ll] == op.ACT_RELU:
test_name += "_relu"
elif activation[ll] == op.ACT_ABS:
test_name += "_abs"
if repeat_layers > 1:
test_name += f'_repeat{repeat_layers}'
MAX_PATH = 255
if len(test_name) + len(base_directory) > MAX_PATH - 10:
h = hashlib.md5(test_name.encode()).hexdigest() # Immutable hash from test name
cutoff = MAX_PATH - len(test_name) - len(base_directory) - len(h) - 10
test_name = test_name[:cutoff] + '-' + h
print(f'{test_name}...')
os.makedirs(os.path.join(base_directory, test_name), exist_ok=True)
# Redirect stdout?
if log:
sys.stdout = open(os.path.join(base_directory, test_name, log_filename), 'w')
print(f'{" ".join(str(x) for x in sys.argv)}')
print(f'{devices.partnum(device)}\n')
print(f'{test_name}')
if block_mode:
filename = input_filename + '.mem'
else:
filename = c_filename + ('_riscv' if riscv else '') + '.c'
if not block_mode and (embedded_code or compact_data):
sampledata_header = \
open(os.path.join(base_directory, test_name, sample_filename), mode='w')
else:
sampledata_header = None
if not block_mode and (embedded_code or mexpress or compact_weights):
weight_header = \
open(os.path.join(base_directory, test_name, weight_filename), mode='w')
else:
weight_header = None
# Calculate the groups needed, and groups and processors used overall
processors_used = 0
group_map = []
for ll in range(layers):
bits = processor_map[ll]
processors_used |= bits
if input_chan[ll] > tc.dev.MAX_CHANNELS:
eprint(f'Layer {ll} is configured for {input_chan[ll]} inputs, which exceeds '
f'the system maximum of {tc.dev.MAX_CHANNELS}.')
sys.exit(1)
if output_chan[ll] > tc.dev.MAX_CHANNELS:
eprint(f'Layer {ll} is configured for {output_chan[ll]} outputs, which exceeds '
f'the system maximum of {tc.dev.MAX_CHANNELS}.')
sys.exit(1)
if (ll != 0 or not fast_fifo_quad) \
and popcount(processor_map[ll]) != in_expand_thresh[ll]:
eprint(f'Layer {ll} has {input_chan[ll]} inputs with input expansion '
f'{in_expand[ll]}, {operands[ll]} operands, threshold {in_expand_thresh[ll]}, '
f'but enabled processor map 0x{processor_map[ll]:016x} '
f'has {popcount(processor_map[ll])} bits instead of the '
f'expected number of {in_expand_thresh[ll]}.')
sys.exit(1)
if ll == 0 and fast_fifo_quad and popcount(processor_map_0) != in_expand_thresh[ll]:
eprint(f'Layer {ll} has {input_chan[ll]} inputs with input expansion '
f'{in_expand[ll]}, threshold {in_expand_thresh[ll]}, but '
f'enabled processor map 0x{processor_map[ll]:016x} '
f'has {popcount(processor_map[ll])} bits instead of the '
f'expected number of {in_expand_thresh[ll]}.')
sys.exit(1)
if popcount(output_processor_map[ll]) != out_expand_thresh[ll]:
eprint(f'Layer {ll} has {output_chan[ll]} outputs with output expansion '
f'{out_expand[ll]}, threshold {out_expand_thresh[ll]}, but '
f'processor output map 0x{output_processor_map[ll]:016x} '
f'has {popcount(output_processor_map[ll])} bits instead of the '
f'expected number of {out_expand_thresh[ll]}.')
sys.exit(1)
this_map = []
for group in range(tc.dev.P_NUMGROUPS):
if (processor_map[ll] >> group*tc.dev.P_NUMPRO) % 2**tc.dev.P_NUMPRO:
this_map.append(group)
group_map.append(this_map)
# Ensure input and output map are the same for passthrough layers
if operator[ll] == op.NONE:
for group in range(tc.dev.P_NUMGROUPS):
in_pro = 2**popcount(
(processor_map[ll] >> group*tc.dev.P_NUMPRO) % 2**tc.dev.P_NUMPRO
) - 1
out_pro = (output_processor_map[ll] >> group*tc.dev.P_NUMPRO) % 2**tc.dev.P_NUMPRO
if out_pro != 0:
out_pro >>= ffs(out_pro)
if out_pro != in_pro:
eprint(f'Layer {ll} is a pass-through layer. The output processors must be a '
'packed version of the input processors for each x16. Configured are: '
f'input {processor_map[ll]:08x}, output '
f'{output_processor_map[ll]:08x}.')
groups_used = []
for group in range(tc.dev.P_NUMGROUPS):
if ((processors_used |
output_processor_map[-1]) >> group*tc.dev.P_NUMPRO) % 2**tc.dev.P_NUMPRO:
groups_used.append(group)
if 0 not in groups_used:
eprint('Group 0 is not used, this currently does not work.')
sys.exit(1)
# Create ARM code wrapper if needed
if riscv and not block_mode:
with open(os.path.join(base_directory, test_name, c_filename + '.c'), mode='w') as f:
apb = apbaccess.apbwriter(
f,
apb_base,
device=device,
master=False,
riscv=False,
riscv_flash=riscv_flash,
riscv_cache=riscv_cache,
riscv_exclusive=riscv_exclusive,
sleep=sleep,
)
apb.copyright_header()
apb.output(f'// ARM wrapper code\n// {test_name}\n')
apb.output(f'// Created using {" ".join(str(x) for x in sys.argv)}\n')
apb.header(
embedded_arm=embedded_code,
fail_indicator=forever,
)
apb.main(
clock_trim=clock_trim,
embedded_arm=embedded_code,
groups=list(set().union(groups_used)),
boost=boost,
forever=forever,
mexpress=mexpress,
fifo=fifo,
)
if input_csv is not None:
csv = os.path.join(base_directory, test_name, input_csv)
else:
csv = None
with open(os.path.join(base_directory, test_name, filename), mode='w') as memfile:
apb = apbaccess.apbwriter(
memfile,
apb_base,
block_level=block_mode,
verify_writes=verify_writes,
no_error_stop=no_error_stop,
weight_header=weight_header,
sampledata_header=sampledata_header,
embedded_code=embedded_code,
compact_weights=compact_weights or mexpress,
compact_data=compact_data,
write_zero_registers=write_zero_regs,
weight_filename=weight_filename,
sample_filename=sample_filename,
device=device,
verify_kernels=verify_kernels,
master=groups_used[0] if oneshot > 0 or stopstart else False,
riscv=True if riscv else None,
riscv_flash=riscv_flash,
riscv_cache=riscv_cache,
riscv_debug=riscv_debug,
riscv_debugwait=riscv_debugwait,
fast_fifo=fast_fifo,
input_csv=input_csv,
input_csv_format=input_csv_format,
input_chan=input_chan[0],
sleep=sleep,
)
apb.copyright_header()
apb.output(f'// {test_name}\n')
apb.output(f'// Created using {" ".join(str(x) for x in sys.argv)}\n')
# Human readable description of test
apb.output(f'\n// Configuring {repeat_layers * layers} '
f'layer{"s" if repeat_layers * layers > 1 else ""}:\n')
for r in range(repeat_layers):
for ll in range(layers):
apb.output(f'// Layer {r * layers + ll}: '
f'{str(operands[ll])+"x" if operands[ll] > 1 else ""}'
f'{input_chan[ll]}x{input_dim_str[ll]} ('
f'{"streaming " if streaming[ll] else ""}'
f'{"flattened " if flatten[ll] else ""}'
f'{"CHW/big data)" if big_data[ll] else "HWC/little data)"}, ')
if pool[ll][0] > 1 or pool[ll][1] > 1:
apb.output(f'{pool_str[ll]} {"avg" if pool_average[ll] else "max"} '
f'pool with stride {pool_stride_str[ll]}')
else:
apb.output('no pooling')
if operator[ll] in [op.CONV1D, op.CONV2D, op.CONVTRANSPOSE2D]:
conv_str = f', {op.string(operator[ll])} with kernel size ' \
f'{kernel_size_str[ll]}, '
else:
conv_str = ', no convolution, '
apb.output(conv_str +
f'stride {stride_str[ll]}, '
f'pad {padding_str[ll]}, '
f'{output_chan[ll]}x{output_dim_str[ll]} output\n')
apb.output('\n')
apb.header(fail_indicator=forever)
if embedded_code or compact_data or mexpress:
apb.output('void memcpy32(uint32_t *dst, const uint32_t *src, int n)\n{\n')
apb.output(' while (n-- > 0) {\n'
' *dst++ = *src++;\n'
' }\n}\n\n')
if (embedded_code and not fifo) or compact_data or input_csv:
# Pre-define data memory loader. Inline later when generating RTL sim.
if input_fifo:
apb.output('#define USE_FIFO\n')
load.load(
True,
apb,
big_data[0],
processor_map_0,
in_offset[0],
[input_chan[0], input_dim[0][0], input_dim[0][1]],
in_expand[0],
operands[0],
in_expand_thresh[0],
data,
padding[0],
split=split,
fifo=fifo,
slowdown=slow_load,
synthesize=synthesize_input,
riscv_flash=riscv_flash,
csv_file=csv,
camera_format=input_csv_format,
camera_retrace=input_csv_retrace,
fixed_input=fixed_input,
debug=debug,
)
if not block_mode and (embedded_code or mexpress or compact_weights):
# Pre-define the kernels and bias values
kern_offs, kern_len = kernels.load(
verbose,
True,
device,
apb,
layers,
operator,
kernel,
kernel_size,
quantization,
processor_map,
output_processor_map,
input_chan,
output_chan,
out_expand,
out_expand_thresh,
in_expand,
in_expand_thresh,
flatten,
mexpress,
verify_kernels,
riscv_flash and not riscv_cache,
fast_fifo_quad,
debug,
block_mode,
)
bias_offs, bias_group, group_bias_max = kbias.load(
verbose,
True,
apb,
layers,
bias,
quantization,
group_map,
output_chan,
streaming,
debug,
)
apb.load_header()
# Initialize CNN registers
if verbose:
print('\nGlobal registers:')
print('-----------------')
# Reset
if device != 84:
apb.write_fifo_ctl(tc.dev.AON_CTL, tc.dev.AON_READY_SEL,
verbose, comment=' // AON control', force_write=True)
# Disable completely unused groups
for group in range(tc.dev.P_NUMGROUPS):
if group not in groups_used:
apb.write_ctl(group, tc.dev.REG_CTL, 0,
verbose, comment=f' // Disable group {group}')
# Configure global control registers for used groups
for _, group in enumerate(groups_used):
if init_tram:
# Zero out Tornado RAM
if not embedded_code:
for p in range(tc.dev.P_NUMPRO):
for offs in range(tc.dev.TRAM_SIZE):
apb.write_tram(group, p, offs, 0, comment='Zero ')
apb.output('\n')
else:
for p in range(tc.dev.P_NUMPRO):
addr = apb_base + tc.dev.C_GROUP_OFFS*group + tc.dev.C_TRAM_BASE \
+ p * tc.dev.TRAM_OFFS * 4
apb.output(f' memset((uint32_t *) 0x{addr:08x}, 0, '
f'{tc.dev.TRAM_SIZE}); // Zero TRAM {group}\n')
apb.output('\n')
# Stop state machine - will be overwritten later; enable FIFO
val = tc.dev.READY_SEL << 1
if fifo:
val |= 1 << 15
if device != 84:
val |= 1 << 3 # Enable clocks
if mexpress:
val |= 1 << 20
apb.write_ctl(group, tc.dev.REG_CTL, val,
verbose, comment=' // Stop SM')
# SRAM Control - does not need to be changed
apb.write_ctl(group, tc.dev.REG_SRAM, 0x40e,
verbose, comment=' // SRAM control')
# Number of layers
apb.write_ctl(group, tc.dev.REG_LCNT_MAX, repeat_layers * layers - 1,
verbose, comment=' // Layer count')
apb.output('\n')
if device != 84 and zero_sram:
for group in range(tc.dev.P_NUMGROUPS):
apb.write_ctl(group, tc.dev.REG_SRAM_TEST, 1 << 0,
verbose, comment=' // Data SRAM BIST')
for group in range(tc.dev.P_NUMGROUPS):
apb.wait_ctl(group, tc.dev.REG_SRAM_TEST, 1 << 27 | 1 << 18, 1 << 27 | 1 << 18,
comment=' // Wait for BIST')
for group in range(tc.dev.P_NUMGROUPS):
apb.verify_ctl(group, tc.dev.REG_SRAM_TEST, 1 << 14, 0,
comment=' // Return on BIST error')
for group in range(tc.dev.P_NUMGROUPS):
apb.write_ctl(group, tc.dev.REG_SRAM_TEST, 0,
verbose, comment=' // Reset BIST', force_write=True)
apb.output('\n')
for group in range(tc.dev.P_NUMGROUPS):
apb.write_ctl(group, tc.dev.REG_SRAM_TEST, 1 << 2,
verbose, comment=' // Mask SRAM BIST')
for group in range(tc.dev.P_NUMGROUPS):
apb.wait_ctl(group, tc.dev.REG_SRAM_TEST, 1 << 27 | 1 << 19, 1 << 27 | 1 << 19,
comment=' // Wait for BIST')
for group in range(tc.dev.P_NUMGROUPS):
apb.verify_ctl(group, tc.dev.REG_SRAM_TEST, 1 << 15, 0,
comment=' // Return on BIST error')
for group in range(tc.dev.P_NUMGROUPS):
apb.write_ctl(group, tc.dev.REG_SRAM_TEST, 0,
verbose, comment=' // Reset BIST', force_write=True)
apb.output('\n')
for group in range(tc.dev.P_NUMGROUPS):
apb.write_ctl(group, tc.dev.REG_SRAM_TEST, 1 << 4,
verbose, comment=' // Tornado SRAM BIST')
for group in range(tc.dev.P_NUMGROUPS):
apb.wait_ctl(group, tc.dev.REG_SRAM_TEST, 1 << 27 | 1 << 20, 1 << 27 | 1 << 20,
comment=' // Wait for BIST')
for group in range(tc.dev.P_NUMGROUPS):
apb.verify_ctl(group, tc.dev.REG_SRAM_TEST, 1 << 16, 0,
comment=' // Return on BIST error')
for group in range(tc.dev.P_NUMGROUPS):
apb.write_ctl(group, tc.dev.REG_SRAM_TEST, 0,
verbose, comment=' // Reset BIST', force_write=True)
apb.output('\n')
for group in range(tc.dev.P_NUMGROUPS):
apb.write_ctl(group, tc.dev.REG_SRAM_TEST, 1 << 6,
verbose, comment=' // Bias Rfile BIST')
for group in range(tc.dev.P_NUMGROUPS):
apb.wait_ctl(group, tc.dev.REG_SRAM_TEST, 1 << 27 | 1 << 21, 1 << 27 | 1 << 21,
comment=' // Wait for BIST')
for group in range(tc.dev.P_NUMGROUPS):
apb.verify_ctl(group, tc.dev.REG_SRAM_TEST, 1 << 17, 0,
comment=' // Return on BIST error')
for group in range(tc.dev.P_NUMGROUPS):
apb.write_ctl(group, tc.dev.REG_SRAM_TEST, 0,
verbose, comment=' // Reset BIST', force_write=True)
apb.output('\n')
if block_mode or not (embedded_code or mexpress or compact_weights):
kern_offs, kern_len = kernels.load(
verbose,
embedded_code,
device, apb,
layers,
operator,
kernel,
kernel_size,
quantization,
processor_map,
output_processor_map,
input_chan,
output_chan,
out_expand,
out_expand_thresh,
in_expand,
in_expand_thresh,
flatten,
mexpress,
verify_kernels,
riscv_flash and not riscv_cache,
fast_fifo_quad,
debug,
block_mode,
)
bias_offs, bias_group, group_bias_max = kbias.load(
verbose,
embedded_code,
apb,
layers,
bias,
quantization,
group_map,
output_chan,
streaming,
debug,
)
else:
apb.output(' load_kernels();\n')
if verify_kernels:
apb.output(' if (!verify_kernels()) return 0;\n')
if max(group_bias_max) > 0:
apb.output(' load_bias();\n')
if verbose:
print('\nGlobal configuration:')
print('---------------------')
print(f'Used processors = 0x{processors_used:016x}')
print(f'Used groups = {groups_used}')
print('\nPer-group configuration:')
print('-----------------------')
print(f'Used bias memory = {group_bias_max}')
print('\nPer-layer configuration:')
print('------------------------')
if repeat_layers > 1:
print(f'Layer repeat count = {repeat_layers}')
print(f'Input dimensions = {input_dim}')
print(f'Input channels = {input_chan}')
print(f'Convolution groups = {conv_groups}')
print(f'Flatten = {flatten}')
print('Processor map = [',
', '.join('0x{:016x}'.format(k) for k in processor_map), ']', sep='',)
if device != 84:
print(f'Input expansion = {in_expand}')
print(f'Expansion threshold = {in_expand_thresh}')
print('Element-wise op = [',
', '.join(op.string(k, elt=True) for k in eltwise), ']', sep='',)
print(f'Operand expansion = {operands}')
print('Input offsets = [',
', '.join('0x{:04x}'.format(k) for k in in_offset), ']', sep='',)
print(f'Output dimensions = {output_dim}')
print(f'Output channels = {output_chan}')
print('Output processors = [',
', '.join('0x{:016x}'.format(k) for k in output_processor_map), ']', sep='',)
if device != 84:
print(f'Output expansion = {out_expand}')
print(f'Expansion threshold = {out_expand_thresh}')
print(f'Output data bits = {output_width}')
print('Output offsets = [',
', '.join('0x{:04x}'.format(k) for k in out_offset), ']', sep='',)
print(f'Group map = {group_map}')
print(f'Kernel offsets = {kern_offs}')
print(f'Kernel lengths = {kern_len}')
if device != 84:
print(f'Kernel dimensions = {kernel_size}')
print(f'Kernel size = {quantization}')
print(f'Output shift = {output_shift}')
print('Operator = [',
', '.join(op.string(k) for k in operator), ']', sep='',)
print(f'Stride = {stride}')
print(f'Padding = {padding}')
print(f'Group with bias = {bias_group}')
print(f'Bias offsets = {bias_offs}')
print(f'Pooling = {pool}')
print(f'Pooling stride = {pool_stride}')
print(f'Pooled dimensions = {pooled_dim}')
print(f'Streaming = {streaming}')
print('')
if verbose:
print('Layer register configuration:')
print('-----------------------------')
# Configure per-layer control registers
for r in range(repeat_layers):
for ll in range(layers):
local_source = False
for _, group in enumerate(groups_used):
# Local output must be used:
# - When parallel processing is enabled (not currently supported), or
# - When there are gaps in the output, and
# - the gaps are non-uniform, or
# - the layer is in passthrough mode
# Uniform gaps (when not in passthrough mode) can be achieved using the
# time slot offset.
if local_source:
break
gap_max, gap_min = 0, tc.dev.MAX_PROC
gmap = \
output_processor_map[ll] & 2**tc.dev.P_NUMPRO - 1 << group*tc.dev.P_NUMPRO
if popcount(gmap) > 1:
p = ffs(gmap)
while p < fls(gmap):
gap = ffs(gmap & ~(2**(p+1) - 1)) - p - 1
gap_min, gap_max = min(gap, gap_min), max(gap, gap_max)
p += gap + 1
local_source = \
gap_min != gap_max or gap_max > 0 and operator[ll] == op.NONE
# FIXME: Check that we don't overlap by-16 groups when in local_source mode
# FIXME: Non-uniform gaps are not supported
# For passthrough, determine time slot count (maximum across all used groups)
tscnt_max = 0
for _, group in enumerate(groups_used):
if operator[ll] == op.NONE:
if popcount((processor_map[ll] >> group*tc.dev.P_NUMPRO)
% 2**tc.dev.P_NUMPRO) != 0:
tscnt_max = max(
tscnt_max,
(popcount((processor_map[ll] >> group*tc.dev.P_NUMPRO)
% 2**tc.dev.P_NUMPRO) * output_width[ll] // 8 - 1) // 4
)
for _, group in enumerate(groups_used):
apb.output(f'\n // Layer {r * layers + ll} group {group}\n')
if device == 84 and operator[ll] == op.CONV1D:
# For 1D convolutions on AI84, the column count is always 3, and the
# row count is divided by 3. Padding is divided by 3.
val = (padding[ll][0] // 3 << 8) \
| (input_dim[ll][0] + 2*padding[ll][0]) // 3 - 1
apb.write_lreg(group, r * layers + ll, tc.dev.LREG_RCNT, val,
verbose, comment=' // Rows')
apb.write_lreg(group, r * layers + ll, tc.dev.LREG_CCNT, 2,
verbose, comment=' // Columns')
else:
# Configure row count
# [9:0] maxcount: lower 8 bits = total of width + pad - 1
# [17:16] pad: 2 bits pad
if flatten[ll]:
val = 0
else:
if operator[ll] == op.CONVTRANSPOSE2D:
val = stride[ll][1]*input_dim[ll][0] - 1
else:
val = input_dim[ll][0] - 1
assert padding[ll][0] < 2**2
assert val + 2*padding[ll][0] < 2**10
apb.write_lreg(group, r * layers + ll, tc.dev.LREG_RCNT,
padding[ll][0] << 16 | val + 2*padding[ll][0],
verbose, comment=' // Rows')
# Configure column count (evaluates to 0 for 1D convolutions)
# [9:0] width including padding - 1
# [17:16] pad count (0 = no pad, 1 = half pad, 2 = full pad)
if flatten[ll]:
val = 0
else:
if operator[ll] == op.CONVTRANSPOSE2D:
val = stride[ll][1]*input_dim[ll][1] - 1
else:
val = input_dim[ll][1] - 1
assert padding[ll][1] < 2**2
assert val + 2*padding[ll][1] < 2**10
apb.write_lreg(group, r * layers + ll, tc.dev.LREG_CCNT,
padding[ll][1] << 16 | val + 2 * padding[ll][1],
verbose, comment=' // Columns')
# Configure pooling row count
val = pool[ll][0]-1
if device == 84 and pool[ll][0] == 1:
val = 1
else:
val = pool[ll][0]-1
assert val < 2**4
apb.write_lreg(group, r * layers + ll, tc.dev.LREG_PRCNT, val,
verbose, comment=' // Pooling rows')
# Configure pooling column count
if device == 84 and pool[ll][1] == 1:
val = 1
else:
val = pool[ll][1]-1
assert val < 2**4
apb.write_lreg(group, r * layers + ll, tc.dev.LREG_PCCNT, val,
verbose, comment=' // Pooling columns')
# Configure pooling stride count
if pool[ll][0] > 1 or pool[ll][1] > 1:
val = pool_stride[ll][0]-1
elif operator[ll] == op.CONVTRANSPOSE2D:
val = 0
else:
val = stride[ll][0]-1
if device == 84 and operator[ll] == op.CONV1D:
val //= 3
assert val < 2**4
apb.write_lreg(group, r * layers + ll, tc.dev.LREG_STRIDE, val,
verbose, comment=' // Stride')
val = out_offset[ll] // 4
if not local_source:
# Configure SRAM write pointer -- write ptr is global
# Get offset to first available instance of the first used processor of the
# next layer.
if operator[ll] != op.NONE:
instance = ffs(output_processor_map[ll]) & ~(tc.dev.P_SHARED-1)
else:
if output_processor_map[ll] & \
2**tc.dev.P_NUMPRO - 1 << group*tc.dev.P_NUMPRO > 0:
instance = ffs(output_processor_map[ll]
& 2**tc.dev.P_NUMPRO - 1 << group*tc.dev.P_NUMPRO) \
& ~(tc.dev.P_SHARED-1)
else:
instance = 0
val |= (instance % tc.dev.P_SHARED) * tc.dev.INSTANCE_SIZE \
| (instance // tc.dev.P_SHARED) << tc.dev.INSTANCE_SHIFT
else:
instance = ffs(output_processor_map[ll] >> group * tc.dev.P_SHARED) \
& ~(tc.dev.P_SHARED-1)
val |= (instance + group * tc.dev.P_SHARED) * tc.dev.INSTANCE_SIZE
assert val < 2**17
apb.write_lreg(group, r * layers + ll, tc.dev.LREG_WPTR_BASE, val,
verbose, comment=' // SRAM write ptr')
if device == 84:
# Configure write pointer mask offset count
# [15:0] Timeslot offset
# [11:0] 12 bits for memory - word address every time
# we reach limit
# [13:12] instance in group
# [15:14] by-16 group
# [31:16] Mask offset (0x10000000, required when writing more than 4 masks)
if input_chan[ll] * kern_len[ll] > 4:
val = 1 << tc.dev.INSTANCE_SHIFT + 16
else:
val = 0
apb.write_lreg(group, r * layers + ll, tc.dev.LREG_WPTR_OFFS, val,
verbose, comment=' // Mask offset count')
else:
# [15:0] Write Pointer Timeslot Offset Register
# Used for 1x1 convolution, and pooling without convolution
if operator[ll] == op.CONV2D and kernel_size[ll] == [1, 1]:
val = 1