blob: 28bc6b79ac02612939585761638d13b4aa279cf6 [file] [log] [blame]
Tim Hall79d07d22020-04-27 18:20:16 +01001# Copyright (C) 2020 Arm Limited or its affiliates. All rights reserved.
2#
3# SPDX-License-Identifier: Apache-2.0
4#
5# Licensed under the Apache License, Version 2.0 (the License); you may
6# not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an AS IS BASIS, WITHOUT
13# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
Tim Hall79d07d22020-04-27 18:20:16 +010016# Description:
17# Register level (low-level) command stream generation for Ethos-U55. Takes a high-level command stream and generates
18# all the register settings. Calculates dependencies between commands and inserts wait operations. And generates a bit
19# stream suitable for interpretation by the Ethos-U55 processor.
Tim Hall79d07d22020-04-27 18:20:16 +010020from collections import defaultdict
Diego Russoe8a10452020-04-21 17:39:10 +010021from enum import Enum
22from enum import IntEnum
Diego Russoea6111a2020-04-14 18:41:58 +010023
24import numpy as np
25
26from . import scaling
Diego Russoe8a10452020-04-21 17:39:10 +010027from .architecture_features import ArchitectureFeatures
28from .architecture_features import Block
29from .architecture_features import Kernel
30from .architecture_features import Rect
31from .architecture_features import SharedBufferArea
32from .architecture_features import SHRAMElements
33from .data_type import BaseType
34from .data_type import DataType
35from .ethos_u55_regs.ethos_u55_regs import acc_format
36from .ethos_u55_regs.ethos_u55_regs import activation
37from .ethos_u55_regs.ethos_u55_regs import cmd0
38from .ethos_u55_regs.ethos_u55_regs import cmd1
39from .ethos_u55_regs.ethos_u55_regs import elementwise_mode
40from .ethos_u55_regs.ethos_u55_regs import ifm_precision
Jacob Bohlincf7da102020-05-20 09:03:40 +020041from .ethos_u55_regs.ethos_u55_regs import resampling_mode
Diego Russoe8a10452020-04-21 17:39:10 +010042from .ethos_u55_regs.ethos_u55_regs import rounding
Tim Hall79d07d22020-04-27 18:20:16 +010043from .high_level_command_stream import CommandType
Diego Russoe8a10452020-04-21 17:39:10 +010044from .numeric_util import clamp_sigmoid
45from .numeric_util import clamp_tanh
Louis Verhaardb2fb2122020-06-04 15:51:24 +020046from .numeric_util import full_shape
Diego Russoe8a10452020-04-21 17:39:10 +010047from .numeric_util import quantise_float32
48from .numeric_util import round_away_zero
Diego Russoe8a10452020-04-21 17:39:10 +010049from .numeric_util import round_up_to_int
Tim Hall79d07d22020-04-27 18:20:16 +010050from .operation import NpuBlockType
Tim Hall79d07d22020-04-27 18:20:16 +010051from .shared_buffer_allocation import SharedBufferAllocation
Patrik Gustavssoneca2e952020-05-27 09:15:11 +020052from .tensor import MemType
Diego Russoe8a10452020-04-21 17:39:10 +010053from .tensor import TensorBlockTraversal
54from .tensor import TensorFormat
Tim Hall79d07d22020-04-27 18:20:16 +010055
56
57class RegisterMachine:
58 def __init__(self):
59 self.n_banks = 1
60 self.registers = [defaultdict(lambda: None) for _ in range(self.n_banks)]
61 self.bank_idx = 0
62
63 def set_register(self, reg, value):
64 is_changed = self.registers[self.bank_idx][reg] != value
65 self.registers[self.bank_idx][reg] = value
66 # is_changed = True # force command
67 return is_changed
68
69 def switch_bank(self):
70 self.bank_idx = (self.bank_idx + 1) % self.n_banks
71
72
73class CmdMode(IntEnum):
74 NoPayload = 0x0000
75 Payload32 = 0x4000
76 Mask = 0xC000
77 CmdOpMask = 0x03FF
78
79
80class BasePointerIndex(IntEnum):
Patrik Gustavssoneca2e952020-05-27 09:15:11 +020081 WeightTensor = 0 # base address index for the Weight tensor
82 ScratchTensor = 1 # base address index for the Scratch_tensor in the TensorArena
83 ScratchFastTensor = 2 # base address for the Scratch_fast_tensor
Tim Hall79d07d22020-04-27 18:20:16 +010084
85
86# TODO: Replace with definitions from ethos_u55_regs
87class IFM2Broadcast(IntEnum):
88 BroadcastHdim = 1 << 0
89 BroadcastWdim = 1 << 1
90 BroadcastCdim = 1 << 2
91 ReverseOperandOrder = 1 << 6
92 UseIFM2Scalar = 1 << 7
93
94
95class CommandStreamEmitter:
96 def __init__(self):
97 self.cmd_stream = []
98 self.reg_machine = [RegisterMachine(), RegisterMachine()]
99 self.last_absolute_wait = defaultdict(int)
100
101 def get_reg_machine(self, cmd):
102 if "DMA" in cmd.name:
103 return self.reg_machine[1]
104 else:
105 return self.reg_machine[0]
106
107 def size_in_bytes(self):
108 sz = 0
109 for cmd in self.cmd_stream:
110 sz += len(cmd) * 4
111 return sz
112
113 def to_list(self):
114 return [elem for cmd in self.cmd_stream for elem in cmd]
115
116 def print_cmds(self):
117 print("Code: Command: Param: Payload:")
118 for words_for_one_command in self.cmd_stream:
119 code = words_for_one_command[0] & 0x0000FFFF # lower 16 bits
120 param = words_for_one_command[0] >> 16 # higher 16 bits
121
122 payload_mode = CmdMode(code & CmdMode.Mask)
123
124 # code and command
125 s = " 0x%04x " % code
126 if payload_mode == CmdMode.NoPayload:
127 s += str(cmd0(code & CmdMode.CmdOpMask))
128 else:
129 s += str(cmd1(code & CmdMode.CmdOpMask))
130
131 s = s.ljust(40)
132 s += "%5d" % param
133
134 # payload
135 if payload_mode == CmdMode.Payload32:
136 s += " 0x%08x (%d)" % (words_for_one_command[1], words_for_one_command[1])
137 else:
138 s += " -"
139
140 print(s)
141
142 def cmd0_with_param(self, cmd, param):
143 if isinstance(param, Enum):
144 param = int(param.value)
145 else:
146 param = int(param)
147 param = param & 0xFFFF
148 command = cmd.value | (param << 16)
149 if not self.get_reg_machine(cmd).set_register(cmd, (command, param)):
150 return
151
152 # This is not a redundant command, actually write it
153 self.cmd_stream.append((command,))
154
155 def cmd1_with_offset(self, cmd, offset, param=0x0):
156 offset = int(offset) & 0xFFFFFFFFF
157 command = cmd.value | CmdMode.Payload32.value | (param << 16)
158
159 if not self.get_reg_machine(cmd).set_register(cmd, (command, offset)):
160 return
161
162 # This is not a redundant command, actually write it
163 self.cmd_stream.append((command, offset))
164
165 def cmd_wait(self, cmd, param, absolute_wait_time):
166 if absolute_wait_time <= self.last_absolute_wait[cmd]:
167 return
168
169 self.last_absolute_wait[cmd] = absolute_wait_time
170 param = int(param)
171 command = ((param & 0xFFFF) << 16) | cmd.value
172 self.cmd_stream.append((command,))
173
174 def cmd_do_operation(self, cmd, param=0):
175 param = int(param)
176 command = ((param & 0xFFFF) << 16) | cmd.value
177
178 self.cmd_stream.append((command,))
179 self.get_reg_machine(cmd).switch_bank()
180
181
182def calc_command_dependencies(cmd_stream, arch):
183 cmd_starts = {}
184 cmd_ends = {}
185 memory_accesses = {}
186
187 # Keep track of accumulated number of commands in command stream.
188 # First element kernel ops: (# of blocks, # of commands)
189 # Second element DMA ops: (# of commands)
190 pos = np.array((np.array((0, 0)), np.array([0])))
191
192 dependencies = {}
193
194 for cmd in cmd_stream:
195 cmd_starts[cmd] = pos
196 op_count = cmd.get_operation_count()
197 # Keep track of both num blocks and commands
198 cmd_add = 0 if (op_count[0] == 0) else 1
199 pos = np.array((pos[0] + np.array((op_count[0], cmd_add)), pos[1] + np.array([op_count[1]])))
200 cmd_ends[cmd] = np.array((pos[0], pos[1]))
201 memory_accesses[cmd] = cmd.get_memory_accesses()
202
203 for idx, cmd in enumerate(cmd_stream):
204 curr_accesses = memory_accesses[cmd]
205 # Keep track of command dependency.
206 # First element kernel ops: (# of blocks, # of commands)
207 # Second element DMA ops: (# of commands)
208 dep_offsets = np.array((np.array((-1, -1)), np.array([-1])))
209 dep_cmds = [None] * CommandType.Size.value
210 if idx > 0:
211 # Look at the previous commands in backwards order
212 for prev_cmd in cmd_stream[idx - 1 :: -1]:
213 assert prev_cmd is not cmd
214 if dep_cmds[prev_cmd.cmdtype] is None:
215 is_dependency = False
216 if cmd.cmdtype == CommandType.NpuStripe and prev_cmd.cmdtype == CommandType.NpuStripe:
217 # Special handling here, as dpu -> dpu operations require additional care
218 if not SharedBufferAllocation.is_compatible(prev_cmd.ps.shared_buffer, cmd.ps.shared_buffer):
219 is_dependency = True
220 elif memory_accesses[prev_cmd].conflicts(curr_accesses):
221 is_dependency = True
222 else:
223 if memory_accesses[prev_cmd].conflicts(curr_accesses):
224 is_dependency = True
225
226 if is_dependency:
227 new_offset = cmd_ends[prev_cmd][prev_cmd.cmdtype]
228 if new_offset[0] > dep_offsets[prev_cmd.cmdtype][0]:
229 dep_cmds[prev_cmd.cmdtype] = prev_cmd
230 dep_offsets[prev_cmd.cmdtype] = new_offset
231
232 # Check if we've got dependencies for all commands, in which case we can early out
233 for dep in dep_cmds:
234 if dep is None:
235 break
236 else:
237 break # all handled
238
239 # Convert absolute to relative dependencies, using None to signal the special case of no
240 # dependency of this kind
241 res = [None] * CommandType.Size.value
242 for i in range(CommandType.Size.value):
243 if dep_cmds[i] is not None:
244 res[i] = cmd_starts[cmd][i] - dep_offsets[i]
245
246 dependencies[cmd] = cmd_starts[cmd], res
247
248 return dependencies
249
250
251def get_op_kernel(ps):
252 if ps.primary_op is None:
253 return None
254
255 strides = ps.primary_op.attrs.get("strides", (1, 1, 1, 1))
256 dilation = ps.primary_op.attrs.get("dilation", (1, 1, 1, 1))
257 if ps.weight_tensor:
258 if ps.npu_block_type in set((NpuBlockType.VectorProduct, NpuBlockType.ElementWise)):
259 k_h = 1
260 k_w = 1
261 else:
262 k_h = ps.weight_tensor.shape[0]
263 k_w = ps.weight_tensor.shape[1]
264 else:
265 k_h = ps.primary_op.attrs.get("filter_height", 1)
266 k_w = ps.primary_op.attrs.get("filter_width", 1)
267
268 return Kernel(k_w, k_h, strides[2], strides[1], dilation[2], dilation[1])
269
270
Tim Hall79d07d22020-04-27 18:20:16 +0100271def has_prev_op_dependency(prev_cmd, cmd):
272 if prev_cmd is None:
273 return False
274 if (prev_cmd.cmdtype == cmd.cmdtype == CommandType.NpuStripe) and (prev_cmd.ps != cmd.ps):
Tim Hall90337952020-05-07 16:42:35 +0100275 if prev_cmd.ofm_tensor.equivalence_id == cmd.ifm_tensor.equivalence_id:
Tim Hall79d07d22020-04-27 18:20:16 +0100276 return True
Tim Hall90337952020-05-07 16:42:35 +0100277 elif cmd.ifm2_tensor is not None:
Louis Verhaardb2fb2122020-06-04 15:51:24 +0200278 return prev_cmd.ofm_tensor.equivalence_id == cmd.ifm2_tensor.equivalence_id
Tim Hall79d07d22020-04-27 18:20:16 +0100279 return False
280
281
282def get_op_ofm_rect(cmd):
Charles Xu3e9c4342020-04-22 08:31:43 +0200283 start = full_shape(4, cmd.ofm_box.start_coord, 0)
284 end = full_shape(4, cmd.ofm_box.end_coord, 1)
Tim Hall79d07d22020-04-27 18:20:16 +0100285 return Rect(start[-2], start[-3], start[-1], end[-2] - 1, end[-3] - 1, end[-1] - 1)
286
287
288def get_op_ifm_rect(cmd):
Charles Xu3e9c4342020-04-22 08:31:43 +0200289 start = full_shape(4, cmd.ifm_box.start_coord, 0)
290 end = full_shape(4, cmd.ifm_box.end_coord, 1)
Tim Hall79d07d22020-04-27 18:20:16 +0100291 return Rect(start[-2], start[-3], start[-1], end[-2] - 1, end[-3] - 1, end[-1] - 1)
292
293
294def get_op_ifmofm_block_depth(arch, cmd):
295 # Note: NOT equivalent to the normal ifm block depth calculation since
296 # it takes into account 'depthless' block operations by returning full
297 # depth
298 if cmd.ps.npu_block_type in (NpuBlockType.ConvolutionDepthWise, NpuBlockType.Pooling, NpuBlockType.ElementWise):
299 return cmd.ofm_box.get_size_shape()[-1]
300
301 return arch.calc_ifm_block_depth(cmd.ifm_box.get_size_shape()[-1], cmd.ifm_tensor.dtype.bits)
302
303
304def get_op_padding_lt(cmd):
305 if cmd.ps.npu_block_type not in (
306 NpuBlockType.ConvolutionDepthWise,
307 NpuBlockType.Pooling,
308 NpuBlockType.ConvolutionMxN,
309 ):
310 return (0, 0)
311
312 explicit_padding = list(cmd.ps.primary_op.attrs["explicit_padding"]) # (top, left, bottom, right)
313
314 # Check if this is for horizontal ifm streaming
315 if not (cmd.is_first_h_stripe and cmd.is_last_h_stripe):
316 explicit_padding[0] = cmd.pad_top
317 explicit_padding[2] = cmd.pad_bottom
318
319 return (explicit_padding[1], explicit_padding[0])
320
321
322def generate_register_command_stream(nng, sg, arch, verbose=False):
323 emit = CommandStreamEmitter()
324
Patrik Gustavssoneca2e952020-05-27 09:15:11 +0200325 if arch.feature_map_storage_mem_area == arch.fast_storage_mem_area:
326 base_ptr_idx_map = {
327 MemType.Permanent_NPU: BasePointerIndex.WeightTensor,
328 MemType.Permanent_CPU: BasePointerIndex.WeightTensor,
329 MemType.Scratch: BasePointerIndex.ScratchTensor,
330 MemType.Scratch_fast: BasePointerIndex.ScratchTensor,
331 }
332 else:
333 base_ptr_idx_map = {
334 MemType.Permanent_NPU: BasePointerIndex.WeightTensor,
335 MemType.Permanent_CPU: BasePointerIndex.WeightTensor,
336 MemType.Scratch: BasePointerIndex.ScratchTensor,
337 MemType.Scratch_fast: BasePointerIndex.ScratchFastTensor,
338 }
Tim Hall79d07d22020-04-27 18:20:16 +0100339
340 # Maps an AccumulatorType enum to the corresponding acc_format value
341 acc_format_map = {
342 SHRAMElements.Acc16: acc_format.FP_S5_10.value,
343 SHRAMElements.Acc32: acc_format.INT_32BIT.value,
344 SHRAMElements.Acc40: acc_format.INT_40BIT.value,
345 }
346
347 # Maps an elementwise op type to an elementwise_mode enum value used by NPU_OP_ELEMENTWISE
348 elementwise_mode_map = {
349 "MulAct": elementwise_mode.MUL.value,
350 "AddAct": elementwise_mode.ADD.value,
351 "SubAct": elementwise_mode.SUB.value,
352 "Minimum": elementwise_mode.MIN.value,
353 "Maximum": elementwise_mode.MAX.value,
354 "LeakyRelu": elementwise_mode.LRELU.value,
355 "Abs": elementwise_mode.ABS.value,
356 }
357
358 cmd_stream = []
359 for cmd in sg.high_level_command_stream:
360 if cmd.cmdtype == CommandType.NpuStripe and cmd.ps.npu_block_type == NpuBlockType.Default:
361 print("Warning: Skipping register command stream generation for", cmd.ps)
362 else:
363 cmd_stream.append(cmd)
364
365 dependencies = calc_command_dependencies(cmd_stream, arch)
366
367 # Initialise operator dependency state
368 prev_ifm_rect = cur_ifm_rect = None
369 prev_ifm_block_depth = cur_ifm_block_depth = None
370 prev_ofm_rect = cur_ofm_rect = None
371 prev_ofm_block = cur_ofm_block = None
372 prev_kernel = cur_kernel = None
373 prev_cmd = None
374
375 def emit_wait_commands(cmd):
376 # The command is fully set up, emit whatever wait commands we need
377 absolute_dep, relative_dep = dependencies[cmd]
378 if relative_dep[CommandType.NpuStripe] is not None:
379 if cmd.cmdtype == CommandType.DMA:
380 param = relative_dep[CommandType.NpuStripe][1]
381 if param <= 3:
382 emit.cmd_wait(cmd0.NPU_OP_KERNEL_WAIT, param, absolute_dep[CommandType.NpuStripe][1])
383 else:
384 param = relative_dep[CommandType.NpuStripe][0]
385 param = min(param, 0xFFFF) # Clamp to allowable wait amount
386
387 if relative_dep[CommandType.DMA] is not None:
Patrik Gustavssoneca2e952020-05-27 09:15:11 +0200388 # TODO This can be optimized for yoda
389 param = 0
Tim Hall79d07d22020-04-27 18:20:16 +0100390 emit.cmd_wait(cmd0.NPU_OP_DMA_WAIT, param, absolute_dep[CommandType.DMA][0])
Tim Hall79d07d22020-04-27 18:20:16 +0100391
Tim Hall42e41892020-07-06 10:51:31 +0100392 if arch.is_yoda_system:
Jacob Bohlin0b9ca782020-07-09 11:16:30 +0200393 emit.cmd0_with_param(cmd0.NPU_SET_PARALLEL_MODE, arch.ncores - 1)
Tim Hallf7e810a2020-06-25 15:04:31 +0100394
Tim Hall79d07d22020-04-27 18:20:16 +0100395 for cmd in cmd_stream:
396 if cmd.cmdtype == CommandType.DMA:
397 start_coord = cmd.box.start_coord
398
399 src_addr = cmd.in_tensor.address_for_coordinate(start_coord)
400 dst_addr = cmd.out_tensor.address_for_coordinate(start_coord)
401
402 if cmd.in_tensor.compressed_values is not None:
403 stream_index = cmd.in_tensor.compressed_stream_index_from_coord(start_coord)
404 sz = cmd.in_tensor.size_of_compressed_stream(stream_index)
405 else:
406 sz = cmd.in_tensor.address_for_coordinate(cmd.box.end_coord, is_top_box=True) - src_addr
407
Patrik Gustavssoneca2e952020-05-27 09:15:11 +0200408 emit.cmd0_with_param(cmd0.NPU_SET_DMA0_SRC_REGION, base_ptr_idx_map[cmd.in_tensor.mem_type])
Tim Hall79d07d22020-04-27 18:20:16 +0100409 emit.cmd1_with_offset(cmd1.NPU_SET_DMA0_SRC, src_addr)
Patrik Gustavssoneca2e952020-05-27 09:15:11 +0200410 emit.cmd0_with_param(cmd0.NPU_SET_DMA0_DST_REGION, base_ptr_idx_map[cmd.out_tensor.mem_type])
411
Tim Hall79d07d22020-04-27 18:20:16 +0100412 emit.cmd1_with_offset(cmd1.NPU_SET_DMA0_DST, dst_addr)
413 emit.cmd1_with_offset(cmd1.NPU_SET_DMA0_LEN, sz)
414 dma_channel = 0
415 mode = 0 # From external to external
416
417 emit_wait_commands(cmd)
418 emit.cmd_do_operation(cmd0.NPU_OP_DMA_START, dma_channel * 16 + mode)
419
420 elif cmd.cmdtype == CommandType.NpuStripe:
421
422 ps = cmd.ps
423 primary_op = ps.primary_op
424 npu_block_type = ps.npu_block_type
425 # Specifies if global scale from the NPU_SET_OFM_SCALE register should be used instead of per-channel scale
426 use_global_scale = False
427 # Specifies type of rounding to be used.
428 rounding_mode = rounding.TFL
Louis Verhaardb2fb2122020-06-04 15:51:24 +0200429 if primary_op.type == "ResizeBilinear":
Dwight Lidman3ec04ac2020-04-30 11:54:48 +0200430 rounding_mode = rounding.TRUNCATE
Tim Hall79d07d22020-04-27 18:20:16 +0100431 fmf = primary_op.attrs.get("fused_memory_function", None)
432 faf = primary_op.attrs.get("fused_activation_function", None)
Jacob Bohlin9fbc4912020-06-29 11:58:50 +0200433 fused_quantize = any(op.type == "Quantize" for op in ps.ops)
Tim Hall79d07d22020-04-27 18:20:16 +0100434
435 # Specifies which operand to apply scaling to in bitexact elementwise ADD/SUB
436 op_to_scale = 0
437
438 # Update state history
439 prev_ifm_rect = cur_ifm_rect
440 prev_ifm_block_depth = cur_ifm_block_depth
441 prev_ofm_rect = cur_ofm_rect
442 prev_ofm_block = cur_ofm_block
443 prev_kernel = cur_kernel
Louis Verhaardb2fb2122020-06-04 15:51:24 +0200444 cur_kernel = get_op_kernel(ps)
Tim Hall79d07d22020-04-27 18:20:16 +0100445
446 block_config = ps.block_config
447 emit.cmd0_with_param(cmd0.NPU_SET_OFM_BLK_HEIGHT_M1, block_config[0] - 1)
448 emit.cmd0_with_param(cmd0.NPU_SET_OFM_BLK_WIDTH_M1, block_config[1] - 1)
449 emit.cmd0_with_param(cmd0.NPU_SET_OFM_BLK_DEPTH_M1, block_config[3] - 1)
450
451 shared_buffer = ps.shared_buffer
452
453 if npu_block_type == NpuBlockType.ElementWise:
454 ifm2_broadcast = 0
455
456 if cmd.ifm_tensor.shape == []:
457 # The scalar has to be the ifm2 tensor so switch the ifms
458 cmd.ifm_tensor, cmd.ifm2_tensor = cmd.ifm2_tensor, cmd.ifm_tensor
459 cmd.ifm_box, cmd.ifm2_box = cmd.ifm2_box, cmd.ifm_box
460
461 # Set ReverseOperandOrder bit to IFM2_BROADCAST
462 ifm2_broadcast |= IFM2Broadcast.ReverseOperandOrder
463
464 # Calculate scales needed for arithmetic elementwise operators
465 if primary_op.type in set(("AddAct", "MulAct", "SubAct",)):
466 input_scale = cmd.ifm_tensor.quantization.scale_f32
467 input2_scale = cmd.ifm2_tensor.quantization.scale_f32
468 output_scale = cmd.ofm_tensor.quantization.scale_f32
469 use_global_scale = True
470
471 if primary_op.type == "MulAct":
472 if (faf == "Sigmoid") or (faf == "Tanh"):
473 output_scale = 1 / 0x3000
474
475 ofm_scale, shift = scaling.elementwise_mul_scale(input_scale, input2_scale, output_scale)
476 emit.cmd1_with_offset(cmd1.NPU_SET_OFM_SCALE, ofm_scale, shift)
477 else: # AddAct/SubAct
478 if (faf == "Sigmoid") or (faf == "Tanh"):
479 output_scale = 1 / 0x3000
480
481 if input_scale == input2_scale:
482 opa_scale, opb_scale, ofm_scale, shift = scaling.simplified_elementwise_add_sub_scale(
483 input_scale, input2_scale, output_scale
484 )
485 opa_shift = 0 # Unused for this case
486 else:
487 # Use advanced implementation only when input scales differ
488 bitdepth = cmd.ifm_tensor.dtype.bits
489 (
490 opa_scale,
491 opa_shift,
492 ofm_scale,
493 shift,
494 op_to_scale,
495 ) = scaling.advanced_elementwise_add_sub_scale(
496 input_scale, input2_scale, output_scale, bitdepth
497 )
498 opb_scale = 0 # Unused for this case
499 if ifm2_broadcast & IFM2Broadcast.ReverseOperandOrder:
500 # If the operand order is reversed we also have to swap which operand is scaled
501 if op_to_scale == scaling.OperandToScale.OPa:
502 op_to_scale = scaling.OperandToScale.OPb
503 else:
504 op_to_scale = scaling.OperandToScale.OPa
505
506 emit.cmd1_with_offset(cmd1.NPU_SET_OPA_SCALE, opa_scale, opa_shift)
507 emit.cmd1_with_offset(cmd1.NPU_SET_OPB_SCALE, opb_scale)
508 emit.cmd1_with_offset(cmd1.NPU_SET_OFM_SCALE, ofm_scale, shift)
509
510 if primary_op.type in set(("LeakyRelu", "Abs",)):
511 output_scale = cmd.ofm_tensor.quantization.scale_f32
512 use_global_scale = True
513
514 if primary_op.type == "LeakyRelu":
515 output_scale *= primary_op.attrs["alpha"]
516
517 ofm_scale, shift = scaling.quantise_scale(output_scale)
518 emit.cmd1_with_offset(cmd1.NPU_SET_OFM_SCALE, ofm_scale, shift)
519
520 # For elementwise set the required SHRAM to be equal to the total size of SHRAM
521 shram_required = arch.shram_total_banks
522 emit.cmd0_with_param(cmd0.NPU_SET_IFM_IB_END, shram_required)
523
524 # Acc buffers not needed so set AB_START to size of SHRAM
525 emit.cmd0_with_param(cmd0.NPU_SET_AB_START, arch.shram_total_banks)
526
527 # Is not a unary operator
528 if cmd.ifm2_tensor is not None:
529 if cmd.ifm2_tensor.shape == []:
530 # IFM2 is a constant, set UseIFM2Scalar bit to IFM2_BROADCAST
531 ifm2_broadcast |= IFM2Broadcast.UseIFM2Scalar
532 else:
533 ifm_box_shape = cmd.ifm_box.get_size_shape()
534 ifm2_box_shape = cmd.ifm2_box.get_size_shape()
535
536 if len(cmd.ifm_tensor.shape) > 1 and ifm_box_shape[1] != ifm2_box_shape[1]:
537 # Broadcast in 'H' dimension
538 assert cmd.ifm2_tensor.shape[1] == 1
539 ifm2_broadcast |= IFM2Broadcast.BroadcastHdim
540
541 if len(cmd.ifm_tensor.shape) > 2 and ifm_box_shape[2] != ifm2_box_shape[2]:
542 # Broadcast in 'W' dimension
543 assert cmd.ifm2_tensor.shape[2] == 1
544 ifm2_broadcast |= IFM2Broadcast.BroadcastWdim
545
546 if len(cmd.ifm_tensor.shape) > 3 and ifm_box_shape[3] != ifm2_box_shape[3]:
547 # Broadcast in 'C' dimension
548 assert cmd.ifm2_tensor.shape[3] == 1
549 ifm2_broadcast |= IFM2Broadcast.BroadcastCdim
550
551 # Set IFM2_IB_START to the latter half of the IB space
552 ifm_ib_start = shared_buffer.bank_locations[SharedBufferArea.IFM]
553 emit.cmd0_with_param(
554 cmd0.NPU_SET_IFM2_IB_START, (shram_required - ifm_ib_start) / 2 + ifm_ib_start
555 )
556
557 emit.cmd0_with_param(cmd0.NPU_SET_IFM2_BROADCAST, ifm2_broadcast)
558
559 else:
560 emit.cmd0_with_param(
561 cmd0.NPU_SET_IFM_IB_END,
562 shared_buffer.bank_locations[SharedBufferArea.IFM]
563 + shared_buffer.banks_required[SharedBufferArea.IFM],
564 )
565 emit.cmd0_with_param(cmd0.NPU_SET_AB_START, shared_buffer.bank_locations[SharedBufferArea.Accumulators])
566
567 emit.cmd0_with_param(cmd0.NPU_SET_ACC_FORMAT, acc_format_map[shared_buffer.use_accumulator_element])
568
Louis Verhaardb2fb2122020-06-04 15:51:24 +0200569 if primary_op.type == "ResizeBilinear":
Dwight Lidman3ec04ac2020-04-30 11:54:48 +0200570 # perform nearest neighbor upscale
Jacob Bohlincf7da102020-05-20 09:03:40 +0200571 emit.cmd0_with_param(cmd0.NPU_SET_IFM_UPSCALE, resampling_mode.NEAREST)
572 elif primary_op.type == "Conv2DBackpropInputSwitchedBias":
573 # perform insert zero upscale
574 emit.cmd0_with_param(cmd0.NPU_SET_IFM_UPSCALE, resampling_mode.TRANSPOSE)
Dwight Lidman3ec04ac2020-04-30 11:54:48 +0200575 else:
Jacob Bohlincf7da102020-05-20 09:03:40 +0200576 emit.cmd0_with_param(cmd0.NPU_SET_IFM_UPSCALE, resampling_mode.NONE)
Tim Hall79d07d22020-04-27 18:20:16 +0100577
578 if npu_block_type in set(
579 (NpuBlockType.ConvolutionMxN, NpuBlockType.ConvolutionDepthWise, NpuBlockType.Pooling)
580 ):
581 # Set up padding
582 explicit_padding = list(primary_op.attrs["explicit_padding"]) # (top, left, bottom, right)
583
584 # Check if this is for horizontal ifm streaming
585 if not (cmd.is_first_h_stripe and cmd.is_last_h_stripe):
586 explicit_padding[0] = cmd.pad_top
587 explicit_padding[2] = cmd.pad_bottom
588
589 # Indexing from end since a 1x1 Avgpool might have been added with non 4-dimensional input/output,
590 # because of activation function needed to be fused.
591 if cmd.ifm_box.start_coord[-2] > 0:
592 explicit_padding[1] = 0
593 if cmd.ifm_box.end_coord[-2] < cmd.ifm_tensor.shape[-2]:
594 explicit_padding[3] = 0
Tim Hall79d07d22020-04-27 18:20:16 +0100595 emit.cmd0_with_param(cmd0.NPU_SET_IFM_PAD_TOP, explicit_padding[0])
596 emit.cmd0_with_param(cmd0.NPU_SET_IFM_PAD_LEFT, explicit_padding[1])
597 emit.cmd0_with_param(cmd0.NPU_SET_IFM_PAD_BOTTOM, explicit_padding[2])
598 emit.cmd0_with_param(cmd0.NPU_SET_IFM_PAD_RIGHT, explicit_padding[3])
599
Dwight Lidman0538a772020-05-06 14:09:17 +0200600 # set kernel x stride low bit
601 stride = primary_op.attrs["strides"][2] - 1 & 1
602 # set kernel y stride low bit
603 stride |= (primary_op.attrs["strides"][1] - 1 & 1) << 1
604 # set kernel x stride extension bits
605 stride |= (primary_op.attrs["strides"][2] - 1 >> 1) << 6
606 # set kernel y stride extension bits
607 stride |= (primary_op.attrs["strides"][1] - 1 >> 1) << 9
608
Tim Hall79d07d22020-04-27 18:20:16 +0100609 if npu_block_type == NpuBlockType.Pooling:
610 k_height, k_width = primary_op.attrs["ksize"][1:3]
611 emit.cmd0_with_param(cmd0.NPU_SET_KERNEL_HEIGHT_M1, k_height - 1)
612 emit.cmd0_with_param(cmd0.NPU_SET_KERNEL_WIDTH_M1, k_width - 1)
613
614 valid_padding = sum(explicit_padding) == 0
615
Dwight Lidman3ec04ac2020-04-30 11:54:48 +0200616 if primary_op.type in set(("AvgPool", "AvgPoolAct", "ResizeBilinear")) and valid_padding:
Tim Hall79d07d22020-04-27 18:20:16 +0100617 # For valid padding vela has to output scaling values
618 if faf == "Sigmoid" or faf == "Tanh":
619 rescale = 0x3000 * cmd.ifm_tensor.quantization.scale_f32
Tim Hall79d07d22020-04-27 18:20:16 +0100620
Fredrik Svedberg620d88c2020-05-19 10:43:01 +0200621 if cmd.ifm_tensor.dtype == DataType.int16:
Charles Xu749d9212020-06-11 12:39:19 +0200622 multiplier = max(1, int(4096 * cmd.ifm_tensor.quantization.scale_f32 + 0.5))
Fredrik Svedberg620d88c2020-05-19 10:43:01 +0200623 rescale *= 3 * multiplier
624
625 rescale_bits = len(bin(round_up_to_int(rescale))) - 2 + 1
Tim Hall79d07d22020-04-27 18:20:16 +0100626 scale, shift = scaling.quantise_pooling_scale(k_height * k_width, rescale_bits)
Fredrik Svedberg620d88c2020-05-19 10:43:01 +0200627
628 if cmd.ifm_tensor.dtype == DataType.int16:
629 scale = (1 << shift) * 3 * multiplier
630 else:
631 scale = int(round_away_zero(scale * rescale))
Jacob Bohlin9fbc4912020-06-29 11:58:50 +0200632 elif fused_quantize:
633 # Quantize op requires different scaling
634 ifm_scale_f64 = np.double(cmd.ifm_tensor.quantization.scale_f32)
635 ofm_scale_f64 = np.double(cmd.ofm_tensor.quantization.scale_f32)
636 scale, shift = scaling.quantise_scale(ifm_scale_f64 / ofm_scale_f64)
Tim Hall79d07d22020-04-27 18:20:16 +0100637 else:
638 # In case avg pool fused with concat or other memory operation, rescaling might be needed.
639 # k_height == k_width == 1 is allways true in this case
640 # Normally the scale is maximised, to get maximum precision, which means that
641 # if rescale != 1, scale need to consider the number of bits needed for rescaling
642 rescale = cmd.ifm_tensor.quantization.scale_f32 / cmd.ofm_tensor.quantization.scale_f32
643 rescale_bits = 0
644 if k_height == k_width == 1:
645 if fmf == "ConcatSliceWrite":
646 rounding_mode = rounding.NATURAL
647 if rescale > 1:
648 rescale_bits = len(bin(round_up_to_int(rescale))) - 2 + 1
649 elif rescale < 1:
650 rescale_bits = -(len(bin(round_up_to_int(1 / rescale))) - 2 - 1)
651 scale, shift = scaling.quantise_pooling_scale(k_height * k_width, rescale_bits)
652 scale = int(round_away_zero(scale * rescale))
653
654 emit.cmd1_with_offset(cmd1.NPU_SET_OFM_SCALE, scale, shift)
655 # Valid-padded average pool should use the global scale from
656 # NPU_SET_OFM_SCALE register, which is set above.
657 use_global_scale = True
658
659 else: # Convolution
660 assert cmd.weight_tensor.block_traversal != TensorBlockTraversal.Default
Fredrik Svedbergd67c0aa2020-03-30 13:15:28 +0200661 # Reduced precision quantization and natural rounding used for int16
662 if cmd.ifm_tensor.dtype == DataType.int16:
663 rounding_mode = rounding.NATURAL
Louis Verhaardb2fb2122020-06-04 15:51:24 +0200664 stride |= (cur_kernel.dilation.y - 1) << 4
665 stride |= (cur_kernel.dilation.x - 1) << 3
666 emit.cmd0_with_param(
667 cmd0.NPU_SET_KERNEL_HEIGHT_M1, cur_kernel.dilation.y * (cmd.weight_tensor.shape[0] - 1)
668 )
669 emit.cmd0_with_param(
670 cmd0.NPU_SET_KERNEL_WIDTH_M1, cur_kernel.dilation.x * (cmd.weight_tensor.shape[1] - 1)
671 )
Tim Hall79d07d22020-04-27 18:20:16 +0100672 if cmd.weight_tensor.block_traversal == TensorBlockTraversal.PartKernelFirst:
673 # Part-kernel-first weight ordering
674 assert npu_block_type == NpuBlockType.ConvolutionMxN
675 stride |= 1 << 2
676
677 emit.cmd0_with_param(cmd0.NPU_SET_KERNEL_STRIDE, stride)
678
679 elif npu_block_type in set((NpuBlockType.VectorProduct,)):
680 # Vector product is implemented using a 1x1 convolution so need
681 # to setup the appropriate padding and kernel info
682 emit.cmd0_with_param(cmd0.NPU_SET_IFM_PAD_TOP, 0)
683 emit.cmd0_with_param(cmd0.NPU_SET_IFM_PAD_LEFT, 0)
684 emit.cmd0_with_param(cmd0.NPU_SET_IFM_PAD_BOTTOM, 0)
685 emit.cmd0_with_param(cmd0.NPU_SET_IFM_PAD_RIGHT, 0)
686
687 # kernel stride reg = 0 means stride(1,1) + depth first weight
688 # order + dilation(0,0) + kernel_split_size=8
689 emit.cmd0_with_param(cmd0.NPU_SET_KERNEL_STRIDE, 0)
690
691 emit.cmd0_with_param(cmd0.NPU_SET_KERNEL_HEIGHT_M1, 0)
692 emit.cmd0_with_param(cmd0.NPU_SET_KERNEL_WIDTH_M1, 0)
693
694 if npu_block_type in set(
695 (NpuBlockType.ConvolutionMxN, NpuBlockType.ConvolutionDepthWise, NpuBlockType.VectorProduct)
696 ):
697 # Emit Weight base address commands, only maps the area required for
698 # this command's weights from the larger tensor.
699 stream_index = cmd.weight_tensor.compressed_stream_index_from_coord(cmd.weight_box.start_coord)
Tim Hallf7e810a2020-06-25 15:04:31 +0100700 weight_substream_offsets = cmd.weight_tensor.compressed_values_substream_offsets[stream_index]
Jacob Bohlin0b9ca782020-07-09 11:16:30 +0200701 substreams = len(weight_substream_offsets) - 1 # Offset list must terminate with full stream length
Tim Hallf7e810a2020-06-25 15:04:31 +0100702
703 # Extract weight substream offsets and calculate their lengths
704 assert len(weight_substream_offsets) > 1 and (weight_substream_offsets[0] == 0)
Tim Hall79d07d22020-04-27 18:20:16 +0100705 weight_addr = cmd.weight_tensor.address_for_coordinate(cmd.weight_box.start_coord)
Tim Hallf7e810a2020-06-25 15:04:31 +0100706
Tim Hall62316762020-06-25 16:55:02 +0100707 # Set weights sources for active and present cores
Jacob Bohlin0b9ca782020-07-09 11:16:30 +0200708 for core, param in enumerate(
709 [
710 (cmd1.NPU_SET_WEIGHT_BASE, cmd1.NPU_SET_WEIGHT_LENGTH),
711 (cmd1.NPU_SET_WEIGHT1_BASE, cmd1.NPU_SET_WEIGHT1_LENGTH),
712 ]
713 ):
Tim Hall62316762020-06-25 16:55:02 +0100714 if core < substreams:
Jacob Bohlin0b9ca782020-07-09 11:16:30 +0200715 emit.cmd1_with_offset(param[0], weight_addr + weight_substream_offsets[core])
716 emit.cmd1_with_offset(
717 param[1], weight_substream_offsets[core + 1] - weight_substream_offsets[core]
718 )
Tim Hall62316762020-06-25 16:55:02 +0100719 elif core < arch.ncores:
720 emit.cmd1_with_offset(param[0], weight_addr)
721 emit.cmd1_with_offset(param[1], 0)
Tim Hallf7e810a2020-06-25 15:04:31 +0100722
Patrik Gustavssoneca2e952020-05-27 09:15:11 +0200723 weight_region = base_ptr_idx_map[cmd.weight_tensor.mem_type]
Tim Hall79d07d22020-04-27 18:20:16 +0100724 emit.cmd0_with_param(cmd0.NPU_SET_WEIGHT_REGION, weight_region)
Tim Hall79d07d22020-04-27 18:20:16 +0100725
726 # Emit Scale & Bias base address commands, with length matching the amount required by
727 # the weight tensors.
728 if cmd.scale_tensor is not None:
Tim Hallf7e810a2020-06-25 15:04:31 +0100729 scale_substream_offsets = cmd.scale_tensor.compressed_values_substream_offsets[stream_index]
Jacob Bohlin0b9ca782020-07-09 11:16:30 +0200730 substreams = len(scale_substream_offsets) - 1 # Offset list must terminate with full stream length
Tim Hallf7e810a2020-06-25 15:04:31 +0100731
732 # Extract scale substream offsets and calculate their lengths
733 assert len(scale_substream_offsets) > 1 and (scale_substream_offsets[0] == 0)
Jacob Bohlin0b9ca782020-07-09 11:16:30 +0200734 scale_addr = cmd.scale_tensor.address_for_coordinate(cmd.weight_box.start_coord[-1:])
Tim Hallf7e810a2020-06-25 15:04:31 +0100735
Tim Hall62316762020-06-25 16:55:02 +0100736 # Set scale sources for active and present cores
Jacob Bohlin0b9ca782020-07-09 11:16:30 +0200737 for core, param in enumerate(
738 [
739 (cmd1.NPU_SET_SCALE_BASE, cmd1.NPU_SET_SCALE_LENGTH),
740 (cmd1.NPU_SET_SCALE1_BASE, cmd1.NPU_SET_SCALE1_LENGTH),
741 ]
742 ):
Tim Hall62316762020-06-25 16:55:02 +0100743 if core < substreams:
Jacob Bohlin0b9ca782020-07-09 11:16:30 +0200744 emit.cmd1_with_offset(param[0], scale_addr + scale_substream_offsets[core])
745 emit.cmd1_with_offset(
746 param[1], scale_substream_offsets[core + 1] - scale_substream_offsets[core]
747 )
Tim Hall62316762020-06-25 16:55:02 +0100748 elif core < arch.ncores:
749 emit.cmd1_with_offset(param[0], scale_addr)
750 emit.cmd1_with_offset(param[1], 0)
Tim Hallf7e810a2020-06-25 15:04:31 +0100751
Tim Hall79d07d22020-04-27 18:20:16 +0100752 # Emit base address for NPU to access scale & bias data
Patrik Gustavssoneca2e952020-05-27 09:15:11 +0200753 scale_region = base_ptr_idx_map[cmd.scale_tensor.mem_type]
Tim Hall79d07d22020-04-27 18:20:16 +0100754 emit.cmd0_with_param(cmd0.NPU_SET_SCALE_REGION, scale_region)
Tim Hall79d07d22020-04-27 18:20:16 +0100755
756 ofm_quant = cmd.ofm_tensor.quantization
757 ofm_quant_qmin = cmd.ofm_tensor.quantization.quant_min
758 ofm_quant_qmax = cmd.ofm_tensor.quantization.quant_max
759 ifm_min = cmd.ifm_tensor.quantization.min
760 ifm_max = cmd.ifm_tensor.quantization.max
761
762 # Emit commands for any fused activation function
Diego Russoea6111a2020-04-14 18:41:58 +0100763 if faf is None:
Tim Hall79d07d22020-04-27 18:20:16 +0100764 emit.cmd0_with_param(cmd0.NPU_SET_ACTIVATION, activation.NONE)
765 # Even if no activation function, values need to be set to override previous values
766 faf_min = ofm_quant_qmin
767 faf_max = ofm_quant_qmax
768 elif faf == "Relu":
769 emit.cmd0_with_param(cmd0.NPU_SET_ACTIVATION, activation.NONE)
770 faf_min = quantise_float32(0.0, ofm_quant.scale_f32, ofm_quant.zero_point)
771 faf_max = ofm_quant_qmax
772 elif faf == "Relu6":
773 emit.cmd0_with_param(cmd0.NPU_SET_ACTIVATION, activation.NONE)
774 faf_min = quantise_float32(0.0, ofm_quant.scale_f32, ofm_quant.zero_point)
775 faf_max = quantise_float32(6.0, ofm_quant.scale_f32, ofm_quant.zero_point)
776 elif faf == "ReluN1To1":
777 emit.cmd0_with_param(cmd0.NPU_SET_ACTIVATION, activation.NONE)
778 faf_min = quantise_float32(-1.0, ofm_quant.scale_f32, ofm_quant.zero_point)
779 faf_max = quantise_float32(1.0, ofm_quant.scale_f32, ofm_quant.zero_point)
780 elif faf == "Tanh":
781 emit.cmd0_with_param(cmd0.NPU_SET_ACTIVATION, activation.TANH)
Fredrik Svedberg620d88c2020-05-19 10:43:01 +0200782 if primary_op.type in set(("AvgPool", "AvgPoolAct", "ResizeBilinear")):
783 faf_min = quantise_float32(-1.0, ofm_quant.scale_f32, ofm_quant.zero_point)
784 faf_max = quantise_float32(1.0, ofm_quant.scale_f32, ofm_quant.zero_point)
785 else:
786 faf_min = quantise_float32(clamp_tanh(ifm_min), ofm_quant.scale_f32, ofm_quant.zero_point)
787 faf_max = quantise_float32(clamp_tanh(ifm_max), ofm_quant.scale_f32, ofm_quant.zero_point)
Tim Hall79d07d22020-04-27 18:20:16 +0100788 elif faf == "Sigmoid":
789 emit.cmd0_with_param(cmd0.NPU_SET_ACTIVATION, activation.SIGMOID)
Fredrik Svedberg620d88c2020-05-19 10:43:01 +0200790 if primary_op.type in set(("AvgPool", "AvgPoolAct", "ResizeBilinear")):
791 faf_min = quantise_float32(0, ofm_quant.scale_f32, ofm_quant.zero_point)
792 faf_max = quantise_float32(1.0, ofm_quant.scale_f32, ofm_quant.zero_point)
793 else:
794 faf_min = quantise_float32(clamp_sigmoid(ifm_min), ofm_quant.scale_f32, ofm_quant.zero_point)
795 faf_max = quantise_float32(clamp_sigmoid(ifm_max), ofm_quant.scale_f32, ofm_quant.zero_point)
Tim Hall79d07d22020-04-27 18:20:16 +0100796 else:
797 raise Exception("Unsupported fused_activation_function = " + faf)
798
799 # Activation range needs to be set based upon the quantisation range and the fused activation range
800 emit.cmd0_with_param(cmd0.NPU_SET_ACTIVATION_MIN, max(ofm_quant_qmin, faf_min))
801 emit.cmd0_with_param(cmd0.NPU_SET_ACTIVATION_MAX, min(ofm_quant_qmax, faf_max))
802
803 out_shape = cmd.ofm_box.get_size_shape()
804 if len(out_shape) >= 4:
805 emit.cmd0_with_param(cmd0.NPU_SET_OFM_HEIGHT_M1, out_shape[-3] - 1)
806 else:
807 emit.cmd0_with_param(cmd0.NPU_SET_OFM_HEIGHT_M1, 0)
808 if len(out_shape) >= 2:
809 emit.cmd0_with_param(cmd0.NPU_SET_OFM_WIDTH_M1, out_shape[-2] - 1)
810 else:
811 emit.cmd0_with_param(cmd0.NPU_SET_OFM_WIDTH_M1, 0)
812 emit.cmd0_with_param(cmd0.NPU_SET_OFM_DEPTH_M1, out_shape[-1] - 1)
813
814 if npu_block_type in set((NpuBlockType.ConvolutionMxN, NpuBlockType.VectorProduct)):
815 in_shape = cmd.ifm_box.get_size_shape()
816 emit.cmd0_with_param(cmd0.NPU_SET_IFM_DEPTH_M1, in_shape[-1] - 1)
817 else:
818 emit.cmd0_with_param(cmd0.NPU_SET_IFM_DEPTH_M1, out_shape[-1] - 1)
819
Jacob Bohlin3c678292020-04-27 10:27:25 +0200820 for tens, box, region_op, ptr_ops, stride_ops, zero_point_op in (
Tim Hall79d07d22020-04-27 18:20:16 +0100821 (
822 cmd.ifm_tensor,
823 cmd.ifm_box,
Jacob Bohlin3c678292020-04-27 10:27:25 +0200824 cmd0.NPU_SET_IFM_REGION,
Tim Hall79d07d22020-04-27 18:20:16 +0100825 (cmd1.NPU_SET_IFM_BASE0, cmd1.NPU_SET_IFM_BASE1, cmd1.NPU_SET_IFM_BASE2, cmd1.NPU_SET_IFM_BASE3),
826 (cmd1.NPU_SET_IFM_STRIDE_C, cmd1.NPU_SET_IFM_STRIDE_Y, cmd1.NPU_SET_IFM_STRIDE_X),
827 cmd0.NPU_SET_IFM_ZERO_POINT,
828 ),
829 (
830 cmd.ifm2_tensor,
831 cmd.ifm2_box,
Jacob Bohlin3c678292020-04-27 10:27:25 +0200832 cmd0.NPU_SET_IFM2_REGION,
Tim Hall79d07d22020-04-27 18:20:16 +0100833 (
834 cmd1.NPU_SET_IFM2_BASE0,
835 cmd1.NPU_SET_IFM2_BASE1,
836 cmd1.NPU_SET_IFM2_BASE2,
837 cmd1.NPU_SET_IFM2_BASE3,
838 ),
839 (cmd1.NPU_SET_IFM2_STRIDE_C, cmd1.NPU_SET_IFM2_STRIDE_Y, cmd1.NPU_SET_IFM2_STRIDE_X),
840 cmd0.NPU_SET_IFM2_ZERO_POINT,
841 ),
842 (
843 cmd.ofm_tensor,
844 cmd.ofm_box,
Jacob Bohlin3c678292020-04-27 10:27:25 +0200845 cmd0.NPU_SET_OFM_REGION,
Tim Hall79d07d22020-04-27 18:20:16 +0100846 (cmd1.NPU_SET_OFM_BASE0, cmd1.NPU_SET_OFM_BASE1, cmd1.NPU_SET_OFM_BASE2, cmd1.NPU_SET_OFM_BASE3),
847 (cmd1.NPU_SET_OFM_STRIDE_C, cmd1.NPU_SET_OFM_STRIDE_Y, cmd1.NPU_SET_OFM_STRIDE_X),
848 cmd0.NPU_SET_OFM_ZERO_POINT,
849 ),
850 ):
851
Diego Russoea6111a2020-04-14 18:41:58 +0100852 if tens is None:
Tim Hall79d07d22020-04-27 18:20:16 +0100853 continue
854
Jacob Bohlin9fbc4912020-06-29 11:58:50 +0200855 need_zero_point = (faf is not None) or (fmf == "ConcatSliceWrite") or fused_quantize
Tim Hall79d07d22020-04-27 18:20:16 +0100856 if (
Dwight Lidman86d49932020-06-04 15:31:56 +0200857 primary_op.type in set(("AvgPool", "AvgPoolAct", "ResizeBilinear")) and not need_zero_point
Diego Russoea6111a2020-04-14 18:41:58 +0100858 ) or tens.quantization is None:
Tim Hall79d07d22020-04-27 18:20:16 +0100859 # Actual integer operation, just set scale to 1 and zero point to 0
860 emit.cmd0_with_param(zero_point_op, 0)
861 else:
862 assert tens.quantization.zero_point is not None, "need an actual zero point set"
863 emit.cmd0_with_param(zero_point_op, int(tens.quantization.zero_point))
864
865 if tens.shape == []:
866 # Empty shape, elementwise constant
Louis Verhaardc88a96f2020-06-10 09:04:33 +0200867 ifm2_scalar = tens.quant_values
Tim Hall79d07d22020-04-27 18:20:16 +0100868 assert ifm2_scalar.size == 1
Louis Verhaardc88a96f2020-06-10 09:04:33 +0200869 emit.cmd0_with_param(cmd0.NPU_SET_IFM2_SCALAR, int(ifm2_scalar.item(0)))
Tim Hall79d07d22020-04-27 18:20:16 +0100870 continue
871
872 height_0, height_1, width_0, addresses = tens.addresses_for_rolling_buffer(
873 box.start_coord, box.end_coord
874 )
875 if npu_block_type != NpuBlockType.VectorProduct:
876 if tens == cmd.ifm_tensor:
877 emit.cmd0_with_param(cmd0.NPU_SET_IFM_HEIGHT0_M1, height_0 - 1)
878 emit.cmd0_with_param(cmd0.NPU_SET_IFM_HEIGHT1_M1, height_1 - 1)
879 emit.cmd0_with_param(cmd0.NPU_SET_IFM_WIDTH0_M1, width_0 - 1)
880 elif tens == cmd.ofm_tensor:
881 emit.cmd0_with_param(cmd0.NPU_SET_OFM_HEIGHT0_M1, height_0 - 1)
882 emit.cmd0_with_param(cmd0.NPU_SET_OFM_HEIGHT1_M1, height_1 - 1)
883 emit.cmd0_with_param(cmd0.NPU_SET_OFM_WIDTH0_M1, width_0 - 1)
Louis Verhaard0cf06c72020-05-12 08:31:05 +0200884 if tens == cmd.ifm2_tensor:
Tim Hall79d07d22020-04-27 18:20:16 +0100885 emit.cmd0_with_param(cmd0.NPU_SET_IFM2_HEIGHT0_M1, height_0 - 1)
886 emit.cmd0_with_param(cmd0.NPU_SET_IFM2_HEIGHT1_M1, height_1 - 1)
887 emit.cmd0_with_param(cmd0.NPU_SET_IFM2_WIDTH0_M1, width_0 - 1)
888 else:
889 if len(out_shape) == 2:
890 # TODO: N is put in W-dimension for now
891 # Should be spread over H and W, but then block size selectetion,
892 # and stride calculation should be changed
893 if tens == cmd.ifm_tensor:
894 emit.cmd0_with_param(cmd0.NPU_SET_IFM_WIDTH0_M1, out_shape[-2] - 1)
895 elif tens == cmd.ofm_tensor:
896 emit.cmd0_with_param(cmd0.NPU_SET_OFM_WIDTH0_M1, out_shape[-2] - 1)
897 else:
898 assert False
899
Patrik Gustavssoneca2e952020-05-27 09:15:11 +0200900 emit.cmd0_with_param(region_op, base_ptr_idx_map[tens.mem_type])
Jacob Bohlin3c678292020-04-27 10:27:25 +0200901
Tim Hall79d07d22020-04-27 18:20:16 +0100902 for idx, addr in enumerate(addresses):
903 if addr is None:
904 addresses[idx] = 0
905
906 emit.cmd1_with_offset(ptr_ops[0], addresses[0])
907 emit.cmd1_with_offset(ptr_ops[1], addresses[1])
908 emit.cmd1_with_offset(ptr_ops[2], addresses[2])
909 emit.cmd1_with_offset(ptr_ops[3], addresses[3])
910
911 strides = tens.get_strides()
912 emit.cmd1_with_offset(stride_ops[0], strides[1]) # stride between 16-byte channel blocks (C)
913 emit.cmd1_with_offset(stride_ops[2], strides[3]) # stride between horisontal values (W)
914 emit.cmd1_with_offset(stride_ops[1], strides[2]) # stride between vertical values (H)
915
916 if tens.format == TensorFormat.NHCWB16:
917 # Check that all BasePointer addresses are aligned to 16 bytes
918 assert (int(addresses[0]) % 16) == 0
919 assert (int(addresses[1]) % 16) == 0
920 assert (int(addresses[2]) % 16) == 0
921 assert (int(addresses[3]) % 16) == 0
922
923 ofm_dtype = cmd.ofm_tensor.dtype
924 assert ofm_dtype.type & BaseType.Int
925 prec = 0
926 if ofm_dtype.size_in_bits() == 8:
927 prec = 0
928 elif ofm_dtype.size_in_bits() == 16:
929 prec = 2
930 else:
931 assert 0
932
933 if ofm_dtype.type & BaseType.Signed:
934 prec += 1
935
936 if use_global_scale:
937 # Set global scale bit, as opposed to using per channel scale
938 prec |= 1 << 8
939
940 if cmd.ofm_tensor.format == TensorFormat.NHCWB16:
941 prec |= 1 << 6
942
943 prec |= rounding_mode.value << 14
944
945 emit.cmd0_with_param(cmd0.NPU_SET_OFM_PRECISION, prec)
946
947 prec = None
948 weight_bits = 8
949 if cmd.weight_tensor is not None:
950 weight_bits = cmd.weight_tensor.dtype.size_in_bits()
951
952 ifm_dtype = cmd.ifm_tensor.dtype
953
954 assert weight_bits == 8, "Unsupported weight bit depth"
955 assert ifm_dtype.size_in_bits() in {8, 16}
956
957 if ifm_dtype.size_in_bits() == 8:
958 if ifm_dtype.type & BaseType.Signed:
Diqing Zhongfed918b2020-04-27 10:27:34 +0200959 prec = ifm_precision.S8
Tim Hall79d07d22020-04-27 18:20:16 +0100960 else:
Diqing Zhongfed918b2020-04-27 10:27:34 +0200961 prec = ifm_precision.U8
Tim Hall79d07d22020-04-27 18:20:16 +0100962 elif ifm_dtype.size_in_bits() == 16:
963 if ifm_dtype.type & BaseType.Signed:
Diqing Zhongfed918b2020-04-27 10:27:34 +0200964 prec = ifm_precision.S16
Tim Hall79d07d22020-04-27 18:20:16 +0100965 else:
Diqing Zhongfed918b2020-04-27 10:27:34 +0200966 prec = ifm_precision.U16
Tim Hall79d07d22020-04-27 18:20:16 +0100967
968 ifm_prec = prec.value
969 ifm2_prec = ifm_prec
970
971 if cmd.ifm_tensor.format == TensorFormat.NHCWB16:
972 ifm_prec |= 1 << 6
973
974 ifm_prec |= op_to_scale << 8
975
976 emit.cmd0_with_param(cmd0.NPU_SET_IFM_PRECISION, ifm_prec)
977
978 if cmd.ifm2_tensor is not None:
979 if cmd.ifm2_tensor.format == TensorFormat.NHCWB16:
980 ifm2_prec |= 1 << 6
981 emit.cmd0_with_param(cmd0.NPU_SET_IFM2_PRECISION, ifm2_prec)
982
983 emit_wait_commands(cmd)
984
985 # Get op parameters
986 cur_ifm_block_depth = get_op_ifmofm_block_depth(arch, cmd)
987 cur_ofm_block = Block(ps.block_config[1], ps.block_config[0], ps.block_config[3])
988 cur_ofm_rect = get_op_ofm_rect(cmd)
989 cur_ifm_rect = get_op_ifm_rect(cmd)
Tim Hall79d07d22020-04-27 18:20:16 +0100990 cur_padLT = get_op_padding_lt(cmd)
991 if (prev_kernel is not None) and (cur_kernel is not None) and has_prev_op_dependency(prev_cmd, cmd):
992 if cmd.ifm_tensor.shape == prev_cmd.ofm_tensor.shape:
993 blockdep = arch.calc_block_dep(
994 prev_ifm_rect,
995 prev_ofm_rect,
996 prev_ifm_block_depth,
997 prev_ofm_block,
998 prev_kernel,
999 cur_ifm_rect,
1000 cur_ofm_rect,
1001 cur_ifm_block_depth,
1002 cur_ofm_block,
1003 cur_kernel,
1004 cur_padLT,
1005 )
1006 else:
1007 blockdep = 0
1008 else:
1009 blockdep = ArchitectureFeatures.MAX_BLOCKDEP
1010
1011 # Set between every op (dependent or not)
1012 blockdep = min(blockdep, arch.max_blockdep)
1013 emit.cmd0_with_param(cmd0.NPU_SET_BLOCKDEP, blockdep)
1014 prev_cmd = cmd
1015
1016 if npu_block_type == NpuBlockType.ConvolutionMxN:
1017 emit.cmd_do_operation(cmd0.NPU_OP_CONV)
1018 elif npu_block_type == NpuBlockType.ConvolutionDepthWise:
1019 emit.cmd_do_operation(cmd0.NPU_OP_DEPTHWISE)
1020 elif npu_block_type == NpuBlockType.VectorProduct:
1021 # Vector product is implemented using a 1x1 convolution
1022 emit.cmd_do_operation(cmd0.NPU_OP_CONV)
1023 elif npu_block_type == NpuBlockType.Pooling:
1024 param = "Max" not in primary_op.type
1025 emit.cmd_do_operation(cmd0.NPU_OP_POOL, param=param)
1026 elif npu_block_type == NpuBlockType.ElementWise:
1027 param = elementwise_mode_map[primary_op.type]
1028 emit.cmd_do_operation(cmd0.NPU_OP_ELEMENTWISE, param)
1029 else:
1030 print("Warning: Skipping register command stream generation for", ps)
1031
1032 # Fill in final part of command stream:
1033 emit.cmd_do_operation(cmd0.NPU_OP_STOP, param=0xFFFF)
1034
1035 sg.register_command_stream = emit.to_list()
1036 if verbose:
1037 emit.print_cmds()
1038 print("number of commands", len(emit.cmd_stream))
1039 print("command stream length in words", len(sg.register_command_stream))