blob: 09348811133fd6bad10b228a95993a9128f667db [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
Fredrik Svedberga0c36242020-06-03 15:43:31 +020041from .ethos_u55_regs.ethos_u55_regs import pooling_mode
Jacob Bohlincf7da102020-05-20 09:03:40 +020042from .ethos_u55_regs.ethos_u55_regs import resampling_mode
Diego Russoe8a10452020-04-21 17:39:10 +010043from .ethos_u55_regs.ethos_u55_regs import rounding
Tim Hall79d07d22020-04-27 18:20:16 +010044from .high_level_command_stream import CommandType
Diego Russoe8a10452020-04-21 17:39:10 +010045from .numeric_util import clamp_sigmoid
46from .numeric_util import clamp_tanh
Louis Verhaardb2fb2122020-06-04 15:51:24 +020047from .numeric_util import full_shape
Diego Russoe8a10452020-04-21 17:39:10 +010048from .numeric_util import quantise_float32
49from .numeric_util import round_away_zero
Diego Russoe8a10452020-04-21 17:39:10 +010050from .numeric_util import round_up_to_int
Tim Hall79d07d22020-04-27 18:20:16 +010051from .operation import NpuBlockType
Tim Hall79d07d22020-04-27 18:20:16 +010052from .shared_buffer_allocation import SharedBufferAllocation
Patrik Gustavssoneca2e952020-05-27 09:15:11 +020053from .tensor import MemType
Diego Russoe8a10452020-04-21 17:39:10 +010054from .tensor import TensorBlockTraversal
55from .tensor import TensorFormat
Fredrik Svedberga0c36242020-06-03 15:43:31 +020056from .tensor import TensorPurpose
Tim Hall79d07d22020-04-27 18:20:16 +010057
58
59class RegisterMachine:
60 def __init__(self):
61 self.n_banks = 1
62 self.registers = [defaultdict(lambda: None) for _ in range(self.n_banks)]
63 self.bank_idx = 0
64
65 def set_register(self, reg, value):
66 is_changed = self.registers[self.bank_idx][reg] != value
67 self.registers[self.bank_idx][reg] = value
68 # is_changed = True # force command
69 return is_changed
70
71 def switch_bank(self):
72 self.bank_idx = (self.bank_idx + 1) % self.n_banks
73
74
75class CmdMode(IntEnum):
76 NoPayload = 0x0000
77 Payload32 = 0x4000
78 Mask = 0xC000
79 CmdOpMask = 0x03FF
80
81
82class BasePointerIndex(IntEnum):
Patrik Gustavssoneca2e952020-05-27 09:15:11 +020083 WeightTensor = 0 # base address index for the Weight tensor
84 ScratchTensor = 1 # base address index for the Scratch_tensor in the TensorArena
85 ScratchFastTensor = 2 # base address for the Scratch_fast_tensor
Fredrik Svedberga0c36242020-06-03 15:43:31 +020086 Mem2Mem = (1 << 8) | (3 << 0) # base address slot for memory 2 memory transfer
Tim Hall79d07d22020-04-27 18:20:16 +010087
88
89# TODO: Replace with definitions from ethos_u55_regs
90class IFM2Broadcast(IntEnum):
91 BroadcastHdim = 1 << 0
92 BroadcastWdim = 1 << 1
93 BroadcastCdim = 1 << 2
94 ReverseOperandOrder = 1 << 6
95 UseIFM2Scalar = 1 << 7
96
97
98class CommandStreamEmitter:
99 def __init__(self):
100 self.cmd_stream = []
101 self.reg_machine = [RegisterMachine(), RegisterMachine()]
102 self.last_absolute_wait = defaultdict(int)
103
104 def get_reg_machine(self, cmd):
105 if "DMA" in cmd.name:
106 return self.reg_machine[1]
107 else:
108 return self.reg_machine[0]
109
110 def size_in_bytes(self):
111 sz = 0
112 for cmd in self.cmd_stream:
113 sz += len(cmd) * 4
114 return sz
115
116 def to_list(self):
117 return [elem for cmd in self.cmd_stream for elem in cmd]
118
119 def print_cmds(self):
120 print("Code: Command: Param: Payload:")
121 for words_for_one_command in self.cmd_stream:
122 code = words_for_one_command[0] & 0x0000FFFF # lower 16 bits
123 param = words_for_one_command[0] >> 16 # higher 16 bits
124
125 payload_mode = CmdMode(code & CmdMode.Mask)
126
127 # code and command
128 s = " 0x%04x " % code
129 if payload_mode == CmdMode.NoPayload:
130 s += str(cmd0(code & CmdMode.CmdOpMask))
131 else:
132 s += str(cmd1(code & CmdMode.CmdOpMask))
133
134 s = s.ljust(40)
135 s += "%5d" % param
136
137 # payload
138 if payload_mode == CmdMode.Payload32:
139 s += " 0x%08x (%d)" % (words_for_one_command[1], words_for_one_command[1])
140 else:
141 s += " -"
142
143 print(s)
144
145 def cmd0_with_param(self, cmd, param):
146 if isinstance(param, Enum):
147 param = int(param.value)
148 else:
149 param = int(param)
150 param = param & 0xFFFF
151 command = cmd.value | (param << 16)
152 if not self.get_reg_machine(cmd).set_register(cmd, (command, param)):
153 return
154
155 # This is not a redundant command, actually write it
156 self.cmd_stream.append((command,))
157
158 def cmd1_with_offset(self, cmd, offset, param=0x0):
159 offset = int(offset) & 0xFFFFFFFFF
160 command = cmd.value | CmdMode.Payload32.value | (param << 16)
161
162 if not self.get_reg_machine(cmd).set_register(cmd, (command, offset)):
163 return
164
165 # This is not a redundant command, actually write it
166 self.cmd_stream.append((command, offset))
167
168 def cmd_wait(self, cmd, param, absolute_wait_time):
169 if absolute_wait_time <= self.last_absolute_wait[cmd]:
170 return
171
172 self.last_absolute_wait[cmd] = absolute_wait_time
173 param = int(param)
174 command = ((param & 0xFFFF) << 16) | cmd.value
175 self.cmd_stream.append((command,))
176
177 def cmd_do_operation(self, cmd, param=0):
178 param = int(param)
179 command = ((param & 0xFFFF) << 16) | cmd.value
180
181 self.cmd_stream.append((command,))
182 self.get_reg_machine(cmd).switch_bank()
183
184
185def calc_command_dependencies(cmd_stream, arch):
186 cmd_starts = {}
187 cmd_ends = {}
188 memory_accesses = {}
189
190 # Keep track of accumulated number of commands in command stream.
191 # First element kernel ops: (# of blocks, # of commands)
192 # Second element DMA ops: (# of commands)
Michael McGeagh8677e532020-07-28 11:32:22 +0100193 pos = np.array((np.array((0, 0)), np.array([0])), dtype=object)
Tim Hall79d07d22020-04-27 18:20:16 +0100194
195 dependencies = {}
196
197 for cmd in cmd_stream:
198 cmd_starts[cmd] = pos
199 op_count = cmd.get_operation_count()
200 # Keep track of both num blocks and commands
201 cmd_add = 0 if (op_count[0] == 0) else 1
Michael McGeagh8677e532020-07-28 11:32:22 +0100202 pos = np.array((pos[0] + np.array((op_count[0], cmd_add)), pos[1] + np.array([op_count[1]])), dtype=object)
203 cmd_ends[cmd] = np.array((pos[0], pos[1]), dtype=object)
Tim Hall79d07d22020-04-27 18:20:16 +0100204 memory_accesses[cmd] = cmd.get_memory_accesses()
205
206 for idx, cmd in enumerate(cmd_stream):
207 curr_accesses = memory_accesses[cmd]
208 # Keep track of command dependency.
209 # First element kernel ops: (# of blocks, # of commands)
210 # Second element DMA ops: (# of commands)
Michael McGeagh8677e532020-07-28 11:32:22 +0100211 dep_offsets = np.array((np.array((-1, -1)), np.array([-1])), dtype=object)
Tim Hall79d07d22020-04-27 18:20:16 +0100212 dep_cmds = [None] * CommandType.Size.value
213 if idx > 0:
214 # Look at the previous commands in backwards order
215 for prev_cmd in cmd_stream[idx - 1 :: -1]:
216 assert prev_cmd is not cmd
217 if dep_cmds[prev_cmd.cmdtype] is None:
218 is_dependency = False
219 if cmd.cmdtype == CommandType.NpuStripe and prev_cmd.cmdtype == CommandType.NpuStripe:
220 # Special handling here, as dpu -> dpu operations require additional care
221 if not SharedBufferAllocation.is_compatible(prev_cmd.ps.shared_buffer, cmd.ps.shared_buffer):
222 is_dependency = True
223 elif memory_accesses[prev_cmd].conflicts(curr_accesses):
224 is_dependency = True
225 else:
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200226 if memory_accesses[prev_cmd].conflicts(curr_accesses) or (
227 prev_cmd.cmdtype == CommandType.DMA and prev_cmd.in_tensor.purpose == TensorPurpose.LUT
228 ):
Tim Hall79d07d22020-04-27 18:20:16 +0100229 is_dependency = True
230
231 if is_dependency:
232 new_offset = cmd_ends[prev_cmd][prev_cmd.cmdtype]
233 if new_offset[0] > dep_offsets[prev_cmd.cmdtype][0]:
234 dep_cmds[prev_cmd.cmdtype] = prev_cmd
235 dep_offsets[prev_cmd.cmdtype] = new_offset
236
237 # Check if we've got dependencies for all commands, in which case we can early out
238 for dep in dep_cmds:
239 if dep is None:
240 break
241 else:
242 break # all handled
243
244 # Convert absolute to relative dependencies, using None to signal the special case of no
245 # dependency of this kind
246 res = [None] * CommandType.Size.value
247 for i in range(CommandType.Size.value):
248 if dep_cmds[i] is not None:
249 res[i] = cmd_starts[cmd][i] - dep_offsets[i]
250
251 dependencies[cmd] = cmd_starts[cmd], res
252
253 return dependencies
254
255
256def get_op_kernel(ps):
257 if ps.primary_op is None:
258 return None
259
260 strides = ps.primary_op.attrs.get("strides", (1, 1, 1, 1))
261 dilation = ps.primary_op.attrs.get("dilation", (1, 1, 1, 1))
262 if ps.weight_tensor:
263 if ps.npu_block_type in set((NpuBlockType.VectorProduct, NpuBlockType.ElementWise)):
264 k_h = 1
265 k_w = 1
266 else:
267 k_h = ps.weight_tensor.shape[0]
268 k_w = ps.weight_tensor.shape[1]
269 else:
270 k_h = ps.primary_op.attrs.get("filter_height", 1)
271 k_w = ps.primary_op.attrs.get("filter_width", 1)
272
273 return Kernel(k_w, k_h, strides[2], strides[1], dilation[2], dilation[1])
274
275
Tim Hall79d07d22020-04-27 18:20:16 +0100276def has_prev_op_dependency(prev_cmd, cmd):
277 if prev_cmd is None:
278 return False
279 if (prev_cmd.cmdtype == cmd.cmdtype == CommandType.NpuStripe) and (prev_cmd.ps != cmd.ps):
Tim Hall90337952020-05-07 16:42:35 +0100280 if prev_cmd.ofm_tensor.equivalence_id == cmd.ifm_tensor.equivalence_id:
Tim Hall79d07d22020-04-27 18:20:16 +0100281 return True
Tim Hall90337952020-05-07 16:42:35 +0100282 elif cmd.ifm2_tensor is not None:
Louis Verhaardb2fb2122020-06-04 15:51:24 +0200283 return prev_cmd.ofm_tensor.equivalence_id == cmd.ifm2_tensor.equivalence_id
Tim Hall79d07d22020-04-27 18:20:16 +0100284 return False
285
286
287def get_op_ofm_rect(cmd):
Charles Xu3e9c4342020-04-22 08:31:43 +0200288 start = full_shape(4, cmd.ofm_box.start_coord, 0)
289 end = full_shape(4, cmd.ofm_box.end_coord, 1)
Tim Hall79d07d22020-04-27 18:20:16 +0100290 return Rect(start[-2], start[-3], start[-1], end[-2] - 1, end[-3] - 1, end[-1] - 1)
291
292
293def get_op_ifm_rect(cmd):
Charles Xu3e9c4342020-04-22 08:31:43 +0200294 start = full_shape(4, cmd.ifm_box.start_coord, 0)
295 end = full_shape(4, cmd.ifm_box.end_coord, 1)
Tim Hall79d07d22020-04-27 18:20:16 +0100296 return Rect(start[-2], start[-3], start[-1], end[-2] - 1, end[-3] - 1, end[-1] - 1)
297
298
299def get_op_ifmofm_block_depth(arch, cmd):
300 # Note: NOT equivalent to the normal ifm block depth calculation since
301 # it takes into account 'depthless' block operations by returning full
302 # depth
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200303 if cmd.ps.npu_block_type in (
304 NpuBlockType.ConvolutionDepthWise,
305 NpuBlockType.Pooling,
306 NpuBlockType.ElementWise,
307 NpuBlockType.ReduceSum,
308 ):
Tim Hall79d07d22020-04-27 18:20:16 +0100309 return cmd.ofm_box.get_size_shape()[-1]
310
311 return arch.calc_ifm_block_depth(cmd.ifm_box.get_size_shape()[-1], cmd.ifm_tensor.dtype.bits)
312
313
314def get_op_padding_lt(cmd):
315 if cmd.ps.npu_block_type not in (
316 NpuBlockType.ConvolutionDepthWise,
317 NpuBlockType.Pooling,
318 NpuBlockType.ConvolutionMxN,
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200319 NpuBlockType.ReduceSum,
Tim Hall79d07d22020-04-27 18:20:16 +0100320 ):
321 return (0, 0)
322
323 explicit_padding = list(cmd.ps.primary_op.attrs["explicit_padding"]) # (top, left, bottom, right)
324
325 # Check if this is for horizontal ifm streaming
326 if not (cmd.is_first_h_stripe and cmd.is_last_h_stripe):
327 explicit_padding[0] = cmd.pad_top
328 explicit_padding[2] = cmd.pad_bottom
329
330 return (explicit_padding[1], explicit_padding[0])
331
332
Jacob Bohline99b8932020-07-13 16:01:51 +0200333def ifm_ifm2_correct_order(ifm_shape, ifm2_shape):
334 if ifm_shape == []:
335 # Scalar needs to be in IFM2
336 return False
337 elif ifm2_shape == []:
338 return True
339
340 for ifm, ifm2 in zip(ifm_shape, ifm2_shape):
341 if ifm != ifm2 and ifm == 1:
342 # Broadcasted FM needs to be in IFM2
343 return False
344
345 return True
346
347
Tim Hall79d07d22020-04-27 18:20:16 +0100348def generate_register_command_stream(nng, sg, arch, verbose=False):
349 emit = CommandStreamEmitter()
350
Patrik Gustavssoneca2e952020-05-27 09:15:11 +0200351 if arch.feature_map_storage_mem_area == arch.fast_storage_mem_area:
352 base_ptr_idx_map = {
353 MemType.Permanent_NPU: BasePointerIndex.WeightTensor,
354 MemType.Permanent_CPU: BasePointerIndex.WeightTensor,
355 MemType.Scratch: BasePointerIndex.ScratchTensor,
356 MemType.Scratch_fast: BasePointerIndex.ScratchTensor,
357 }
358 else:
359 base_ptr_idx_map = {
360 MemType.Permanent_NPU: BasePointerIndex.WeightTensor,
361 MemType.Permanent_CPU: BasePointerIndex.WeightTensor,
362 MemType.Scratch: BasePointerIndex.ScratchTensor,
363 MemType.Scratch_fast: BasePointerIndex.ScratchFastTensor,
364 }
Tim Hall79d07d22020-04-27 18:20:16 +0100365
366 # Maps an AccumulatorType enum to the corresponding acc_format value
367 acc_format_map = {
368 SHRAMElements.Acc16: acc_format.FP_S5_10.value,
369 SHRAMElements.Acc32: acc_format.INT_32BIT.value,
370 SHRAMElements.Acc40: acc_format.INT_40BIT.value,
371 }
372
373 # Maps an elementwise op type to an elementwise_mode enum value used by NPU_OP_ELEMENTWISE
374 elementwise_mode_map = {
375 "MulAct": elementwise_mode.MUL.value,
376 "AddAct": elementwise_mode.ADD.value,
377 "SubAct": elementwise_mode.SUB.value,
378 "Minimum": elementwise_mode.MIN.value,
379 "Maximum": elementwise_mode.MAX.value,
380 "LeakyRelu": elementwise_mode.LRELU.value,
381 "Abs": elementwise_mode.ABS.value,
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200382 "CLZ": elementwise_mode.CLZ.value,
383 "SHR": elementwise_mode.SHR.value,
384 "SHL": elementwise_mode.SHL.value,
Tim Hall79d07d22020-04-27 18:20:16 +0100385 }
386
387 cmd_stream = []
388 for cmd in sg.high_level_command_stream:
389 if cmd.cmdtype == CommandType.NpuStripe and cmd.ps.npu_block_type == NpuBlockType.Default:
390 print("Warning: Skipping register command stream generation for", cmd.ps)
391 else:
392 cmd_stream.append(cmd)
393
394 dependencies = calc_command_dependencies(cmd_stream, arch)
395
396 # Initialise operator dependency state
397 prev_ifm_rect = cur_ifm_rect = None
398 prev_ifm_block_depth = cur_ifm_block_depth = None
399 prev_ofm_rect = cur_ofm_rect = None
400 prev_ofm_block = cur_ofm_block = None
401 prev_kernel = cur_kernel = None
402 prev_cmd = None
403
404 def emit_wait_commands(cmd):
405 # The command is fully set up, emit whatever wait commands we need
406 absolute_dep, relative_dep = dependencies[cmd]
407 if relative_dep[CommandType.NpuStripe] is not None:
408 if cmd.cmdtype == CommandType.DMA:
409 param = relative_dep[CommandType.NpuStripe][1]
410 if param <= 3:
411 emit.cmd_wait(cmd0.NPU_OP_KERNEL_WAIT, param, absolute_dep[CommandType.NpuStripe][1])
412 else:
413 param = relative_dep[CommandType.NpuStripe][0]
414 param = min(param, 0xFFFF) # Clamp to allowable wait amount
415
416 if relative_dep[CommandType.DMA] is not None:
Patrik Gustavssoneca2e952020-05-27 09:15:11 +0200417 # TODO This can be optimized for yoda
418 param = 0
Tim Hall79d07d22020-04-27 18:20:16 +0100419 emit.cmd_wait(cmd0.NPU_OP_DMA_WAIT, param, absolute_dep[CommandType.DMA][0])
Tim Hall79d07d22020-04-27 18:20:16 +0100420
Tim Hall42e41892020-07-06 10:51:31 +0100421 if arch.is_yoda_system:
Jacob Bohlin0b9ca782020-07-09 11:16:30 +0200422 emit.cmd0_with_param(cmd0.NPU_SET_PARALLEL_MODE, arch.ncores - 1)
Tim Hallf7e810a2020-06-25 15:04:31 +0100423
Tim Hall79d07d22020-04-27 18:20:16 +0100424 for cmd in cmd_stream:
425 if cmd.cmdtype == CommandType.DMA:
426 start_coord = cmd.box.start_coord
427
428 src_addr = cmd.in_tensor.address_for_coordinate(start_coord)
429 dst_addr = cmd.out_tensor.address_for_coordinate(start_coord)
430
431 if cmd.in_tensor.compressed_values is not None:
432 stream_index = cmd.in_tensor.compressed_stream_index_from_coord(start_coord)
433 sz = cmd.in_tensor.size_of_compressed_stream(stream_index)
434 else:
435 sz = cmd.in_tensor.address_for_coordinate(cmd.box.end_coord, is_top_box=True) - src_addr
436
Patrik Gustavssoneca2e952020-05-27 09:15:11 +0200437 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 +0100438 emit.cmd1_with_offset(cmd1.NPU_SET_DMA0_SRC, src_addr)
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200439 if cmd.out_tensor.purpose == TensorPurpose.LUT:
440 emit.cmd0_with_param(cmd0.NPU_SET_DMA0_DST_REGION, BasePointerIndex.Mem2Mem)
441 else:
442 emit.cmd0_with_param(cmd0.NPU_SET_DMA0_DST_REGION, base_ptr_idx_map[cmd.out_tensor.mem_type])
Patrik Gustavssoneca2e952020-05-27 09:15:11 +0200443
Tim Hall79d07d22020-04-27 18:20:16 +0100444 emit.cmd1_with_offset(cmd1.NPU_SET_DMA0_DST, dst_addr)
445 emit.cmd1_with_offset(cmd1.NPU_SET_DMA0_LEN, sz)
446 dma_channel = 0
447 mode = 0 # From external to external
448
449 emit_wait_commands(cmd)
450 emit.cmd_do_operation(cmd0.NPU_OP_DMA_START, dma_channel * 16 + mode)
451
452 elif cmd.cmdtype == CommandType.NpuStripe:
453
454 ps = cmd.ps
455 primary_op = ps.primary_op
456 npu_block_type = ps.npu_block_type
457 # Specifies if global scale from the NPU_SET_OFM_SCALE register should be used instead of per-channel scale
458 use_global_scale = False
459 # Specifies type of rounding to be used.
460 rounding_mode = rounding.TFL
Louis Verhaardb2fb2122020-06-04 15:51:24 +0200461 if primary_op.type == "ResizeBilinear":
Dwight Lidman3ec04ac2020-04-30 11:54:48 +0200462 rounding_mode = rounding.TRUNCATE
Tim Hall79d07d22020-04-27 18:20:16 +0100463 fmf = primary_op.attrs.get("fused_memory_function", None)
464 faf = primary_op.attrs.get("fused_activation_function", None)
Jacob Bohlin9fbc4912020-06-29 11:58:50 +0200465 fused_quantize = any(op.type == "Quantize" for op in ps.ops)
Tim Hall79d07d22020-04-27 18:20:16 +0100466
467 # Specifies which operand to apply scaling to in bitexact elementwise ADD/SUB
468 op_to_scale = 0
469
470 # Update state history
471 prev_ifm_rect = cur_ifm_rect
472 prev_ifm_block_depth = cur_ifm_block_depth
473 prev_ofm_rect = cur_ofm_rect
474 prev_ofm_block = cur_ofm_block
475 prev_kernel = cur_kernel
Louis Verhaardb2fb2122020-06-04 15:51:24 +0200476 cur_kernel = get_op_kernel(ps)
Tim Hall79d07d22020-04-27 18:20:16 +0100477
478 block_config = ps.block_config
479 emit.cmd0_with_param(cmd0.NPU_SET_OFM_BLK_HEIGHT_M1, block_config[0] - 1)
480 emit.cmd0_with_param(cmd0.NPU_SET_OFM_BLK_WIDTH_M1, block_config[1] - 1)
481 emit.cmd0_with_param(cmd0.NPU_SET_OFM_BLK_DEPTH_M1, block_config[3] - 1)
482
483 shared_buffer = ps.shared_buffer
484
485 if npu_block_type == NpuBlockType.ElementWise:
Jacob Bohlinbe733cf2020-08-13 10:21:34 +0200486 ifm2_broadcast = 0
Tim Hall79d07d22020-04-27 18:20:16 +0100487
Jacob Bohlinbf612682020-08-13 09:37:02 +0200488 if cmd.ifm2_tensor and not ifm_ifm2_correct_order(cmd.ifm_tensor.shape, cmd.ifm2_tensor.shape):
Tim Hall79d07d22020-04-27 18:20:16 +0100489 # The scalar has to be the ifm2 tensor so switch the ifms
490 cmd.ifm_tensor, cmd.ifm2_tensor = cmd.ifm2_tensor, cmd.ifm_tensor
491 cmd.ifm_box, cmd.ifm2_box = cmd.ifm2_box, cmd.ifm_box
492
493 # Set ReverseOperandOrder bit to IFM2_BROADCAST
494 ifm2_broadcast |= IFM2Broadcast.ReverseOperandOrder
495
496 # Calculate scales needed for arithmetic elementwise operators
497 if primary_op.type in set(("AddAct", "MulAct", "SubAct",)):
498 input_scale = cmd.ifm_tensor.quantization.scale_f32
499 input2_scale = cmd.ifm2_tensor.quantization.scale_f32
500 output_scale = cmd.ofm_tensor.quantization.scale_f32
501 use_global_scale = True
502
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200503 if output_scale is not None and faf in ("Sigmoid", "Tanh"):
504 output_scale = 1 / 0x3000
Tim Hall79d07d22020-04-27 18:20:16 +0100505
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200506 if primary_op.type == "MulAct":
507 if None in (input_scale, input2_scale, output_scale):
508 ofm_scale = 1
509 shift = 0
510 else:
511 ofm_scale, shift = scaling.elementwise_mul_scale(input_scale, input2_scale, output_scale)
Tim Hall79d07d22020-04-27 18:20:16 +0100512 emit.cmd1_with_offset(cmd1.NPU_SET_OFM_SCALE, ofm_scale, shift)
513 else: # AddAct/SubAct
Charles Xu9a03fdf2020-07-02 15:12:40 +0200514 # Force output scale same as the input scale for
515 # resizebiliner 1x1 that is converted to add
516 if "resizebilinear" in primary_op.attrs:
517 output_scale = input2_scale
518
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200519 if None in (input_scale, input2_scale, output_scale):
520 opa_scale = opb_scale = ofm_scale = 1
521 opa_shift = shift = 0
522 elif input_scale == input2_scale:
Tim Hall79d07d22020-04-27 18:20:16 +0100523 opa_scale, opb_scale, ofm_scale, shift = scaling.simplified_elementwise_add_sub_scale(
524 input_scale, input2_scale, output_scale
525 )
526 opa_shift = 0 # Unused for this case
527 else:
528 # Use advanced implementation only when input scales differ
529 bitdepth = cmd.ifm_tensor.dtype.bits
530 (
531 opa_scale,
532 opa_shift,
533 ofm_scale,
534 shift,
535 op_to_scale,
536 ) = scaling.advanced_elementwise_add_sub_scale(
537 input_scale, input2_scale, output_scale, bitdepth
538 )
539 opb_scale = 0 # Unused for this case
540 if ifm2_broadcast & IFM2Broadcast.ReverseOperandOrder:
541 # If the operand order is reversed we also have to swap which operand is scaled
542 if op_to_scale == scaling.OperandToScale.OPa:
543 op_to_scale = scaling.OperandToScale.OPb
544 else:
545 op_to_scale = scaling.OperandToScale.OPa
546
547 emit.cmd1_with_offset(cmd1.NPU_SET_OPA_SCALE, opa_scale, opa_shift)
548 emit.cmd1_with_offset(cmd1.NPU_SET_OPB_SCALE, opb_scale)
549 emit.cmd1_with_offset(cmd1.NPU_SET_OFM_SCALE, ofm_scale, shift)
550
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200551 elif primary_op.type in set(("LeakyRelu", "Abs",)):
Tim Hall79d07d22020-04-27 18:20:16 +0100552 output_scale = cmd.ofm_tensor.quantization.scale_f32
553 use_global_scale = True
554
555 if primary_op.type == "LeakyRelu":
556 output_scale *= primary_op.attrs["alpha"]
557
558 ofm_scale, shift = scaling.quantise_scale(output_scale)
559 emit.cmd1_with_offset(cmd1.NPU_SET_OFM_SCALE, ofm_scale, shift)
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200560 else:
561 emit.cmd1_with_offset(cmd1.NPU_SET_OFM_SCALE, 1, 0)
Tim Hall79d07d22020-04-27 18:20:16 +0100562
563 # For elementwise set the required SHRAM to be equal to the total size of SHRAM
564 shram_required = arch.shram_total_banks
565 emit.cmd0_with_param(cmd0.NPU_SET_IFM_IB_END, shram_required)
566
567 # Acc buffers not needed so set AB_START to size of SHRAM
568 emit.cmd0_with_param(cmd0.NPU_SET_AB_START, arch.shram_total_banks)
569
570 # Is not a unary operator
571 if cmd.ifm2_tensor is not None:
572 if cmd.ifm2_tensor.shape == []:
573 # IFM2 is a constant, set UseIFM2Scalar bit to IFM2_BROADCAST
574 ifm2_broadcast |= IFM2Broadcast.UseIFM2Scalar
575 else:
576 ifm_box_shape = cmd.ifm_box.get_size_shape()
577 ifm2_box_shape = cmd.ifm2_box.get_size_shape()
578
579 if len(cmd.ifm_tensor.shape) > 1 and ifm_box_shape[1] != ifm2_box_shape[1]:
580 # Broadcast in 'H' dimension
581 assert cmd.ifm2_tensor.shape[1] == 1
582 ifm2_broadcast |= IFM2Broadcast.BroadcastHdim
583
584 if len(cmd.ifm_tensor.shape) > 2 and ifm_box_shape[2] != ifm2_box_shape[2]:
585 # Broadcast in 'W' dimension
586 assert cmd.ifm2_tensor.shape[2] == 1
587 ifm2_broadcast |= IFM2Broadcast.BroadcastWdim
588
589 if len(cmd.ifm_tensor.shape) > 3 and ifm_box_shape[3] != ifm2_box_shape[3]:
590 # Broadcast in 'C' dimension
591 assert cmd.ifm2_tensor.shape[3] == 1
592 ifm2_broadcast |= IFM2Broadcast.BroadcastCdim
593
594 # Set IFM2_IB_START to the latter half of the IB space
595 ifm_ib_start = shared_buffer.bank_locations[SharedBufferArea.IFM]
596 emit.cmd0_with_param(
597 cmd0.NPU_SET_IFM2_IB_START, (shram_required - ifm_ib_start) / 2 + ifm_ib_start
598 )
599
600 emit.cmd0_with_param(cmd0.NPU_SET_IFM2_BROADCAST, ifm2_broadcast)
601
602 else:
603 emit.cmd0_with_param(
604 cmd0.NPU_SET_IFM_IB_END,
605 shared_buffer.bank_locations[SharedBufferArea.IFM]
606 + shared_buffer.banks_required[SharedBufferArea.IFM],
607 )
608 emit.cmd0_with_param(cmd0.NPU_SET_AB_START, shared_buffer.bank_locations[SharedBufferArea.Accumulators])
609
610 emit.cmd0_with_param(cmd0.NPU_SET_ACC_FORMAT, acc_format_map[shared_buffer.use_accumulator_element])
611
Louis Verhaardb2fb2122020-06-04 15:51:24 +0200612 if primary_op.type == "ResizeBilinear":
Dwight Lidman3ec04ac2020-04-30 11:54:48 +0200613 # perform nearest neighbor upscale
Jacob Bohlincf7da102020-05-20 09:03:40 +0200614 emit.cmd0_with_param(cmd0.NPU_SET_IFM_UPSCALE, resampling_mode.NEAREST)
615 elif primary_op.type == "Conv2DBackpropInputSwitchedBias":
616 # perform insert zero upscale
617 emit.cmd0_with_param(cmd0.NPU_SET_IFM_UPSCALE, resampling_mode.TRANSPOSE)
Dwight Lidman3ec04ac2020-04-30 11:54:48 +0200618 else:
Jacob Bohlincf7da102020-05-20 09:03:40 +0200619 emit.cmd0_with_param(cmd0.NPU_SET_IFM_UPSCALE, resampling_mode.NONE)
Tim Hall79d07d22020-04-27 18:20:16 +0100620
621 if npu_block_type in set(
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200622 (
623 NpuBlockType.ConvolutionMxN,
624 NpuBlockType.ConvolutionDepthWise,
625 NpuBlockType.Pooling,
626 NpuBlockType.ReduceSum,
627 )
Tim Hall79d07d22020-04-27 18:20:16 +0100628 ):
629 # Set up padding
630 explicit_padding = list(primary_op.attrs["explicit_padding"]) # (top, left, bottom, right)
631
632 # Check if this is for horizontal ifm streaming
633 if not (cmd.is_first_h_stripe and cmd.is_last_h_stripe):
634 explicit_padding[0] = cmd.pad_top
635 explicit_padding[2] = cmd.pad_bottom
636
637 # Indexing from end since a 1x1 Avgpool might have been added with non 4-dimensional input/output,
638 # because of activation function needed to be fused.
639 if cmd.ifm_box.start_coord[-2] > 0:
640 explicit_padding[1] = 0
641 if cmd.ifm_box.end_coord[-2] < cmd.ifm_tensor.shape[-2]:
642 explicit_padding[3] = 0
Tim Hall79d07d22020-04-27 18:20:16 +0100643 emit.cmd0_with_param(cmd0.NPU_SET_IFM_PAD_TOP, explicit_padding[0])
644 emit.cmd0_with_param(cmd0.NPU_SET_IFM_PAD_LEFT, explicit_padding[1])
645 emit.cmd0_with_param(cmd0.NPU_SET_IFM_PAD_BOTTOM, explicit_padding[2])
646 emit.cmd0_with_param(cmd0.NPU_SET_IFM_PAD_RIGHT, explicit_padding[3])
647
Dwight Lidman0538a772020-05-06 14:09:17 +0200648 # set kernel x stride low bit
649 stride = primary_op.attrs["strides"][2] - 1 & 1
650 # set kernel y stride low bit
651 stride |= (primary_op.attrs["strides"][1] - 1 & 1) << 1
652 # set kernel x stride extension bits
653 stride |= (primary_op.attrs["strides"][2] - 1 >> 1) << 6
654 # set kernel y stride extension bits
655 stride |= (primary_op.attrs["strides"][1] - 1 >> 1) << 9
656
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200657 if npu_block_type in set((NpuBlockType.Pooling, NpuBlockType.ReduceSum)):
Tim Hall79d07d22020-04-27 18:20:16 +0100658 k_height, k_width = primary_op.attrs["ksize"][1:3]
659 emit.cmd0_with_param(cmd0.NPU_SET_KERNEL_HEIGHT_M1, k_height - 1)
660 emit.cmd0_with_param(cmd0.NPU_SET_KERNEL_WIDTH_M1, k_width - 1)
661
662 valid_padding = sum(explicit_padding) == 0
663
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200664 if (
665 primary_op.type in set(("AvgPool", "AvgPoolAct", "ResizeBilinear", "ReduceSum"))
666 and valid_padding
667 ):
Tim Hall79d07d22020-04-27 18:20:16 +0100668 # For valid padding vela has to output scaling values
669 if faf == "Sigmoid" or faf == "Tanh":
670 rescale = 0x3000 * cmd.ifm_tensor.quantization.scale_f32
Tim Hall79d07d22020-04-27 18:20:16 +0100671
Fredrik Svedberg620d88c2020-05-19 10:43:01 +0200672 if cmd.ifm_tensor.dtype == DataType.int16:
Charles Xu749d9212020-06-11 12:39:19 +0200673 multiplier = max(1, int(4096 * cmd.ifm_tensor.quantization.scale_f32 + 0.5))
Fredrik Svedberg620d88c2020-05-19 10:43:01 +0200674 rescale *= 3 * multiplier
675
676 rescale_bits = len(bin(round_up_to_int(rescale))) - 2 + 1
Tim Hall79d07d22020-04-27 18:20:16 +0100677 scale, shift = scaling.quantise_pooling_scale(k_height * k_width, rescale_bits)
Fredrik Svedberg620d88c2020-05-19 10:43:01 +0200678
679 if cmd.ifm_tensor.dtype == DataType.int16:
680 scale = (1 << shift) * 3 * multiplier
681 else:
682 scale = int(round_away_zero(scale * rescale))
Jacob Bohlin9fbc4912020-06-29 11:58:50 +0200683 elif fused_quantize:
684 # Quantize op requires different scaling
685 ifm_scale_f64 = np.double(cmd.ifm_tensor.quantization.scale_f32)
686 ofm_scale_f64 = np.double(cmd.ofm_tensor.quantization.scale_f32)
687 scale, shift = scaling.quantise_scale(ifm_scale_f64 / ofm_scale_f64)
Tim Hall79d07d22020-04-27 18:20:16 +0100688 else:
689 # In case avg pool fused with concat or other memory operation, rescaling might be needed.
690 # k_height == k_width == 1 is allways true in this case
691 # Normally the scale is maximised, to get maximum precision, which means that
692 # if rescale != 1, scale need to consider the number of bits needed for rescaling
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200693 if None not in (
694 cmd.ofm_tensor.quantization.scale_f32,
695 cmd.ifm_tensor.quantization.scale_f32,
696 ):
697 rescale = cmd.ifm_tensor.quantization.scale_f32 / cmd.ofm_tensor.quantization.scale_f32
698 rescale_bits = 0
699 if k_height == k_width == 1:
700 if fmf == "ConcatSliceWrite":
701 rounding_mode = rounding.NATURAL
702 if rescale > 1:
703 rescale_bits = len(bin(round_up_to_int(rescale))) - 2 + 1
704 elif rescale < 1:
705 rescale_bits = -(len(bin(round_up_to_int(1 / rescale))) - 2 - 1)
706 scale, shift = scaling.quantise_pooling_scale(k_height * k_width, rescale_bits)
707 scale = int(round_away_zero(scale * rescale))
708 else:
709 scale = 1
710 shift = 0
Tim Hall79d07d22020-04-27 18:20:16 +0100711
712 emit.cmd1_with_offset(cmd1.NPU_SET_OFM_SCALE, scale, shift)
713 # Valid-padded average pool should use the global scale from
714 # NPU_SET_OFM_SCALE register, which is set above.
715 use_global_scale = True
716
717 else: # Convolution
718 assert cmd.weight_tensor.block_traversal != TensorBlockTraversal.Default
Fredrik Svedbergd67c0aa2020-03-30 13:15:28 +0200719 # Reduced precision quantization and natural rounding used for int16
720 if cmd.ifm_tensor.dtype == DataType.int16:
721 rounding_mode = rounding.NATURAL
Louis Verhaardb2fb2122020-06-04 15:51:24 +0200722 stride |= (cur_kernel.dilation.y - 1) << 4
723 stride |= (cur_kernel.dilation.x - 1) << 3
724 emit.cmd0_with_param(
725 cmd0.NPU_SET_KERNEL_HEIGHT_M1, cur_kernel.dilation.y * (cmd.weight_tensor.shape[0] - 1)
726 )
727 emit.cmd0_with_param(
728 cmd0.NPU_SET_KERNEL_WIDTH_M1, cur_kernel.dilation.x * (cmd.weight_tensor.shape[1] - 1)
729 )
Tim Hall79d07d22020-04-27 18:20:16 +0100730 if cmd.weight_tensor.block_traversal == TensorBlockTraversal.PartKernelFirst:
731 # Part-kernel-first weight ordering
732 assert npu_block_type == NpuBlockType.ConvolutionMxN
733 stride |= 1 << 2
734
735 emit.cmd0_with_param(cmd0.NPU_SET_KERNEL_STRIDE, stride)
736
737 elif npu_block_type in set((NpuBlockType.VectorProduct,)):
738 # Vector product is implemented using a 1x1 convolution so need
739 # to setup the appropriate padding and kernel info
740 emit.cmd0_with_param(cmd0.NPU_SET_IFM_PAD_TOP, 0)
741 emit.cmd0_with_param(cmd0.NPU_SET_IFM_PAD_LEFT, 0)
742 emit.cmd0_with_param(cmd0.NPU_SET_IFM_PAD_BOTTOM, 0)
743 emit.cmd0_with_param(cmd0.NPU_SET_IFM_PAD_RIGHT, 0)
744
745 # kernel stride reg = 0 means stride(1,1) + depth first weight
746 # order + dilation(0,0) + kernel_split_size=8
747 emit.cmd0_with_param(cmd0.NPU_SET_KERNEL_STRIDE, 0)
748
749 emit.cmd0_with_param(cmd0.NPU_SET_KERNEL_HEIGHT_M1, 0)
750 emit.cmd0_with_param(cmd0.NPU_SET_KERNEL_WIDTH_M1, 0)
751
752 if npu_block_type in set(
753 (NpuBlockType.ConvolutionMxN, NpuBlockType.ConvolutionDepthWise, NpuBlockType.VectorProduct)
754 ):
755 # Emit Weight base address commands, only maps the area required for
756 # this command's weights from the larger tensor.
757 stream_index = cmd.weight_tensor.compressed_stream_index_from_coord(cmd.weight_box.start_coord)
Tim Hallf7e810a2020-06-25 15:04:31 +0100758 weight_substream_offsets = cmd.weight_tensor.compressed_values_substream_offsets[stream_index]
Jacob Bohlin0b9ca782020-07-09 11:16:30 +0200759 substreams = len(weight_substream_offsets) - 1 # Offset list must terminate with full stream length
Tim Hallf7e810a2020-06-25 15:04:31 +0100760
761 # Extract weight substream offsets and calculate their lengths
762 assert len(weight_substream_offsets) > 1 and (weight_substream_offsets[0] == 0)
Tim Hall79d07d22020-04-27 18:20:16 +0100763 weight_addr = cmd.weight_tensor.address_for_coordinate(cmd.weight_box.start_coord)
Tim Hallf7e810a2020-06-25 15:04:31 +0100764
Tim Hall62316762020-06-25 16:55:02 +0100765 # Set weights sources for active and present cores
Jacob Bohlin0b9ca782020-07-09 11:16:30 +0200766 for core, param in enumerate(
767 [
768 (cmd1.NPU_SET_WEIGHT_BASE, cmd1.NPU_SET_WEIGHT_LENGTH),
769 (cmd1.NPU_SET_WEIGHT1_BASE, cmd1.NPU_SET_WEIGHT1_LENGTH),
770 ]
771 ):
Tim Hall62316762020-06-25 16:55:02 +0100772 if core < substreams:
Jacob Bohlin0b9ca782020-07-09 11:16:30 +0200773 emit.cmd1_with_offset(param[0], weight_addr + weight_substream_offsets[core])
774 emit.cmd1_with_offset(
775 param[1], weight_substream_offsets[core + 1] - weight_substream_offsets[core]
776 )
Tim Hall62316762020-06-25 16:55:02 +0100777 elif core < arch.ncores:
778 emit.cmd1_with_offset(param[0], weight_addr)
779 emit.cmd1_with_offset(param[1], 0)
Tim Hallf7e810a2020-06-25 15:04:31 +0100780
Patrik Gustavssoneca2e952020-05-27 09:15:11 +0200781 weight_region = base_ptr_idx_map[cmd.weight_tensor.mem_type]
Tim Hall79d07d22020-04-27 18:20:16 +0100782 emit.cmd0_with_param(cmd0.NPU_SET_WEIGHT_REGION, weight_region)
Tim Hall79d07d22020-04-27 18:20:16 +0100783
784 # Emit Scale & Bias base address commands, with length matching the amount required by
785 # the weight tensors.
786 if cmd.scale_tensor is not None:
Tim Hallf7e810a2020-06-25 15:04:31 +0100787 scale_substream_offsets = cmd.scale_tensor.compressed_values_substream_offsets[stream_index]
Jacob Bohlin0b9ca782020-07-09 11:16:30 +0200788 substreams = len(scale_substream_offsets) - 1 # Offset list must terminate with full stream length
Tim Hallf7e810a2020-06-25 15:04:31 +0100789
790 # Extract scale substream offsets and calculate their lengths
791 assert len(scale_substream_offsets) > 1 and (scale_substream_offsets[0] == 0)
Jacob Bohlin0b9ca782020-07-09 11:16:30 +0200792 scale_addr = cmd.scale_tensor.address_for_coordinate(cmd.weight_box.start_coord[-1:])
Tim Hallf7e810a2020-06-25 15:04:31 +0100793
Tim Hall62316762020-06-25 16:55:02 +0100794 # Set scale sources for active and present cores
Jacob Bohlin0b9ca782020-07-09 11:16:30 +0200795 for core, param in enumerate(
796 [
797 (cmd1.NPU_SET_SCALE_BASE, cmd1.NPU_SET_SCALE_LENGTH),
798 (cmd1.NPU_SET_SCALE1_BASE, cmd1.NPU_SET_SCALE1_LENGTH),
799 ]
800 ):
Tim Hall62316762020-06-25 16:55:02 +0100801 if core < substreams:
Jacob Bohlin0b9ca782020-07-09 11:16:30 +0200802 emit.cmd1_with_offset(param[0], scale_addr + scale_substream_offsets[core])
803 emit.cmd1_with_offset(
804 param[1], scale_substream_offsets[core + 1] - scale_substream_offsets[core]
805 )
Tim Hall62316762020-06-25 16:55:02 +0100806 elif core < arch.ncores:
807 emit.cmd1_with_offset(param[0], scale_addr)
808 emit.cmd1_with_offset(param[1], 0)
Tim Hallf7e810a2020-06-25 15:04:31 +0100809
Tim Hall79d07d22020-04-27 18:20:16 +0100810 # Emit base address for NPU to access scale & bias data
Patrik Gustavssoneca2e952020-05-27 09:15:11 +0200811 scale_region = base_ptr_idx_map[cmd.scale_tensor.mem_type]
Tim Hall79d07d22020-04-27 18:20:16 +0100812 emit.cmd0_with_param(cmd0.NPU_SET_SCALE_REGION, scale_region)
Tim Hall79d07d22020-04-27 18:20:16 +0100813
814 ofm_quant = cmd.ofm_tensor.quantization
815 ofm_quant_qmin = cmd.ofm_tensor.quantization.quant_min
816 ofm_quant_qmax = cmd.ofm_tensor.quantization.quant_max
817 ifm_min = cmd.ifm_tensor.quantization.min
818 ifm_max = cmd.ifm_tensor.quantization.max
819
820 # Emit commands for any fused activation function
Diego Russoea6111a2020-04-14 18:41:58 +0100821 if faf is None:
Tim Hall79d07d22020-04-27 18:20:16 +0100822 emit.cmd0_with_param(cmd0.NPU_SET_ACTIVATION, activation.NONE)
823 # Even if no activation function, values need to be set to override previous values
824 faf_min = ofm_quant_qmin
825 faf_max = ofm_quant_qmax
826 elif faf == "Relu":
827 emit.cmd0_with_param(cmd0.NPU_SET_ACTIVATION, activation.NONE)
828 faf_min = quantise_float32(0.0, ofm_quant.scale_f32, ofm_quant.zero_point)
829 faf_max = ofm_quant_qmax
830 elif faf == "Relu6":
831 emit.cmd0_with_param(cmd0.NPU_SET_ACTIVATION, activation.NONE)
832 faf_min = quantise_float32(0.0, ofm_quant.scale_f32, ofm_quant.zero_point)
833 faf_max = quantise_float32(6.0, ofm_quant.scale_f32, ofm_quant.zero_point)
834 elif faf == "ReluN1To1":
835 emit.cmd0_with_param(cmd0.NPU_SET_ACTIVATION, activation.NONE)
836 faf_min = quantise_float32(-1.0, ofm_quant.scale_f32, ofm_quant.zero_point)
837 faf_max = quantise_float32(1.0, ofm_quant.scale_f32, ofm_quant.zero_point)
838 elif faf == "Tanh":
839 emit.cmd0_with_param(cmd0.NPU_SET_ACTIVATION, activation.TANH)
Fredrik Svedberg620d88c2020-05-19 10:43:01 +0200840 if primary_op.type in set(("AvgPool", "AvgPoolAct", "ResizeBilinear")):
841 faf_min = quantise_float32(-1.0, ofm_quant.scale_f32, ofm_quant.zero_point)
842 faf_max = quantise_float32(1.0, ofm_quant.scale_f32, ofm_quant.zero_point)
843 else:
844 faf_min = quantise_float32(clamp_tanh(ifm_min), ofm_quant.scale_f32, ofm_quant.zero_point)
845 faf_max = quantise_float32(clamp_tanh(ifm_max), ofm_quant.scale_f32, ofm_quant.zero_point)
Tim Hall79d07d22020-04-27 18:20:16 +0100846 elif faf == "Sigmoid":
847 emit.cmd0_with_param(cmd0.NPU_SET_ACTIVATION, activation.SIGMOID)
Fredrik Svedberg620d88c2020-05-19 10:43:01 +0200848 if primary_op.type in set(("AvgPool", "AvgPoolAct", "ResizeBilinear")):
849 faf_min = quantise_float32(0, ofm_quant.scale_f32, ofm_quant.zero_point)
850 faf_max = quantise_float32(1.0, ofm_quant.scale_f32, ofm_quant.zero_point)
851 else:
852 faf_min = quantise_float32(clamp_sigmoid(ifm_min), ofm_quant.scale_f32, ofm_quant.zero_point)
853 faf_max = quantise_float32(clamp_sigmoid(ifm_max), ofm_quant.scale_f32, ofm_quant.zero_point)
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200854 elif faf == "LUT":
855 lut_index = int(activation.LUT_START.value) + primary_op.attrs.get("lut_index", 0)
856 assert lut_index <= activation.LUT_END.value, "LUT index out of range."
857 emit.cmd0_with_param(cmd0.NPU_SET_ACTIVATION, lut_index)
858 faf_min = ofm_quant_qmin
859 faf_max = ofm_quant_qmax
Tim Hall79d07d22020-04-27 18:20:16 +0100860 else:
861 raise Exception("Unsupported fused_activation_function = " + faf)
862
863 # Activation range needs to be set based upon the quantisation range and the fused activation range
864 emit.cmd0_with_param(cmd0.NPU_SET_ACTIVATION_MIN, max(ofm_quant_qmin, faf_min))
865 emit.cmd0_with_param(cmd0.NPU_SET_ACTIVATION_MAX, min(ofm_quant_qmax, faf_max))
866
867 out_shape = cmd.ofm_box.get_size_shape()
868 if len(out_shape) >= 4:
869 emit.cmd0_with_param(cmd0.NPU_SET_OFM_HEIGHT_M1, out_shape[-3] - 1)
870 else:
871 emit.cmd0_with_param(cmd0.NPU_SET_OFM_HEIGHT_M1, 0)
872 if len(out_shape) >= 2:
873 emit.cmd0_with_param(cmd0.NPU_SET_OFM_WIDTH_M1, out_shape[-2] - 1)
874 else:
875 emit.cmd0_with_param(cmd0.NPU_SET_OFM_WIDTH_M1, 0)
876 emit.cmd0_with_param(cmd0.NPU_SET_OFM_DEPTH_M1, out_shape[-1] - 1)
877
Fredrik Svedberga0c36242020-06-03 15:43:31 +0200878 if npu_block_type in set((NpuBlockType.ConvolutionMxN, NpuBlockType.VectorProduct, NpuBlockType.ReduceSum)):
Tim Hall79d07d22020-04-27 18:20:16 +0100879 in_shape = cmd.ifm_box.get_size_shape()
880 emit.cmd0_with_param(cmd0.NPU_SET_IFM_DEPTH_M1, in_shape[-1] - 1)
881 else:
882 emit.cmd0_with_param(cmd0.NPU_SET_IFM_DEPTH_M1, out_shape[-1] - 1)
883
Jacob Bohlin3c678292020-04-27 10:27:25 +0200884 for tens, box, region_op, ptr_ops, stride_ops, zero_point_op in (
Tim Hall79d07d22020-04-27 18:20:16 +0100885 (
886 cmd.ifm_tensor,
887 cmd.ifm_box,
Jacob Bohlin3c678292020-04-27 10:27:25 +0200888 cmd0.NPU_SET_IFM_REGION,
Tim Hall79d07d22020-04-27 18:20:16 +0100889 (cmd1.NPU_SET_IFM_BASE0, cmd1.NPU_SET_IFM_BASE1, cmd1.NPU_SET_IFM_BASE2, cmd1.NPU_SET_IFM_BASE3),
890 (cmd1.NPU_SET_IFM_STRIDE_C, cmd1.NPU_SET_IFM_STRIDE_Y, cmd1.NPU_SET_IFM_STRIDE_X),
891 cmd0.NPU_SET_IFM_ZERO_POINT,
892 ),
893 (
894 cmd.ifm2_tensor,
895 cmd.ifm2_box,
Jacob Bohlin3c678292020-04-27 10:27:25 +0200896 cmd0.NPU_SET_IFM2_REGION,
Tim Hall79d07d22020-04-27 18:20:16 +0100897 (
898 cmd1.NPU_SET_IFM2_BASE0,
899 cmd1.NPU_SET_IFM2_BASE1,
900 cmd1.NPU_SET_IFM2_BASE2,
901 cmd1.NPU_SET_IFM2_BASE3,
902 ),
903 (cmd1.NPU_SET_IFM2_STRIDE_C, cmd1.NPU_SET_IFM2_STRIDE_Y, cmd1.NPU_SET_IFM2_STRIDE_X),
904 cmd0.NPU_SET_IFM2_ZERO_POINT,
905 ),
906 (
907 cmd.ofm_tensor,
908 cmd.ofm_box,
Jacob Bohlin3c678292020-04-27 10:27:25 +0200909 cmd0.NPU_SET_OFM_REGION,
Tim Hall79d07d22020-04-27 18:20:16 +0100910 (cmd1.NPU_SET_OFM_BASE0, cmd1.NPU_SET_OFM_BASE1, cmd1.NPU_SET_OFM_BASE2, cmd1.NPU_SET_OFM_BASE3),
911 (cmd1.NPU_SET_OFM_STRIDE_C, cmd1.NPU_SET_OFM_STRIDE_Y, cmd1.NPU_SET_OFM_STRIDE_X),
912 cmd0.NPU_SET_OFM_ZERO_POINT,
913 ),
914 ):
915
Diego Russoea6111a2020-04-14 18:41:58 +0100916 if tens is None:
Tim Hall79d07d22020-04-27 18:20:16 +0100917 continue
918
Jacob Bohlin9fbc4912020-06-29 11:58:50 +0200919 need_zero_point = (faf is not None) or (fmf == "ConcatSliceWrite") or fused_quantize
Tim Hall79d07d22020-04-27 18:20:16 +0100920 if (
Dwight Lidman86d49932020-06-04 15:31:56 +0200921 primary_op.type in set(("AvgPool", "AvgPoolAct", "ResizeBilinear")) and not need_zero_point
Diego Russoea6111a2020-04-14 18:41:58 +0100922 ) or tens.quantization is None:
Tim Hall79d07d22020-04-27 18:20:16 +0100923 # Actual integer operation, just set scale to 1 and zero point to 0
924 emit.cmd0_with_param(zero_point_op, 0)
925 else:
926 assert tens.quantization.zero_point is not None, "need an actual zero point set"
Charles Xu9a03fdf2020-07-02 15:12:40 +0200927 if (
928 "resizebilinear" in primary_op.attrs
929 and primary_op.type == "AddAct"
930 and cmd0.NPU_SET_OFM_ZERO_POINT == zero_point_op
931 ):
932 # Force output zero point same as the input zero point
933 # for resizebiliner 1x1 that is converted to add
934 zero_point = cmd.ifm2_tensor.quantization.zero_point
935 else:
936 zero_point = tens.quantization.zero_point
937 emit.cmd0_with_param(zero_point_op, int(zero_point))
Tim Hall79d07d22020-04-27 18:20:16 +0100938
939 if tens.shape == []:
940 # Empty shape, elementwise constant
Louis Verhaardc88a96f2020-06-10 09:04:33 +0200941 ifm2_scalar = tens.quant_values
Tim Hall79d07d22020-04-27 18:20:16 +0100942 assert ifm2_scalar.size == 1
Louis Verhaardc88a96f2020-06-10 09:04:33 +0200943 emit.cmd0_with_param(cmd0.NPU_SET_IFM2_SCALAR, int(ifm2_scalar.item(0)))
Tim Hall79d07d22020-04-27 18:20:16 +0100944 continue
945
946 height_0, height_1, width_0, addresses = tens.addresses_for_rolling_buffer(
947 box.start_coord, box.end_coord
948 )
949 if npu_block_type != NpuBlockType.VectorProduct:
950 if tens == cmd.ifm_tensor:
951 emit.cmd0_with_param(cmd0.NPU_SET_IFM_HEIGHT0_M1, height_0 - 1)
952 emit.cmd0_with_param(cmd0.NPU_SET_IFM_HEIGHT1_M1, height_1 - 1)
953 emit.cmd0_with_param(cmd0.NPU_SET_IFM_WIDTH0_M1, width_0 - 1)
954 elif tens == cmd.ofm_tensor:
955 emit.cmd0_with_param(cmd0.NPU_SET_OFM_HEIGHT0_M1, height_0 - 1)
956 emit.cmd0_with_param(cmd0.NPU_SET_OFM_HEIGHT1_M1, height_1 - 1)
957 emit.cmd0_with_param(cmd0.NPU_SET_OFM_WIDTH0_M1, width_0 - 1)
Louis Verhaard0cf06c72020-05-12 08:31:05 +0200958 if tens == cmd.ifm2_tensor:
Tim Hall79d07d22020-04-27 18:20:16 +0100959 emit.cmd0_with_param(cmd0.NPU_SET_IFM2_HEIGHT0_M1, height_0 - 1)
960 emit.cmd0_with_param(cmd0.NPU_SET_IFM2_HEIGHT1_M1, height_1 - 1)
961 emit.cmd0_with_param(cmd0.NPU_SET_IFM2_WIDTH0_M1, width_0 - 1)
962 else:
963 if len(out_shape) == 2:
964 # TODO: N is put in W-dimension for now
965 # Should be spread over H and W, but then block size selectetion,
966 # and stride calculation should be changed
967 if tens == cmd.ifm_tensor:
968 emit.cmd0_with_param(cmd0.NPU_SET_IFM_WIDTH0_M1, out_shape[-2] - 1)
969 elif tens == cmd.ofm_tensor:
970 emit.cmd0_with_param(cmd0.NPU_SET_OFM_WIDTH0_M1, out_shape[-2] - 1)
971 else:
972 assert False
973
Patrik Gustavssoneca2e952020-05-27 09:15:11 +0200974 emit.cmd0_with_param(region_op, base_ptr_idx_map[tens.mem_type])
Jacob Bohlin3c678292020-04-27 10:27:25 +0200975
Tim Hall79d07d22020-04-27 18:20:16 +0100976 for idx, addr in enumerate(addresses):
977 if addr is None:
978 addresses[idx] = 0
979
980 emit.cmd1_with_offset(ptr_ops[0], addresses[0])
981 emit.cmd1_with_offset(ptr_ops[1], addresses[1])
982 emit.cmd1_with_offset(ptr_ops[2], addresses[2])
983 emit.cmd1_with_offset(ptr_ops[3], addresses[3])
984
985 strides = tens.get_strides()
986 emit.cmd1_with_offset(stride_ops[0], strides[1]) # stride between 16-byte channel blocks (C)
987 emit.cmd1_with_offset(stride_ops[2], strides[3]) # stride between horisontal values (W)
988 emit.cmd1_with_offset(stride_ops[1], strides[2]) # stride between vertical values (H)
989
990 if tens.format == TensorFormat.NHCWB16:
991 # Check that all BasePointer addresses are aligned to 16 bytes
992 assert (int(addresses[0]) % 16) == 0
993 assert (int(addresses[1]) % 16) == 0
994 assert (int(addresses[2]) % 16) == 0
995 assert (int(addresses[3]) % 16) == 0
996
997 ofm_dtype = cmd.ofm_tensor.dtype
998 assert ofm_dtype.type & BaseType.Int
999 prec = 0
1000 if ofm_dtype.size_in_bits() == 8:
1001 prec = 0
1002 elif ofm_dtype.size_in_bits() == 16:
1003 prec = 2
Fredrik Svedberga0c36242020-06-03 15:43:31 +02001004 elif ofm_dtype.size_in_bits() == 32:
1005 prec = 4
Tim Hall79d07d22020-04-27 18:20:16 +01001006 else:
1007 assert 0
1008
1009 if ofm_dtype.type & BaseType.Signed:
1010 prec += 1
1011
1012 if use_global_scale:
1013 # Set global scale bit, as opposed to using per channel scale
1014 prec |= 1 << 8
1015
1016 if cmd.ofm_tensor.format == TensorFormat.NHCWB16:
1017 prec |= 1 << 6
1018
1019 prec |= rounding_mode.value << 14
1020
1021 emit.cmd0_with_param(cmd0.NPU_SET_OFM_PRECISION, prec)
1022
1023 prec = None
1024 weight_bits = 8
1025 if cmd.weight_tensor is not None:
1026 weight_bits = cmd.weight_tensor.dtype.size_in_bits()
1027
1028 ifm_dtype = cmd.ifm_tensor.dtype
1029
1030 assert weight_bits == 8, "Unsupported weight bit depth"
Fredrik Svedberga0c36242020-06-03 15:43:31 +02001031 assert (
1032 ifm_dtype.size_in_bits() in {8, 16}
1033 or ifm_dtype.size_in_bits() == 32
1034 and npu_block_type in (NpuBlockType.ElementWise, NpuBlockType.ReduceSum)
1035 ), "Unsupported ifm bit depth"
Tim Hall79d07d22020-04-27 18:20:16 +01001036
1037 if ifm_dtype.size_in_bits() == 8:
1038 if ifm_dtype.type & BaseType.Signed:
Diqing Zhongfed918b2020-04-27 10:27:34 +02001039 prec = ifm_precision.S8
Tim Hall79d07d22020-04-27 18:20:16 +01001040 else:
Diqing Zhongfed918b2020-04-27 10:27:34 +02001041 prec = ifm_precision.U8
Tim Hall79d07d22020-04-27 18:20:16 +01001042 elif ifm_dtype.size_in_bits() == 16:
1043 if ifm_dtype.type & BaseType.Signed:
Diqing Zhongfed918b2020-04-27 10:27:34 +02001044 prec = ifm_precision.S16
Tim Hall79d07d22020-04-27 18:20:16 +01001045 else:
Diqing Zhongfed918b2020-04-27 10:27:34 +02001046 prec = ifm_precision.U16
Fredrik Svedberga0c36242020-06-03 15:43:31 +02001047 elif ifm_dtype == DataType.int32:
1048 prec = ifm_precision.S32
Tim Hall79d07d22020-04-27 18:20:16 +01001049
1050 ifm_prec = prec.value
1051 ifm2_prec = ifm_prec
1052
1053 if cmd.ifm_tensor.format == TensorFormat.NHCWB16:
1054 ifm_prec |= 1 << 6
1055
1056 ifm_prec |= op_to_scale << 8
1057
1058 emit.cmd0_with_param(cmd0.NPU_SET_IFM_PRECISION, ifm_prec)
1059
1060 if cmd.ifm2_tensor is not None:
1061 if cmd.ifm2_tensor.format == TensorFormat.NHCWB16:
1062 ifm2_prec |= 1 << 6
1063 emit.cmd0_with_param(cmd0.NPU_SET_IFM2_PRECISION, ifm2_prec)
1064
1065 emit_wait_commands(cmd)
1066
1067 # Get op parameters
1068 cur_ifm_block_depth = get_op_ifmofm_block_depth(arch, cmd)
1069 cur_ofm_block = Block(ps.block_config[1], ps.block_config[0], ps.block_config[3])
1070 cur_ofm_rect = get_op_ofm_rect(cmd)
1071 cur_ifm_rect = get_op_ifm_rect(cmd)
Tim Hall79d07d22020-04-27 18:20:16 +01001072 cur_padLT = get_op_padding_lt(cmd)
1073 if (prev_kernel is not None) and (cur_kernel is not None) and has_prev_op_dependency(prev_cmd, cmd):
1074 if cmd.ifm_tensor.shape == prev_cmd.ofm_tensor.shape:
1075 blockdep = arch.calc_block_dep(
1076 prev_ifm_rect,
1077 prev_ofm_rect,
1078 prev_ifm_block_depth,
1079 prev_ofm_block,
1080 prev_kernel,
1081 cur_ifm_rect,
1082 cur_ofm_rect,
1083 cur_ifm_block_depth,
1084 cur_ofm_block,
1085 cur_kernel,
1086 cur_padLT,
1087 )
1088 else:
1089 blockdep = 0
1090 else:
1091 blockdep = ArchitectureFeatures.MAX_BLOCKDEP
1092
1093 # Set between every op (dependent or not)
1094 blockdep = min(blockdep, arch.max_blockdep)
1095 emit.cmd0_with_param(cmd0.NPU_SET_BLOCKDEP, blockdep)
1096 prev_cmd = cmd
1097
1098 if npu_block_type == NpuBlockType.ConvolutionMxN:
1099 emit.cmd_do_operation(cmd0.NPU_OP_CONV)
1100 elif npu_block_type == NpuBlockType.ConvolutionDepthWise:
1101 emit.cmd_do_operation(cmd0.NPU_OP_DEPTHWISE)
1102 elif npu_block_type == NpuBlockType.VectorProduct:
1103 # Vector product is implemented using a 1x1 convolution
1104 emit.cmd_do_operation(cmd0.NPU_OP_CONV)
1105 elif npu_block_type == NpuBlockType.Pooling:
Fredrik Svedberga0c36242020-06-03 15:43:31 +02001106 param = pooling_mode.MAX.value if "Max" in primary_op.type else pooling_mode.AVERAGE.value
Tim Hall79d07d22020-04-27 18:20:16 +01001107 emit.cmd_do_operation(cmd0.NPU_OP_POOL, param=param)
Fredrik Svedberga0c36242020-06-03 15:43:31 +02001108 elif npu_block_type == NpuBlockType.ReduceSum:
1109 emit.cmd_do_operation(cmd0.NPU_OP_POOL, param=pooling_mode.REDUCE_SUM.value)
Tim Hall79d07d22020-04-27 18:20:16 +01001110 elif npu_block_type == NpuBlockType.ElementWise:
1111 param = elementwise_mode_map[primary_op.type]
1112 emit.cmd_do_operation(cmd0.NPU_OP_ELEMENTWISE, param)
1113 else:
1114 print("Warning: Skipping register command stream generation for", ps)
1115
1116 # Fill in final part of command stream:
1117 emit.cmd_do_operation(cmd0.NPU_OP_STOP, param=0xFFFF)
1118
1119 sg.register_command_stream = emit.to_list()
1120 if verbose:
1121 emit.print_cmds()
1122 print("number of commands", len(emit.cmd_stream))
1123 print("command stream length in words", len(sg.register_command_stream))