language
stringclasses
6 values
original_string
stringlengths
25
887k
text
stringlengths
25
887k
Python
def Transpose(data, axes, target=utils.CCE): """ Permute the dimensions of the input data. Args: data (tvm.tensor.Tensor): Tensor. axes (Union[list, tuple]): Elements must be int. The index of each dimensions. Returns: tvm.tensor.Tensor, has the same dtype as data. Supported Platforms: 'Ascend', 'GPU', 'CPU' """ utils.check_supported_target(target) if target != utils.CCE: utils.check_shape(data.shape) utils.check_int_list(axes, "axes") return akg.topi.transpose(data, axes) else: return _transpose_ascend(data, axes)
def Transpose(data, axes, target=utils.CCE): """ Permute the dimensions of the input data. Args: data (tvm.tensor.Tensor): Tensor. axes (Union[list, tuple]): Elements must be int. The index of each dimensions. Returns: tvm.tensor.Tensor, has the same dtype as data. Supported Platforms: 'Ascend', 'GPU', 'CPU' """ utils.check_supported_target(target) if target != utils.CCE: utils.check_shape(data.shape) utils.check_int_list(axes, "axes") return akg.topi.transpose(data, axes) else: return _transpose_ascend(data, axes)
Python
def scatter_add(ref, indices, updates): """ Add ref with updates based on sparse index: indices. Note: updates.shape need equal to indices.shape + ref.shape[1:]. Args: ref (tvm.tensor.Tensor): Tensor of type float16, float32, int8, int32 and uint8. indices (tvm.tensor.Tensor): Tensor of type int32. updates (tvm.tensor.Tensor): Tensor has the same type as ref. Returns: tvm.tensor.Tensor, has the same type and shape as ref. """ shape_ref = get_shape(ref) shape_indices = get_shape(indices) shape_updates = get_shape(updates) utils.check_shape(shape_ref) utils.check_shape(shape_indices) utils.check_shape(shape_updates) utils.ops_dtype_check([ref.dtype, updates.dtype], [utils.DtypeForDavinci.ALL_FLOAT, utils.DtypeForDavinci.INT32]) utils.ops_dtype_check(indices.dtype, utils.DtypeForDavinci.INT32) new_shape_indices = (reduce(lambda x, y: x * y, shape_indices), ) if len(shape_ref) > 1: new_shape_ref = (shape_ref[0], reduce(lambda x, y: x * y, shape_ref[1:])) new_indices = topi.reshape(indices, new_shape_indices) new_updates_shape = (tuple(new_indices.shape) + tuple(new_shape_ref[1:])) new_updates = topi.reshape(updates, new_updates_shape) new_ref = topi.reshape(ref, new_shape_ref) else: new_indices = topi.reshape(indices, new_shape_indices) new_updates_shape = (tuple(new_indices.shape) + tuple(shape_ref[1:])) new_updates = topi.reshape(updates, new_updates_shape) new_ref = ref # 1D case hybrid @script def scatter_add_1d(input, input_indices, input_updates): n, = input.shape idx_len = input_indices.shape[0] for i in range(n): for idx in range(idx_len): if i == input_indices[idx]: input[input_indices[idx]] += input_updates[idx] return input # ND case reshape to 2D's hybrid, now 2D -- 5D are OK @script def scatter_add(input, input_indices, input_updates): n, h = input.shape idx_len = input_indices.shape[0] for i in range(n): for idx in range(idx_len): if i == input_indices[idx]: for j in range(h): input[input_indices[idx], j] += input_updates[idx, j] return input if len(shape_ref) == 1: out = scatter_add_1d(new_ref, new_indices, new_updates) else: out = scatter_add(new_ref, new_indices, new_updates) out = topi.reshape(out, shape_ref) attrs["enable_feature_library"] = True out, binds_info = TensorUtils.inplace_set(ref, out) attrs[utils.BINDS] = binds_info return out, attrs
def scatter_add(ref, indices, updates): """ Add ref with updates based on sparse index: indices. Note: updates.shape need equal to indices.shape + ref.shape[1:]. Args: ref (tvm.tensor.Tensor): Tensor of type float16, float32, int8, int32 and uint8. indices (tvm.tensor.Tensor): Tensor of type int32. updates (tvm.tensor.Tensor): Tensor has the same type as ref. Returns: tvm.tensor.Tensor, has the same type and shape as ref. """ shape_ref = get_shape(ref) shape_indices = get_shape(indices) shape_updates = get_shape(updates) utils.check_shape(shape_ref) utils.check_shape(shape_indices) utils.check_shape(shape_updates) utils.ops_dtype_check([ref.dtype, updates.dtype], [utils.DtypeForDavinci.ALL_FLOAT, utils.DtypeForDavinci.INT32]) utils.ops_dtype_check(indices.dtype, utils.DtypeForDavinci.INT32) new_shape_indices = (reduce(lambda x, y: x * y, shape_indices), ) if len(shape_ref) > 1: new_shape_ref = (shape_ref[0], reduce(lambda x, y: x * y, shape_ref[1:])) new_indices = topi.reshape(indices, new_shape_indices) new_updates_shape = (tuple(new_indices.shape) + tuple(new_shape_ref[1:])) new_updates = topi.reshape(updates, new_updates_shape) new_ref = topi.reshape(ref, new_shape_ref) else: new_indices = topi.reshape(indices, new_shape_indices) new_updates_shape = (tuple(new_indices.shape) + tuple(shape_ref[1:])) new_updates = topi.reshape(updates, new_updates_shape) new_ref = ref # 1D case hybrid @script def scatter_add_1d(input, input_indices, input_updates): n, = input.shape idx_len = input_indices.shape[0] for i in range(n): for idx in range(idx_len): if i == input_indices[idx]: input[input_indices[idx]] += input_updates[idx] return input # ND case reshape to 2D's hybrid, now 2D -- 5D are OK @script def scatter_add(input, input_indices, input_updates): n, h = input.shape idx_len = input_indices.shape[0] for i in range(n): for idx in range(idx_len): if i == input_indices[idx]: for j in range(h): input[input_indices[idx], j] += input_updates[idx, j] return input if len(shape_ref) == 1: out = scatter_add_1d(new_ref, new_indices, new_updates) else: out = scatter_add(new_ref, new_indices, new_updates) out = topi.reshape(out, shape_ref) attrs["enable_feature_library"] = True out, binds_info = TensorUtils.inplace_set(ref, out) attrs[utils.BINDS] = binds_info return out, attrs
Python
def decorate_custompass(self, custom_pass): """decorate given list of custom passes, and return decorated passes""" custom_pass = custom_pass if custom_pass else [] pass_list = [] for idx, x in enumerate(custom_pass): x[1].__name__ = "custom{}_phase{}".format(idx, x[0]) pass_list += [(x[0], self.decorate(x[1]))] return pass_list
def decorate_custompass(self, custom_pass): """decorate given list of custom passes, and return decorated passes""" custom_pass = custom_pass if custom_pass else [] pass_list = [] for idx, x in enumerate(custom_pass): x[1].__name__ = "custom{}_phase{}".format(idx, x[0]) pass_list += [(x[0], self.decorate(x[1]))] return pass_list
Python
def build_config(**kwargs): """Configure the build behavior by setting config variables. Parameters ---------- auto_unroll_max_step: int, default=0 Threshold of number of steps in the loop to be automatically unrolled. This takes inner loop count into consideration. auto_unroll_max_depth: int, default=8 The maximum nested level of loops that can be automatically unrolled. unroll_explicit: bool, default=True Whether explicitly unroll the loop, if set false, the unroll hint will be passed to the CodeGen phase, which may generate pragma unroll hint. Set this to be true if CodeGen support unroll pragma and when we want to be more readable. detect_global_barrier: bool, default=True Whether detect global barrier. partition_const_loop: bool, default=False Whether partition const loop data_alignment: int, optional The alignment of data pointer in bytes. If -1 is passed, the alignment will be set to TVM's internal default. offset_factor: int, default=0 The factor used in default buffer declaration. If specified as 0, offset field is not used. restricted_func: bool, default=True Whether build restricted function. That is each buffer argument to the function are guaranteed not to overlap. This enables more optimization. Corresponds to restricted keyword in C99 double_buffer_split_loop: int, default=2 Whether split the loop with factor. If it is zero, no splitting will happen. It it is bigger than one, the logic will do a split with factor equals the integer and unroll the inner loop. This allows the buffer fetching won't contain condition. add_lower_pass: list of tuple (phase, function(Stmt->Stmt)), default=None phase contains an integer on which optimization pass we apply the pass. Additional lowering passes to be applied before make_api. dump_pass_ir: dump ir of each pass into file idx_passname_ir.cc, default=False Returns ------- config: BuildConfig The build configuration """ node_args = {k: v if k not in kwargs else kwargs[k] for k, v in BuildConfig._node_defaults.items()} config = make.node("BuildConfig", **node_args) if "add_lower_pass" in kwargs: config.add_lower_pass = kwargs["add_lower_pass"] return config
def build_config(**kwargs): """Configure the build behavior by setting config variables. Parameters ---------- auto_unroll_max_step: int, default=0 Threshold of number of steps in the loop to be automatically unrolled. This takes inner loop count into consideration. auto_unroll_max_depth: int, default=8 The maximum nested level of loops that can be automatically unrolled. unroll_explicit: bool, default=True Whether explicitly unroll the loop, if set false, the unroll hint will be passed to the CodeGen phase, which may generate pragma unroll hint. Set this to be true if CodeGen support unroll pragma and when we want to be more readable. detect_global_barrier: bool, default=True Whether detect global barrier. partition_const_loop: bool, default=False Whether partition const loop data_alignment: int, optional The alignment of data pointer in bytes. If -1 is passed, the alignment will be set to TVM's internal default. offset_factor: int, default=0 The factor used in default buffer declaration. If specified as 0, offset field is not used. restricted_func: bool, default=True Whether build restricted function. That is each buffer argument to the function are guaranteed not to overlap. This enables more optimization. Corresponds to restricted keyword in C99 double_buffer_split_loop: int, default=2 Whether split the loop with factor. If it is zero, no splitting will happen. It it is bigger than one, the logic will do a split with factor equals the integer and unroll the inner loop. This allows the buffer fetching won't contain condition. add_lower_pass: list of tuple (phase, function(Stmt->Stmt)), default=None phase contains an integer on which optimization pass we apply the pass. Additional lowering passes to be applied before make_api. dump_pass_ir: dump ir of each pass into file idx_passname_ir.cc, default=False Returns ------- config: BuildConfig The build configuration """ node_args = {k: v if k not in kwargs else kwargs[k] for k, v in BuildConfig._node_defaults.items()} config = make.node("BuildConfig", **node_args) if "add_lower_pass" in kwargs: config.add_lower_pass = kwargs["add_lower_pass"] return config
Python
def lower(sch, args, name="default_function", binds=None, simple_mode=False): """Lowering step before build into target. Parameters ---------- sch : tvm.schedule.Schedule The schedule to be built args : list of Buffer or Tensor or Var The argument lists to the function. name : str, optional The name of result function. binds : dict of :any:`Tensor` to :any:`Buffer`, optional Dictionary that maps the Tensor to Buffer which specified the data layout requirement of the function. By default, a new compact buffer is created for each tensor in the argument. simple_mode : bool, optional Whether only output simple and compact statement, this will skip LoopPartition, api wrapper generation and Unrolling. Returns ------- f : LoweredFunc or Stmt The result function, if with_api_wrapper=False Then the Stmt before make api is returned. """ cfg = current_build_config() add_lower_pass = cfg.add_lower_pass if cfg.add_lower_pass else [] if cfg.dump_pass_ir: add_lower_pass = BuildConfig._dump_ir.decorate_custompass(add_lower_pass) lower_phase0 = [x[1] for x in add_lower_pass if x[0] == 0] lower_phase1 = [x[1] for x in add_lower_pass if x[0] == 1] lower_phase2 = [x[1] for x in add_lower_pass if x[0] == 2] lower_phase3 = [x[1] for x in add_lower_pass if x[0] > 2] # Phase 0 if isinstance(sch, schedule.Schedule): stmt = form_body(sch) for f in lower_phase0: stmt = f(stmt) compact = ir_pass.VerifyCompactBuffer(stmt) binds, arg_list = get_binds(args, compact, binds) # Phase 1 stmt = ir_pass.RewriteForTensorCore(stmt, sch, binds) stmt = ir_pass.StorageFlatten(stmt, binds, 64, cfg.instrument_bound_checkers) stmt = ir_pass.CanonicalSimplify(stmt) for f in lower_phase1: stmt = f(stmt) # Phase 2 if not simple_mode: stmt = ir_pass.LoopPartition(stmt, cfg.partition_const_loop) if cfg.disable_vectorize: stmt = ir_pass.SkipVectorize(stmt) else: stmt = ir_pass.VectorizeLoop(stmt) stmt = ir_pass.InjectVirtualThread(stmt) stmt = ir_pass.InjectDoubleBuffer(stmt, cfg.double_buffer_split_loop, False) stmt = ir_pass.StorageRewrite(stmt) stmt = ir_pass.UnrollLoop( stmt, cfg.auto_unroll_max_step, cfg.auto_unroll_max_depth, cfg.auto_unroll_max_extent, cfg.unroll_explicit) for f in lower_phase2: stmt = f(stmt) # Phase 3 stmt = ir_pass.Simplify(stmt) stmt = ir_pass.RemoveNoOp(stmt) if not cfg.disable_select_rewriting: stmt = ir_pass.RewriteUnsafeSelect(stmt) for f in lower_phase3: stmt = f(stmt) # Instrument BoundCheckers if cfg.instrument_bound_checkers: stmt = ir_pass.InstrumentBoundCheckers(stmt) if simple_mode: return stmt return ir_pass.MakeAPI(stmt, name, arg_list, 0, cfg.restricted_func)
def lower(sch, args, name="default_function", binds=None, simple_mode=False): """Lowering step before build into target. Parameters ---------- sch : tvm.schedule.Schedule The schedule to be built args : list of Buffer or Tensor or Var The argument lists to the function. name : str, optional The name of result function. binds : dict of :any:`Tensor` to :any:`Buffer`, optional Dictionary that maps the Tensor to Buffer which specified the data layout requirement of the function. By default, a new compact buffer is created for each tensor in the argument. simple_mode : bool, optional Whether only output simple and compact statement, this will skip LoopPartition, api wrapper generation and Unrolling. Returns ------- f : LoweredFunc or Stmt The result function, if with_api_wrapper=False Then the Stmt before make api is returned. """ cfg = current_build_config() add_lower_pass = cfg.add_lower_pass if cfg.add_lower_pass else [] if cfg.dump_pass_ir: add_lower_pass = BuildConfig._dump_ir.decorate_custompass(add_lower_pass) lower_phase0 = [x[1] for x in add_lower_pass if x[0] == 0] lower_phase1 = [x[1] for x in add_lower_pass if x[0] == 1] lower_phase2 = [x[1] for x in add_lower_pass if x[0] == 2] lower_phase3 = [x[1] for x in add_lower_pass if x[0] > 2] # Phase 0 if isinstance(sch, schedule.Schedule): stmt = form_body(sch) for f in lower_phase0: stmt = f(stmt) compact = ir_pass.VerifyCompactBuffer(stmt) binds, arg_list = get_binds(args, compact, binds) # Phase 1 stmt = ir_pass.RewriteForTensorCore(stmt, sch, binds) stmt = ir_pass.StorageFlatten(stmt, binds, 64, cfg.instrument_bound_checkers) stmt = ir_pass.CanonicalSimplify(stmt) for f in lower_phase1: stmt = f(stmt) # Phase 2 if not simple_mode: stmt = ir_pass.LoopPartition(stmt, cfg.partition_const_loop) if cfg.disable_vectorize: stmt = ir_pass.SkipVectorize(stmt) else: stmt = ir_pass.VectorizeLoop(stmt) stmt = ir_pass.InjectVirtualThread(stmt) stmt = ir_pass.InjectDoubleBuffer(stmt, cfg.double_buffer_split_loop, False) stmt = ir_pass.StorageRewrite(stmt) stmt = ir_pass.UnrollLoop( stmt, cfg.auto_unroll_max_step, cfg.auto_unroll_max_depth, cfg.auto_unroll_max_extent, cfg.unroll_explicit) for f in lower_phase2: stmt = f(stmt) # Phase 3 stmt = ir_pass.Simplify(stmt) stmt = ir_pass.RemoveNoOp(stmt) if not cfg.disable_select_rewriting: stmt = ir_pass.RewriteUnsafeSelect(stmt) for f in lower_phase3: stmt = f(stmt) # Instrument BoundCheckers if cfg.instrument_bound_checkers: stmt = ir_pass.InstrumentBoundCheckers(stmt) if simple_mode: return stmt return ir_pass.MakeAPI(stmt, name, arg_list, 0, cfg.restricted_func)
Python
def build(inputs, args=None, target=None, target_host=None, name="default_function", binds=None): """Build a function with arguments as signature. Code will be generated for devices coupled with target information. Parameters ---------- inputs : tvm.Schedule, LoweredFunc, or dict of target to LoweredFunc list The schedule to be built args : list of Buffer or Tensor or Var, optional The argument lists to the function. target : str or :any:`tvm.target.Target`, optional The target and option of the compilation. target_host : str or :any:`tvm.target.Target` optional Host compilation target, if target is device. When TVM compiles device specific program such as CUDA, we also need host(CPU) side code to interact with the driver setup the dimensions and parameters correctly. target_host is used to specify the host side codegen target. By default, llvm is used if it is enabled, otherwise a stackvm intepreter is used. name : str, optional The name of result function. binds : dict, optional Dictionary that maps the binding of symbolic buffer to Tensor. By default, a new buffer is created for each tensor in the argument. Returns ------- ret : tvm.module A module that combines both host and device code. Examples ________ There are two typical example uses of this function depending on the type of the argument `inputs`: 1. it is a list of lowered functions: .. code-block:: python n = 2 A = tvm.placeholder((n,), name='A') B = tvm.placeholder((n,), name='B') C = tvm.compute(A.shape, lambda *i: A(*i) + B(*i), name='C') s = tvm.create_schedule(C.op) f = tvm.lower(s, [A, B, C], name="test_add") m = tvm.build(f, target="llvm") 2. it is a dict of compilation target to list of lowered functions: .. code-block:: python n = 2 A = tvm.placeholder((n,), name='A') B = tvm.placeholder((n,), name='B') C = tvm.compute(A.shape, lambda *i: A(*i) + B(*i), name='C') s1 = tvm.create_schedule(C.op) with tvm.target.cuda() as cuda_tgt: s2 = topi.cuda.schedule_injective(cuda_tgt, [C]) f1 = tvm.lower(s1, [A, B, C], name="test_add1") f2 = tvm.lower(s2, [A, B, C], name="test_add2") m = tvm.build({"llvm": [f1], "cuda": [f2]}, target_host="llvm") Note ---- See the note on :any:`tvm.target` on target string format. """ if isinstance(inputs, schedule.Schedule): if args is None: raise ValueError("args must be given for build from schedule") flist = lower(inputs, args, name=name, binds=binds) if isinstance(flist, container.LoweredFunc): flist = [flist] elif isinstance(inputs, container.LoweredFunc): if args: raise ValueError("args must be done when build from LoweredFunc.") flist = [inputs] elif isinstance(inputs, (list, tuple, container.Array)): flist = inputs elif not isinstance(inputs, (dict, container.Map)): raise ValueError("inputs must be Schedule, LoweredFunc, list of " "LoweredFunc, or dict of target to list of " "LoweredFunc.") if not isinstance(inputs, (dict, container.Map)): target = _target.current_target() if target is None else target target = target if target else "llvm" target_flist = {target: flist} else: target_flist = inputs for tar, flist in target_flist.items(): if not isinstance(tar, (str, _target.Target)): raise ValueError("The key of inputs must be str or " "_target.Target when inputs is dict.") fname_set = set() for x in flist: if not isinstance(x, container.LoweredFunc): raise ValueError("inputs must be Schedule, LoweredFunc, list " "of LoweredFunc, or dict of str to list of " "LoweredFunc.") if x.name in fname_set: raise ValueError("Duplicate function name %s" % x.name) fname_set.add(x.name) if not target_host: for tar, _ in target_flist.items(): tar = _target.create(tar) device_type = ndarray.context(tar.target_name, 0).device_type if device_type == ndarray.cpu(0).device_type: target_host = tar break if not target_host: target_host = "llvm" if module.enabled("llvm") else "stackvm" fhost_all = [] device_modules = [] for tar, flist in target_flist.items(): fhost, mdev = _build_for_device(flist, tar, target_host) # Save the current lowered functions of the host and the device module. fhost_all += fhost device_modules.append(mdev) # Generate a unified host module. mhost = codegen.build_module(fhost_all, str(target_host)) # Import all modules. for mdev in device_modules: if mdev: mhost.import_module(mdev) return mhost
def build(inputs, args=None, target=None, target_host=None, name="default_function", binds=None): """Build a function with arguments as signature. Code will be generated for devices coupled with target information. Parameters ---------- inputs : tvm.Schedule, LoweredFunc, or dict of target to LoweredFunc list The schedule to be built args : list of Buffer or Tensor or Var, optional The argument lists to the function. target : str or :any:`tvm.target.Target`, optional The target and option of the compilation. target_host : str or :any:`tvm.target.Target` optional Host compilation target, if target is device. When TVM compiles device specific program such as CUDA, we also need host(CPU) side code to interact with the driver setup the dimensions and parameters correctly. target_host is used to specify the host side codegen target. By default, llvm is used if it is enabled, otherwise a stackvm intepreter is used. name : str, optional The name of result function. binds : dict, optional Dictionary that maps the binding of symbolic buffer to Tensor. By default, a new buffer is created for each tensor in the argument. Returns ------- ret : tvm.module A module that combines both host and device code. Examples ________ There are two typical example uses of this function depending on the type of the argument `inputs`: 1. it is a list of lowered functions: .. code-block:: python n = 2 A = tvm.placeholder((n,), name='A') B = tvm.placeholder((n,), name='B') C = tvm.compute(A.shape, lambda *i: A(*i) + B(*i), name='C') s = tvm.create_schedule(C.op) f = tvm.lower(s, [A, B, C], name="test_add") m = tvm.build(f, target="llvm") 2. it is a dict of compilation target to list of lowered functions: .. code-block:: python n = 2 A = tvm.placeholder((n,), name='A') B = tvm.placeholder((n,), name='B') C = tvm.compute(A.shape, lambda *i: A(*i) + B(*i), name='C') s1 = tvm.create_schedule(C.op) with tvm.target.cuda() as cuda_tgt: s2 = topi.cuda.schedule_injective(cuda_tgt, [C]) f1 = tvm.lower(s1, [A, B, C], name="test_add1") f2 = tvm.lower(s2, [A, B, C], name="test_add2") m = tvm.build({"llvm": [f1], "cuda": [f2]}, target_host="llvm") Note ---- See the note on :any:`tvm.target` on target string format. """ if isinstance(inputs, schedule.Schedule): if args is None: raise ValueError("args must be given for build from schedule") flist = lower(inputs, args, name=name, binds=binds) if isinstance(flist, container.LoweredFunc): flist = [flist] elif isinstance(inputs, container.LoweredFunc): if args: raise ValueError("args must be done when build from LoweredFunc.") flist = [inputs] elif isinstance(inputs, (list, tuple, container.Array)): flist = inputs elif not isinstance(inputs, (dict, container.Map)): raise ValueError("inputs must be Schedule, LoweredFunc, list of " "LoweredFunc, or dict of target to list of " "LoweredFunc.") if not isinstance(inputs, (dict, container.Map)): target = _target.current_target() if target is None else target target = target if target else "llvm" target_flist = {target: flist} else: target_flist = inputs for tar, flist in target_flist.items(): if not isinstance(tar, (str, _target.Target)): raise ValueError("The key of inputs must be str or " "_target.Target when inputs is dict.") fname_set = set() for x in flist: if not isinstance(x, container.LoweredFunc): raise ValueError("inputs must be Schedule, LoweredFunc, list " "of LoweredFunc, or dict of str to list of " "LoweredFunc.") if x.name in fname_set: raise ValueError("Duplicate function name %s" % x.name) fname_set.add(x.name) if not target_host: for tar, _ in target_flist.items(): tar = _target.create(tar) device_type = ndarray.context(tar.target_name, 0).device_type if device_type == ndarray.cpu(0).device_type: target_host = tar break if not target_host: target_host = "llvm" if module.enabled("llvm") else "stackvm" fhost_all = [] device_modules = [] for tar, flist in target_flist.items(): fhost, mdev = _build_for_device(flist, tar, target_host) # Save the current lowered functions of the host and the device module. fhost_all += fhost device_modules.append(mdev) # Generate a unified host module. mhost = codegen.build_module(fhost_all, str(target_host)) # Import all modules. for mdev in device_modules: if mdev: mhost.import_module(mdev) return mhost
Python
def gen_data(dtype1, dtype2, shape1, shape2): """generate valid test data for truncate_div""" input1 = random_gaussian(shape1).astype(dtype1) input2 = random_gaussian(shape2).astype(dtype2) input2 = np.where(input2 == 0, np.ones_like(input2), input2) expect = np.divide(input1.astype("float32"), input2.astype("float32")) if dtype1 in ("int8", "uint8", "int32"): expect = np.trunc(expect).astype(dtype1) output = np.full(expect.shape, np.nan, dtype1) return expect, (input1, input2), output
def gen_data(dtype1, dtype2, shape1, shape2): """generate valid test data for truncate_div""" input1 = random_gaussian(shape1).astype(dtype1) input2 = random_gaussian(shape2).astype(dtype2) input2 = np.where(input2 == 0, np.ones_like(input2), input2) expect = np.divide(input1.astype("float32"), input2.astype("float32")) if dtype1 in ("int8", "uint8", "int32"): expect = np.trunc(expect).astype(dtype1) output = np.full(expect.shape, np.nan, dtype1) return expect, (input1, input2), output
Python
def Atan2(y, x, target=utils.CCE): """ Compute arc tangent of y/x. .. math:: \\arctan2(y, x) = \\arctan(\\frac{y}{x}) Args: y (tvm.tensor.Tensor): Input tensor, only support float16, float32. x (tvm.tensor.Tensor): Input tensor, only support float16, float32. Returns: A tvm.tensor.Tensor as angles in radians. Supported Platforms: 'Ascend' """ utils.elemwise_shape_check(get_shape(y), get_shape(x)) utils.elemwise_dtype_check(y.dtype, x.dtype, utils.DtypeForDavinci.ALL_FLOAT) return _atan2_compute(y, x), {"enable_auto_inline": False}
def Atan2(y, x, target=utils.CCE): """ Compute arc tangent of y/x. .. math:: \\arctan2(y, x) = \\arctan(\\frac{y}{x}) Args: y (tvm.tensor.Tensor): Input tensor, only support float16, float32. x (tvm.tensor.Tensor): Input tensor, only support float16, float32. Returns: A tvm.tensor.Tensor as angles in radians. Supported Platforms: 'Ascend' """ utils.elemwise_shape_check(get_shape(y), get_shape(x)) utils.elemwise_dtype_check(y.dtype, x.dtype, utils.DtypeForDavinci.ALL_FLOAT) return _atan2_compute(y, x), {"enable_auto_inline": False}
Python
def fargmax(x, y): """ Build expression for the index of maximum value among input expressions x and y. Args: x (tvm.expr.Expr): Input expression. y (tvm.expr.Expr): Input expression. Returns: tvm.expr.Expr. The call expression. Examples: >>> n = akg.tvm.var('n') >>> m = akg.tvm.var('m') >>> data = akg.tvm.placeholder((n, m), name='data') >>> k = akg.tvm.reduce_axis((0, m), "k") >>> reducer = akg.tvm.comm_reducer(lambda x,y: akg.fargmax(x, y), lambda t: akg.tvm.min_value(t), name="argmax") >>> res = akg.tvm.compute((n,), lambda *indice: reducer(data(*indice, k), axis=k), name="res") """ return akg.tvm.call_pure_intrin(x.dtype, "fargmax", x, y)
def fargmax(x, y): """ Build expression for the index of maximum value among input expressions x and y. Args: x (tvm.expr.Expr): Input expression. y (tvm.expr.Expr): Input expression. Returns: tvm.expr.Expr. The call expression. Examples: >>> n = akg.tvm.var('n') >>> m = akg.tvm.var('m') >>> data = akg.tvm.placeholder((n, m), name='data') >>> k = akg.tvm.reduce_axis((0, m), "k") >>> reducer = akg.tvm.comm_reducer(lambda x,y: akg.fargmax(x, y), lambda t: akg.tvm.min_value(t), name="argmax") >>> res = akg.tvm.compute((n,), lambda *indice: reducer(data(*indice, k), axis=k), name="res") """ return akg.tvm.call_pure_intrin(x.dtype, "fargmax", x, y)
Python
def fargmin(x, y): """ Build expression for the index of minimum value among input expressions x and y. Args: x (tvm.expr.Expr): Input expression. y (tvm.expr.Expr): Input expression. Returns: tvm.expr.Expr. The call expression. """ return akg.tvm.call_pure_intrin(x.dtype, "fargmin", x, y)
def fargmin(x, y): """ Build expression for the index of minimum value among input expressions x and y. Args: x (tvm.expr.Expr): Input expression. y (tvm.expr.Expr): Input expression. Returns: tvm.expr.Expr. The call expression. """ return akg.tvm.call_pure_intrin(x.dtype, "fargmin", x, y)
Python
def dropout(x, y): """ Build expression with dropout function. Args: x (tvm.expr.Expr): Input expression. y (tvm.expr.Expr): Input expression. Returns: tvm.expr.Expr. The call expression. """ return akg.tvm.call_pure_intrin(y.dtype, "dropout", x, y)
def dropout(x, y): """ Build expression with dropout function. Args: x (tvm.expr.Expr): Input expression. y (tvm.expr.Expr): Input expression. Returns: tvm.expr.Expr. The call expression. """ return akg.tvm.call_pure_intrin(y.dtype, "dropout", x, y)
Python
def iou(x, y): """ Return the intersection over union of x, y box. Args: x (tvm.expr.Expr): Input expression. y (tvm.expr.Expr): Input expression. Returns: tvm.expr.Expr. The call expression. """ return akg.tvm.call_pure_intrin(x.dtype, "iou", x, y)
def iou(x, y): """ Return the intersection over union of x, y box. Args: x (tvm.expr.Expr): Input expression. y (tvm.expr.Expr): Input expression. Returns: tvm.expr.Expr. The call expression. """ return akg.tvm.call_pure_intrin(x.dtype, "iou", x, y)
Python
def nms(x, y, scalar): """ return nonmaximum suppresion result x, y box. Args: x (tvm.expr.Expr): Input argument of reduced tensor. y (tvm.expr.Expr): Input argument. scalar (Union[tvm.expr.Expr, float]): Score threshold of nms. Returns: z : tvm.expr.Expr. The result is store in fp16, each fp16 is a hex number indicating suppresion. """ return akg.tvm.call_pure_intrin(x.dtype, "nms", x, y, scalar)
def nms(x, y, scalar): """ return nonmaximum suppresion result x, y box. Args: x (tvm.expr.Expr): Input argument of reduced tensor. y (tvm.expr.Expr): Input argument. scalar (Union[tvm.expr.Expr, float]): Score threshold of nms. Returns: z : tvm.expr.Expr. The result is store in fp16, each fp16 is a hex number indicating suppresion. """ return akg.tvm.call_pure_intrin(x.dtype, "nms", x, y, scalar)
Python
def topk_sort(dst, src, topk): """ sort the proposal box and return topk result, used when the sort process need partition the sorting loop. Args: dst (tvm.expr.Expr): Input argument. The destination of sort generated by common reducer. src (tvm.expr.Expr): Input argument. Strictly required that the box number can be divisible by 16 and item number is 8. topk (tvm.expr.Expr): Input argument. Constant tvm.expr.Expr indicating the required topk number. Returns: z : tvm.expr.Expr. The result. """ return akg.tvm.call_pure_intrin(src.dtype, "topk_sort", dst, src, topk)
def topk_sort(dst, src, topk): """ sort the proposal box and return topk result, used when the sort process need partition the sorting loop. Args: dst (tvm.expr.Expr): Input argument. The destination of sort generated by common reducer. src (tvm.expr.Expr): Input argument. Strictly required that the box number can be divisible by 16 and item number is 8. topk (tvm.expr.Expr): Input argument. Constant tvm.expr.Expr indicating the required topk number. Returns: z : tvm.expr.Expr. The result. """ return akg.tvm.call_pure_intrin(src.dtype, "topk_sort", dst, src, topk)
Python
def proposal_sort(dst, src, topk): """ sort the proposal box and return topk result. Args: dst (tvm.expr.Expr): Input argument. The destination of sort generated by common reducer. src (tvm.expr.Expr): Input argument. Strictly required that the box number can be divisible by 16 and item number is 8. topk (tvm.expr.Expr): Input argument. Constant tvm.expr.Expr indicating the required topk number. Returns: z : tvm.expr.Expr. The result. """ return akg.tvm.call_pure_intrin(src.dtype, "proposal_sort", dst, src, topk)
def proposal_sort(dst, src, topk): """ sort the proposal box and return topk result. Args: dst (tvm.expr.Expr): Input argument. The destination of sort generated by common reducer. src (tvm.expr.Expr): Input argument. Strictly required that the box number can be divisible by 16 and item number is 8. topk (tvm.expr.Expr): Input argument. Constant tvm.expr.Expr indicating the required topk number. Returns: z : tvm.expr.Expr. The result. """ return akg.tvm.call_pure_intrin(src.dtype, "proposal_sort", dst, src, topk)
Python
def cast_to(data, dtype, f1628_int_flag=False): """ a wrapped cast operations , cast data to the type of dtype Args: data (Tensor): akg.tvm.tensor needs to change dtype. dtype (String): dst dtype need to cast to. f1628_int_flag (bool): before fp16->int8/uint8, the data is all interger or not. default value is False. Returns: tensor : akg.tvm.tensor. """ if isinstance(data, akg.tvm.tensor.Tensor): data_dtype = getattr(data, 'dtype') else: raise RuntimeError("The cast input type must be akg.tvm.tensor") if (data_dtype == "float16") and (dtype == "int32"): fp16_max = akg.tvm.const(32768, dtype="float16") fp16_min = akg.tvm.const(2 ** (-15), dtype="float16") data1 = round_to(data, 0.5, -0.5) new_data = vmuls(data1, fp16_max) tmp2 = vabs(new_data) tmp3 = vadds(tmp2, fp16_min) fp16_res = vmul(new_data, vrec(tmp3)) sign_res = round(fp16_res) floor_data = floor(vabs(data)) res = vmul(floor_data, sign_res) return res if data_dtype == "float16" and dtype in ("int8", "uint8") and not f1628_int_flag: fp16_half = akg.tvm.const(-0.5, dtype="float16") set_is_need_save_dtype() data = vadds(data, fp16_half) if data_dtype == dtype: return data if data_dtype == "float16": tmp = data else: tmp = cast(data, dst_dtype="float16") return cast(tmp, dst_dtype=dtype)
def cast_to(data, dtype, f1628_int_flag=False): """ a wrapped cast operations , cast data to the type of dtype Args: data (Tensor): akg.tvm.tensor needs to change dtype. dtype (String): dst dtype need to cast to. f1628_int_flag (bool): before fp16->int8/uint8, the data is all interger or not. default value is False. Returns: tensor : akg.tvm.tensor. """ if isinstance(data, akg.tvm.tensor.Tensor): data_dtype = getattr(data, 'dtype') else: raise RuntimeError("The cast input type must be akg.tvm.tensor") if (data_dtype == "float16") and (dtype == "int32"): fp16_max = akg.tvm.const(32768, dtype="float16") fp16_min = akg.tvm.const(2 ** (-15), dtype="float16") data1 = round_to(data, 0.5, -0.5) new_data = vmuls(data1, fp16_max) tmp2 = vabs(new_data) tmp3 = vadds(tmp2, fp16_min) fp16_res = vmul(new_data, vrec(tmp3)) sign_res = round(fp16_res) floor_data = floor(vabs(data)) res = vmul(floor_data, sign_res) return res if data_dtype == "float16" and dtype in ("int8", "uint8") and not f1628_int_flag: fp16_half = akg.tvm.const(-0.5, dtype="float16") set_is_need_save_dtype() data = vadds(data, fp16_half) if data_dtype == dtype: return data if data_dtype == "float16": tmp = data else: tmp = cast(data, dst_dtype="float16") return cast(tmp, dst_dtype=dtype)
Python
def auto_cast_of_cast(func, *args, **kwargs): """ auto cast dectorator. Note: Before calling elewise api, check the input tensor is supported by the intr. If not supported, casting the input tensor to supported dtype. Raises: TypeError, If the cast type is not supported. """ intr = func.__name__ save_op_output_dtype(func, *args) supported_types = get_intr_types("Intrinsic_" + intr) if len(args) == 1: raw_tensor = args[0] src_dtype = raw_tensor.dtype temp_tensor = raw_tensor if src_dtype not in supported_types: if "float32" in supported_types and is_cast_support(src_dtype, "float32"): temp_tensor = cast(raw_tensor, "float32") else: temp_tensor = cast(raw_tensor, "float16") return func(temp_tensor) return func(*args, **kwargs)
def auto_cast_of_cast(func, *args, **kwargs): """ auto cast dectorator. Note: Before calling elewise api, check the input tensor is supported by the intr. If not supported, casting the input tensor to supported dtype. Raises: TypeError, If the cast type is not supported. """ intr = func.__name__ save_op_output_dtype(func, *args) supported_types = get_intr_types("Intrinsic_" + intr) if len(args) == 1: raw_tensor = args[0] src_dtype = raw_tensor.dtype temp_tensor = raw_tensor if src_dtype not in supported_types: if "float32" in supported_types and is_cast_support(src_dtype, "float32"): temp_tensor = cast(raw_tensor, "float32") else: temp_tensor = cast(raw_tensor, "float16") return func(temp_tensor) return func(*args, **kwargs)
Python
def ceil(raw_tensor): """ cast tensor from src_type to dst_dtype with ceiling method Args: raw_tensor (tvm.tensor.Tensor): input Returns: tvm.tensor.Tensor, casted tensor """ dst_dtype = "int32" return cast_op(raw_tensor, dst_dtype, "elewise_single_ceil")
def ceil(raw_tensor): """ cast tensor from src_type to dst_dtype with ceiling method Args: raw_tensor (tvm.tensor.Tensor): input Returns: tvm.tensor.Tensor, casted tensor """ dst_dtype = "int32" return cast_op(raw_tensor, dst_dtype, "elewise_single_ceil")
Python
def floor(raw_tensor): """ cast tensor from src_type to dst_dtype with flooring method Args: raw_tensor (tvm.tensor.Tensor): input Returns: tvm.tensor.Tensor, casted tensor """ dst_dtype = "int32" return cast_op(raw_tensor, dst_dtype, "elewise_single_floor")
def floor(raw_tensor): """ cast tensor from src_type to dst_dtype with flooring method Args: raw_tensor (tvm.tensor.Tensor): input Returns: tvm.tensor.Tensor, casted tensor """ dst_dtype = "int32" return cast_op(raw_tensor, dst_dtype, "elewise_single_floor")
Python
def round(raw_tensor): """ cast tensor from src_type to dst_dtype with rounding method Args: raw_tensor (tvm.tensor.Tensor): input Returns: tvm.tensor.Tensor, casted tensor """ dst_dtype = "int32" return cast_op(raw_tensor, dst_dtype, "elewise_single_round")
def round(raw_tensor): """ cast tensor from src_type to dst_dtype with rounding method Args: raw_tensor (tvm.tensor.Tensor): input Returns: tvm.tensor.Tensor, casted tensor """ dst_dtype = "int32" return cast_op(raw_tensor, dst_dtype, "elewise_single_round")
Python
def trunc(raw_tensor): """ cast tensor from src_type to dst_dtype with trunc method Args: raw_tensor (tvm.tensor.Tensor): input Returns: tvm.tensor.Tensor, casted tensor """ dst_dtype = "int32" return cast_op(raw_tensor, dst_dtype, "elewise_single_trunc")
def trunc(raw_tensor): """ cast tensor from src_type to dst_dtype with trunc method Args: raw_tensor (tvm.tensor.Tensor): input Returns: tvm.tensor.Tensor, casted tensor """ dst_dtype = "int32" return cast_op(raw_tensor, dst_dtype, "elewise_single_trunc")
Python
def cast_op(input_tensor, output_dtype, op): """factory method of single elewise operations""" in_tensor = input_tensor shape = shape_to_list(in_tensor.shape) if op == "elewise_single_cast": lambda_func = lambda *indice: in_tensor(*indice).astype(output_dtype) elif op == "elewise_single_round": lambda_func = lambda *indice: akg.tvm.round(in_tensor(*indice)).astype(output_dtype) elif op == "elewise_single_ceil": lambda_func = lambda *indice: akg.tvm.ceil(in_tensor(*indice)).astype(output_dtype) elif op == "elewise_single_floor": lambda_func = lambda *indice: akg.tvm.floor(in_tensor(*indice)).astype(output_dtype) elif op == "elewise_single_trunc": lambda_func = lambda *indice: akg.tvm.trunc(in_tensor(*indice)).astype(output_dtype) else: raise ValueError("operation %s not support yet" % op) name = op.split("_")[-1] + "_" + str(name_index[0]) name_index[0] += 1 with akg.tvm.tag_scope(op): tmp = akg.tvm.compute(shape, lambda_func, name=name) return tmp
def cast_op(input_tensor, output_dtype, op): """factory method of single elewise operations""" in_tensor = input_tensor shape = shape_to_list(in_tensor.shape) if op == "elewise_single_cast": lambda_func = lambda *indice: in_tensor(*indice).astype(output_dtype) elif op == "elewise_single_round": lambda_func = lambda *indice: akg.tvm.round(in_tensor(*indice)).astype(output_dtype) elif op == "elewise_single_ceil": lambda_func = lambda *indice: akg.tvm.ceil(in_tensor(*indice)).astype(output_dtype) elif op == "elewise_single_floor": lambda_func = lambda *indice: akg.tvm.floor(in_tensor(*indice)).astype(output_dtype) elif op == "elewise_single_trunc": lambda_func = lambda *indice: akg.tvm.trunc(in_tensor(*indice)).astype(output_dtype) else: raise ValueError("operation %s not support yet" % op) name = op.split("_")[-1] + "_" + str(name_index[0]) name_index[0] += 1 with akg.tvm.tag_scope(op): tmp = akg.tvm.compute(shape, lambda_func, name=name) return tmp
Python
def Neg(data, target=utils.CCE): """ Computes negative value of input tensor. Args: data(tvm.tensor.Tensor): Tensor of type float16, float32, int32. Returns: tvm.tensor.Tensor of same type and shape as input tensor data. Supported Platforms: 'Ascend', 'GPU', 'CPU' """ utils.check_supported_target(target) utils.check_shape(data.shape) if target == utils.CCE: data_type = data.dtype utils.ops_dtype_check(data_type, [utils.DtypeForDavinci.ALL_FLOAT, utils.DtypeForDavinci.INT32]) pone = akg.tvm.const(-1.0, dtype=data_type) res = akg.lang.ascend.vmuls(data, pone) if data_type == "int32": res = akg.topi.cast(res, "int32") else: res = akg.topi.negative(data) return res
def Neg(data, target=utils.CCE): """ Computes negative value of input tensor. Args: data(tvm.tensor.Tensor): Tensor of type float16, float32, int32. Returns: tvm.tensor.Tensor of same type and shape as input tensor data. Supported Platforms: 'Ascend', 'GPU', 'CPU' """ utils.check_supported_target(target) utils.check_shape(data.shape) if target == utils.CCE: data_type = data.dtype utils.ops_dtype_check(data_type, [utils.DtypeForDavinci.ALL_FLOAT, utils.DtypeForDavinci.INT32]) pone = akg.tvm.const(-1.0, dtype=data_type) res = akg.lang.ascend.vmuls(data, pone) if data_type == "int32": res = akg.topi.cast(res, "int32") else: res = akg.topi.negative(data) return res
Python
def argminmax_tiling_strategy(out_shape, axis): """Custom tiling strategy for argminmax op.""" strategy = list() # when reduce axis is one, we do not need any strategy if out_shape[axis] == 1: return strategy # if reduce first axis, it will transpose to last axis # so here we adapt to this change if axis == 0: temp = out_shape[0] out_shape = out_shape[1:] out_shape.append(temp) axis = len(out_shape) - 1 # eliminate single axis, which will automatically disappear in halide ir # and adjust axis if it is influenced shrink = list() for i, shp in enumerate(out_shape): if shp == 1: if i < axis: axis -= 1 else: shrink.append(shp) for i, _ in enumerate(shrink): if i == axis: strategy.append(ct_util.create_constraint_on_axis( values="FULL", constraints=ct_util.TileConstraint.MAX, axis=i)[0]) else: strategy.append(ct_util.create_constraint_on_axis( values=1, constraints=ct_util.TileConstraint.FACTOR, axis=i)[0]) return strategy
def argminmax_tiling_strategy(out_shape, axis): """Custom tiling strategy for argminmax op.""" strategy = list() # when reduce axis is one, we do not need any strategy if out_shape[axis] == 1: return strategy # if reduce first axis, it will transpose to last axis # so here we adapt to this change if axis == 0: temp = out_shape[0] out_shape = out_shape[1:] out_shape.append(temp) axis = len(out_shape) - 1 # eliminate single axis, which will automatically disappear in halide ir # and adjust axis if it is influenced shrink = list() for i, shp in enumerate(out_shape): if shp == 1: if i < axis: axis -= 1 else: shrink.append(shp) for i, _ in enumerate(shrink): if i == axis: strategy.append(ct_util.create_constraint_on_axis( values="FULL", constraints=ct_util.TileConstraint.MAX, axis=i)[0]) else: strategy.append(ct_util.create_constraint_on_axis( values=1, constraints=ct_util.TileConstraint.FACTOR, axis=i)[0]) return strategy
Python
def common(data, axis, method="min"): """ Returns the index with the max or min value across axes of a tensor. Note: method can be "max" or "min" to get argmax or argmin. Args: data (tvm.tensor.Tensor): Tensor of type float16, float32, int8, int32. axis (int): Describe the axis of input tensor. method (str): Can be "max" or "min". Returns: tvm.tensor.Tensor, has type of int32. """ shape = get_shape(data) dtype = data.dtype utils.ops_dtype_check(data.dtype, [utils.DtypeForDavinci.ALL_FLOAT, utils.DtypeForDavinci.ALL_INT]) utils.reduce_axis_check(shape, axis) real_axis = refine_reduce_axis(shape, axis)[0] out_shape = get_reduce_out_shape(shape, axis=axis) attr_map = {} if shape_is_dynamic(data): attr_map["dynamic_shape"] = set_dynamic_shape_limit_for_tensor(data, 4096, real_axis) if dtype != "float16": data = akg.topi.cast(data, "float16") k = akg.tvm.reduce_axis((0, data.shape[real_axis]), "k") if axis in (len(shape) - 1, -1): if method == "min": reducer = akg.tvm.comm_reducer( lambda x, y: dav.fargmin(x, y), lambda t: akg.tvm.max_value(t)) elif method == "max": reducer = akg.tvm.comm_reducer( lambda x, y: dav.fargmax(x, y), lambda t: akg.tvm.min_value(t)) else: raise ValueError("not support " + method) if len(data.shape) == 1: res = akg.tvm.compute((1,), lambda i: reducer(data[k], axis=k)) else: res = akg.tvm.compute(out_shape, lambda *indice: reducer(data(*indice, k), axis=k)) res = akg.tvm.compute(out_shape, lambda *indice: res(*indice).astype("int32"), "argred_output") elif axis in (0, -len(shape)): tmp_idx = akg.tvm.compute(shape[1:], lambda *indice: akg.tvm.const(0.0, "float16"), name='tmp_index') local_data = akg.tvm.compute(shape[1:], lambda *indice: data(0, *indice), name="tmp_data") for idx in range(shape[axis] - 1): if method == 'min': tmp_idx = akg.tvm.compute( shape[1:], lambda *indice, ite_idx=idx: akg.tvm.expr.Select( local_data(*indice) > data(ite_idx + 1, *indice), akg.tvm.const(ite_idx + 1, "float16"), tmp_idx(*indice) )) local_data = akg.tvm.compute( shape[1:], lambda *indice, ite_idx=idx: akg.tvm.expr.Select( local_data(*indice) > data(ite_idx + 1, *indice), data(ite_idx + 1, *indice), local_data(*indice) )) elif method == "max": tmp_idx = akg.tvm.compute( shape[1:], lambda *indice, ite_idx=idx: akg.tvm.expr.Select( local_data(*indice) < data(ite_idx + 1, *indice), akg.tvm.const(ite_idx + 1, "float16"), tmp_idx(*indice) )) local_data = akg.tvm.compute( shape[1:], lambda *indice, ite_idx=idx: akg.tvm.expr.Select( local_data(*indice) < data(ite_idx + 1, *indice), data(ite_idx + 1, *indice), local_data(*indice) )) else: raise ValueError("not support " + method) res = akg.tvm.compute(out_shape, lambda *indice: tmp_idx(*indice).astype("int32"), "cast1") else: raise ValueError("Argmax only support first axis and is last axis now!") lager = out_shape if len(out_shape) > len(shape) else shape strategy = argminmax_tiling_strategy(lager, real_axis) if strategy: attr_map["custom_tiling"] = strategy return res, attr_map
def common(data, axis, method="min"): """ Returns the index with the max or min value across axes of a tensor. Note: method can be "max" or "min" to get argmax or argmin. Args: data (tvm.tensor.Tensor): Tensor of type float16, float32, int8, int32. axis (int): Describe the axis of input tensor. method (str): Can be "max" or "min". Returns: tvm.tensor.Tensor, has type of int32. """ shape = get_shape(data) dtype = data.dtype utils.ops_dtype_check(data.dtype, [utils.DtypeForDavinci.ALL_FLOAT, utils.DtypeForDavinci.ALL_INT]) utils.reduce_axis_check(shape, axis) real_axis = refine_reduce_axis(shape, axis)[0] out_shape = get_reduce_out_shape(shape, axis=axis) attr_map = {} if shape_is_dynamic(data): attr_map["dynamic_shape"] = set_dynamic_shape_limit_for_tensor(data, 4096, real_axis) if dtype != "float16": data = akg.topi.cast(data, "float16") k = akg.tvm.reduce_axis((0, data.shape[real_axis]), "k") if axis in (len(shape) - 1, -1): if method == "min": reducer = akg.tvm.comm_reducer( lambda x, y: dav.fargmin(x, y), lambda t: akg.tvm.max_value(t)) elif method == "max": reducer = akg.tvm.comm_reducer( lambda x, y: dav.fargmax(x, y), lambda t: akg.tvm.min_value(t)) else: raise ValueError("not support " + method) if len(data.shape) == 1: res = akg.tvm.compute((1,), lambda i: reducer(data[k], axis=k)) else: res = akg.tvm.compute(out_shape, lambda *indice: reducer(data(*indice, k), axis=k)) res = akg.tvm.compute(out_shape, lambda *indice: res(*indice).astype("int32"), "argred_output") elif axis in (0, -len(shape)): tmp_idx = akg.tvm.compute(shape[1:], lambda *indice: akg.tvm.const(0.0, "float16"), name='tmp_index') local_data = akg.tvm.compute(shape[1:], lambda *indice: data(0, *indice), name="tmp_data") for idx in range(shape[axis] - 1): if method == 'min': tmp_idx = akg.tvm.compute( shape[1:], lambda *indice, ite_idx=idx: akg.tvm.expr.Select( local_data(*indice) > data(ite_idx + 1, *indice), akg.tvm.const(ite_idx + 1, "float16"), tmp_idx(*indice) )) local_data = akg.tvm.compute( shape[1:], lambda *indice, ite_idx=idx: akg.tvm.expr.Select( local_data(*indice) > data(ite_idx + 1, *indice), data(ite_idx + 1, *indice), local_data(*indice) )) elif method == "max": tmp_idx = akg.tvm.compute( shape[1:], lambda *indice, ite_idx=idx: akg.tvm.expr.Select( local_data(*indice) < data(ite_idx + 1, *indice), akg.tvm.const(ite_idx + 1, "float16"), tmp_idx(*indice) )) local_data = akg.tvm.compute( shape[1:], lambda *indice, ite_idx=idx: akg.tvm.expr.Select( local_data(*indice) < data(ite_idx + 1, *indice), data(ite_idx + 1, *indice), local_data(*indice) )) else: raise ValueError("not support " + method) res = akg.tvm.compute(out_shape, lambda *indice: tmp_idx(*indice).astype("int32"), "cast1") else: raise ValueError("Argmax only support first axis and is last axis now!") lager = out_shape if len(out_shape) > len(shape) else shape strategy = argminmax_tiling_strategy(lager, real_axis) if strategy: attr_map["custom_tiling"] = strategy return res, attr_map
Python
def apply_gradient_descent(var, alpha, delta, target=utils.CCE): """ Update var by subtracting alpha * delta from it. .. math:: var_{t} = var_{t-1} - \\alpha \\delta Args: var (tvm.tensor.Tensor): Input var of dtype float16, float32. alpha (tvm.tensor.Tensor): A scalar tensor of same type as input var. delta (tvm.tensor.Tensor): A tensor of same shape and dtype as input var. Returns: tvm.tensor.Tensor, Updated var. """ # check dtypes utils.ops_dtype_check(var.dtype, utils.DtypeForDavinci.ALL_FLOAT) for i in (alpha, delta): utils.elemwise_dtype_check(var.dtype, i.dtype) # check shapes utils.elemwise_shape_check(var.shape, delta.shape) if tuple(get_shape(alpha)) != (1,): raise RuntimeError("input alpha only support scalar tensor.") # compute out_var = _apply_gradient_descent_compute(var, alpha, delta) # reuse var out_var, binds_info = TensorUtils.inplace_set(var, out_var, "var_buf") attrs = {utils.BINDS: binds_info} return out_var, attrs
def apply_gradient_descent(var, alpha, delta, target=utils.CCE): """ Update var by subtracting alpha * delta from it. .. math:: var_{t} = var_{t-1} - \\alpha \\delta Args: var (tvm.tensor.Tensor): Input var of dtype float16, float32. alpha (tvm.tensor.Tensor): A scalar tensor of same type as input var. delta (tvm.tensor.Tensor): A tensor of same shape and dtype as input var. Returns: tvm.tensor.Tensor, Updated var. """ # check dtypes utils.ops_dtype_check(var.dtype, utils.DtypeForDavinci.ALL_FLOAT) for i in (alpha, delta): utils.elemwise_dtype_check(var.dtype, i.dtype) # check shapes utils.elemwise_shape_check(var.shape, delta.shape) if tuple(get_shape(alpha)) != (1,): raise RuntimeError("input alpha only support scalar tensor.") # compute out_var = _apply_gradient_descent_compute(var, alpha, delta) # reuse var out_var, binds_info = TensorUtils.inplace_set(var, out_var, "var_buf") attrs = {utils.BINDS: binds_info} return out_var, attrs
Python
def _get_center_coordinates_and_sizes_vector(box_data): """Computes the center coordinates, height and width of the boxes. Returns: a list of 4 1-D tensors [ycenter, xcenter, height, width]. """ ymin, xmin, ymax, xmax = [np.squeeze(i) for i in np.split(box_data, 4, 0)] width = np.subtract(xmax, xmin) height = np.subtract(ymax, ymin) ycenter = np.add(ymin, np.multiply(height, 0.5)) xcenter = np.add(xmin, np.multiply(width, 0.5)) return ycenter, xcenter, height, width
def _get_center_coordinates_and_sizes_vector(box_data): """Computes the center coordinates, height and width of the boxes. Returns: a list of 4 1-D tensors [ycenter, xcenter, height, width]. """ ymin, xmin, ymax, xmax = [np.squeeze(i) for i in np.split(box_data, 4, 0)] width = np.subtract(xmax, xmin) height = np.subtract(ymax, ymin) ycenter = np.add(ymin, np.multiply(height, 0.5)) xcenter = np.add(xmin, np.multiply(width, 0.5)) return ycenter, xcenter, height, width
Python
def refine_shape(shape, reduce_axis=None): """ Refine shape to drop 1 in shape according to reduce axis. Note: if input is just shape, result is shape, and if inputs are shape and axis, result is a tuple of (shape, axis). Args: shape : shape of data reduce_axis : list, tuple or int axis want to reduce keepdims: if keepdims = True, we should not refine the shape Returns: shape (list): refined shape. reduce_axis (list): if input parameters send reduce axis, this will be the output. if all the reduce axis is illegal like the length of reduce axis is 1, a empty list([]) will be returned. """ def _refine_shape_no_reduce(): refined = [shp for _, shp in enumerate(shape) if shp > 1] if not refined: refined = [1] return refined if reduce_axis is not None: res_reduce_axis = sorted(refine_reduce_axis(shape, reduce_axis)) if not res_reduce_axis: return _refine_shape_no_reduce(), [] res_shape = shape[:] refined_shape = [] count = 0 for i in res_shape: if i > 1: refined_shape.append(i) count += 1 else: for j, axs in enumerate(res_reduce_axis): if axs > count: res_reduce_axis[j] -= 1 return refined_shape, res_reduce_axis return _refine_shape_no_reduce()
def refine_shape(shape, reduce_axis=None): """ Refine shape to drop 1 in shape according to reduce axis. Note: if input is just shape, result is shape, and if inputs are shape and axis, result is a tuple of (shape, axis). Args: shape : shape of data reduce_axis : list, tuple or int axis want to reduce keepdims: if keepdims = True, we should not refine the shape Returns: shape (list): refined shape. reduce_axis (list): if input parameters send reduce axis, this will be the output. if all the reduce axis is illegal like the length of reduce axis is 1, a empty list([]) will be returned. """ def _refine_shape_no_reduce(): refined = [shp for _, shp in enumerate(shape) if shp > 1] if not refined: refined = [1] return refined if reduce_axis is not None: res_reduce_axis = sorted(refine_reduce_axis(shape, reduce_axis)) if not res_reduce_axis: return _refine_shape_no_reduce(), [] res_shape = shape[:] refined_shape = [] count = 0 for i in res_shape: if i > 1: refined_shape.append(i) count += 1 else: for j, axs in enumerate(res_reduce_axis): if axs > count: res_reduce_axis[j] -= 1 return refined_shape, res_reduce_axis return _refine_shape_no_reduce()
Python
def tvm_shape_to_list(tvm_shape): """translate akg.tvm.shape to list type in python.""" py_shape = [] for i in tvm_shape: if isinstance(i, akg.tvm.expr.Var): py_shape.append(i) else: py_shape.append(i.value) return py_shape
def tvm_shape_to_list(tvm_shape): """translate akg.tvm.shape to list type in python.""" py_shape = [] for i in tvm_shape: if isinstance(i, akg.tvm.expr.Var): py_shape.append(i) else: py_shape.append(i.value) return py_shape
Python
def tvm_array_to_list(tvm_array): """translate akg.tvm.array to list type in python.""" tensor_list = [] for i in tvm_array: if isinstance(i, akg.tvm.tensor.Tensor): tensor_list.append(i) else: raise ValueError("Only surpport akg.tvm.tensor.Tensor.") return tensor_list
def tvm_array_to_list(tvm_array): """translate akg.tvm.array to list type in python.""" tensor_list = [] for i in tvm_array: if isinstance(i, akg.tvm.tensor.Tensor): tensor_list.append(i) else: raise ValueError("Only surpport akg.tvm.tensor.Tensor.") return tensor_list
Python
def convert_to_list(something, convert_all=True): """convert other types to string.""" out = [] if isinstance(something, (list, tuple)): for x in something: out.append(convert_to_list(x, convert_all=False)) else: if convert_all: out.append(something) else: out = something return out
def convert_to_list(something, convert_all=True): """convert other types to string.""" out = [] if isinstance(something, (list, tuple)): for x in something: out.append(convert_to_list(x, convert_all=False)) else: if convert_all: out.append(something) else: out = something return out
Python
def to_tvm_nd_array(data, ctx=None): """convert other types to tvm nd array with specified context""" if ctx is None: ctx = akg.tvm.context("cuda", 0) if isinstance(data, (list, tuple)): return [akg.tvm.nd.array(d, ctx) for d in data] return akg.tvm.nd.array(data, ctx)
def to_tvm_nd_array(data, ctx=None): """convert other types to tvm nd array with specified context""" if ctx is None: ctx = akg.tvm.context("cuda", 0) if isinstance(data, (list, tuple)): return [akg.tvm.nd.array(d, ctx) for d in data] return akg.tvm.nd.array(data, ctx)
Python
def softplus_grad_compute(input_gradients, input_features): """compute for calculations of softplus gradients""" shape_dy = get_shape(input_gradients) shape_x = get_shape(input_features) dtype = input_gradients.dtype if list(shape_dy) != list(shape_x): shape_dy, shape_x, shape_max = produce_shapes(shape_dy, shape_x) input_gradients = akg.lang.ascend.broadcast( input_gradients, shape_max, dtype) input_features = akg.lang.ascend.broadcast( input_features, shape_max, dtype) else: shape_max = shape_dy if dtype != "float32": input_gradients = akg.lang.ascend.cast_to(input_gradients, "float32") input_features = akg.lang.ascend.cast_to( input_features, "float16" if product_is_mini() else "float32") data_exp_tmp = akg.lang.ascend.vexp(input_features) data_add_tmp = akg.lang.ascend.vadds(data_exp_tmp, SCALAR_ONE) data_div_tmp = Divide(data_exp_tmp, data_add_tmp, target="cce") res_tmp = akg.lang.ascend.vmul(input_gradients, data_div_tmp) if dtype == "float16": res = akg.lang.ascend.cast_to(res_tmp, "float16") elif dtype == "int32" or dtype == "int8" or dtype == "uint8": data_zero = akg.lang.ascend.broadcast( tvm.const(0, "float16"), shape_max, "float16") res_min = akg.lang.ascend.vmin(res_tmp, data_zero) res_max = akg.lang.ascend.vmax(res_tmp, data_zero) res_max_int = akg.lang.ascend.floor(res_max) res_min_int = akg.lang.ascend.ceil(res_min) res = akg.lang.ascend.vadd(res_max_int, res_min_int) else: res = res_tmp if dtype == "int8": res = akg.lang.ascend.cast_to(res, "int8") elif dtype == "uint8": res = akg.lang.ascend.cast_to(res, "uint8") return res
def softplus_grad_compute(input_gradients, input_features): """compute for calculations of softplus gradients""" shape_dy = get_shape(input_gradients) shape_x = get_shape(input_features) dtype = input_gradients.dtype if list(shape_dy) != list(shape_x): shape_dy, shape_x, shape_max = produce_shapes(shape_dy, shape_x) input_gradients = akg.lang.ascend.broadcast( input_gradients, shape_max, dtype) input_features = akg.lang.ascend.broadcast( input_features, shape_max, dtype) else: shape_max = shape_dy if dtype != "float32": input_gradients = akg.lang.ascend.cast_to(input_gradients, "float32") input_features = akg.lang.ascend.cast_to( input_features, "float16" if product_is_mini() else "float32") data_exp_tmp = akg.lang.ascend.vexp(input_features) data_add_tmp = akg.lang.ascend.vadds(data_exp_tmp, SCALAR_ONE) data_div_tmp = Divide(data_exp_tmp, data_add_tmp, target="cce") res_tmp = akg.lang.ascend.vmul(input_gradients, data_div_tmp) if dtype == "float16": res = akg.lang.ascend.cast_to(res_tmp, "float16") elif dtype == "int32" or dtype == "int8" or dtype == "uint8": data_zero = akg.lang.ascend.broadcast( tvm.const(0, "float16"), shape_max, "float16") res_min = akg.lang.ascend.vmin(res_tmp, data_zero) res_max = akg.lang.ascend.vmax(res_tmp, data_zero) res_max_int = akg.lang.ascend.floor(res_max) res_min_int = akg.lang.ascend.ceil(res_min) res = akg.lang.ascend.vadd(res_max_int, res_min_int) else: res = res_tmp if dtype == "int8": res = akg.lang.ascend.cast_to(res, "int8") elif dtype == "uint8": res = akg.lang.ascend.cast_to(res, "uint8") return res
Python
def softplus_grad(data_dy, data_x): """ Computes softplus gradients for a softplus operation. .. math:: dx = \\dfrac{dy * e^x}{1 + e^x} Notes: Some value of result will be one less while dtype is "uint8". Args: data_dy (tvm.tensor.Tensor): The backpropagated gradients to the corresponding softplus operation. data_x (tvm.tensor.Tensor): The input_features passed as input to the corresponding softplus operation. source data type support "float16", "float32", "int32", "int8", "uint8". Returns: tvm.tensor.Tensor as gradients of data_x. """ shape_dy = get_shape(data_dy) dtype_dy = data_dy.dtype shape_x = get_shape(data_x) dtype_x = data_x.dtype if dtype_dy != dtype_x: raise RuntimeError( "type of dy and type of x must be same, \ while the types are different") else: dtype = dtype_dy utils.check_shape(shape_dy) utils.check_shape(shape_x) utils.ops_dtype_check( dtype, (utils.DtypeForDavinci.FLOAT16, utils.DtypeForDavinci.FLOAT32, utils.DtypeForDavinci.INT32, utils.DtypeForDavinci.INT8, utils.DtypeForDavinci.UINT8 ) if not product_is_mini() else \ (utils.DtypeForDavinci.FLOAT16, utils.DtypeForDavinci.FLOAT32)) return softplus_grad_compute(data_dy, data_x)
def softplus_grad(data_dy, data_x): """ Computes softplus gradients for a softplus operation. .. math:: dx = \\dfrac{dy * e^x}{1 + e^x} Notes: Some value of result will be one less while dtype is "uint8". Args: data_dy (tvm.tensor.Tensor): The backpropagated gradients to the corresponding softplus operation. data_x (tvm.tensor.Tensor): The input_features passed as input to the corresponding softplus operation. source data type support "float16", "float32", "int32", "int8", "uint8". Returns: tvm.tensor.Tensor as gradients of data_x. """ shape_dy = get_shape(data_dy) dtype_dy = data_dy.dtype shape_x = get_shape(data_x) dtype_x = data_x.dtype if dtype_dy != dtype_x: raise RuntimeError( "type of dy and type of x must be same, \ while the types are different") else: dtype = dtype_dy utils.check_shape(shape_dy) utils.check_shape(shape_x) utils.ops_dtype_check( dtype, (utils.DtypeForDavinci.FLOAT16, utils.DtypeForDavinci.FLOAT32, utils.DtypeForDavinci.INT32, utils.DtypeForDavinci.INT8, utils.DtypeForDavinci.UINT8 ) if not product_is_mini() else \ (utils.DtypeForDavinci.FLOAT16, utils.DtypeForDavinci.FLOAT32)) return softplus_grad_compute(data_dy, data_x)
Python
def _check_params(shape, num, axis, tensor_format, dtype): """ Check the parameters including shape, num, axis, format, dtype. Args: shape (tuple): the shape of tensor num (int): the length of the dim axis axis (int): axis of unapck tensor_format (str): the data format of input dtype (str): the data type Returns: None """ utils.check_shape(shape) # check format format_list = ("ND", "NHWC", "NCHW", "HWCN") if tensor_format == "NC1HWC0": if len(shape) != 5: raise RuntimeError("NC1HWC0 shape length should be equal to 5") # index list of H W axis. suporrted_list = (-5, -3, -2, 0, 2, 3) if axis not in suporrted_list: raise RuntimeError("NC1HWC0 supports unpack of N H W axis") else: if tensor_format not in format_list: raise RuntimeError("Format supports ND,NCHW,NHWC,HWCN and NC1HWC0") # check axis value if axis < -len(shape) or axis >= len(shape): raise RuntimeError("axis= %d not in the union of [%d, %d) " % (axis, -len(shape), len(shape))) # check num value if num is None: num = shape[axis] if num is None: raise RuntimeError("Cannot infer num value from shape %s" % shape) if num != shape[axis]: raise RuntimeError("Num shuld be equal to length of dim axis %d" % shape[axis]) # The maximum size of functional arguments is 1024B. # 1 param takes 8 bytes, needs Multiple output param and 1 input param, # so the maximum size of output is 127 = 1024 // 8 - 1. if num > 127: raise RuntimeError("Exceeds stack holding the parameters, " "maximum is 127 but get %d." % num) utils.ops_dtype_check( dtype, ( utils.DtypeForDavinci.INT8, utils.DtypeForDavinci.INT16, utils.DtypeForDavinci.INT32, utils.DtypeForDavinci.INT64, utils.DtypeForDavinci.UINT8, utils.DtypeForDavinci.UINT16, utils.DtypeForDavinci.UINT32, utils.DtypeForDavinci.UINT64, utils.DtypeForDavinci.FLOAT16, utils.DtypeForDavinci.FLOAT32))
def _check_params(shape, num, axis, tensor_format, dtype): """ Check the parameters including shape, num, axis, format, dtype. Args: shape (tuple): the shape of tensor num (int): the length of the dim axis axis (int): axis of unapck tensor_format (str): the data format of input dtype (str): the data type Returns: None """ utils.check_shape(shape) # check format format_list = ("ND", "NHWC", "NCHW", "HWCN") if tensor_format == "NC1HWC0": if len(shape) != 5: raise RuntimeError("NC1HWC0 shape length should be equal to 5") # index list of H W axis. suporrted_list = (-5, -3, -2, 0, 2, 3) if axis not in suporrted_list: raise RuntimeError("NC1HWC0 supports unpack of N H W axis") else: if tensor_format not in format_list: raise RuntimeError("Format supports ND,NCHW,NHWC,HWCN and NC1HWC0") # check axis value if axis < -len(shape) or axis >= len(shape): raise RuntimeError("axis= %d not in the union of [%d, %d) " % (axis, -len(shape), len(shape))) # check num value if num is None: num = shape[axis] if num is None: raise RuntimeError("Cannot infer num value from shape %s" % shape) if num != shape[axis]: raise RuntimeError("Num shuld be equal to length of dim axis %d" % shape[axis]) # The maximum size of functional arguments is 1024B. # 1 param takes 8 bytes, needs Multiple output param and 1 input param, # so the maximum size of output is 127 = 1024 // 8 - 1. if num > 127: raise RuntimeError("Exceeds stack holding the parameters, " "maximum is 127 but get %d." % num) utils.ops_dtype_check( dtype, ( utils.DtypeForDavinci.INT8, utils.DtypeForDavinci.INT16, utils.DtypeForDavinci.INT32, utils.DtypeForDavinci.INT64, utils.DtypeForDavinci.UINT8, utils.DtypeForDavinci.UINT16, utils.DtypeForDavinci.UINT32, utils.DtypeForDavinci.UINT64, utils.DtypeForDavinci.FLOAT16, utils.DtypeForDavinci.FLOAT32))
Python
def _index_offset(shape, axis, offset, *index): """Compute the offset of index along one dimension.""" input_index = list(index) output_index = () for i, _ in enumerate(shape): if i == axis: input_index[i] = input_index[i] + offset output_index += (input_index[i],) return output_index
def _index_offset(shape, axis, offset, *index): """Compute the offset of index along one dimension.""" input_index = list(index) output_index = () for i, _ in enumerate(shape): if i == axis: input_index[i] = input_index[i] + offset output_index += (input_index[i],) return output_index
Python
def _unpack_compute(input_place, num, axis): """Unpack a tensor into `num` tensors along axis dimension.""" input_shape = get_shape(input_place) for index, _ in enumerate(input_shape): input_shape[index] = input_shape[index] if index != axis else 1 output_shape_list = [input_shape for i in range(num)] offset = 0 out_tensor_list = [] for i, t_shape in enumerate(output_shape_list): out_tensor = tvm.compute( t_shape, lambda *index, t_shape=t_shape: input_place(*_index_offset(t_shape, axis, offset, *index)), name='tensor' + str(i)) out_tensor_list.append(out_tensor) offset = offset + 1 return tuple(out_tensor_list)
def _unpack_compute(input_place, num, axis): """Unpack a tensor into `num` tensors along axis dimension.""" input_shape = get_shape(input_place) for index, _ in enumerate(input_shape): input_shape[index] = input_shape[index] if index != axis else 1 output_shape_list = [input_shape for i in range(num)] offset = 0 out_tensor_list = [] for i, t_shape in enumerate(output_shape_list): out_tensor = tvm.compute( t_shape, lambda *index, t_shape=t_shape: input_place(*_index_offset(t_shape, axis, offset, *index)), name='tensor' + str(i)) out_tensor_list.append(out_tensor) offset = offset + 1 return tuple(out_tensor_list)
Python
def unpack(value, tensor_format, num=None, axis=0, target=utils.CCE): """ Unpacks the given dimension of a rank R tensor into rank (R-1) tensors. It will produce `num` tensors from value, and `axis` dim of each tensor is 1. Args: value (tvm.tensor.Tensor): tensor to be unpacked tensor_format (str): data format, support "ND", "NHWC", "NCHW", "HWCN", "NC1HWC0". num (int): length of the dim axis, automatically inferred if None(default). axis (int): axis to unpack along Returns: The tuple of `tvm.tensor.Tensor` objects unpacked from value. """ shape = get_shape(value) dtype = value.dtype _check_params(shape, num, axis, tensor_format, dtype) # infer the value of num real_axis = axis + len(shape) if axis < 0 else axis num = shape[real_axis] return _unpack_compute(value, num, real_axis)
def unpack(value, tensor_format, num=None, axis=0, target=utils.CCE): """ Unpacks the given dimension of a rank R tensor into rank (R-1) tensors. It will produce `num` tensors from value, and `axis` dim of each tensor is 1. Args: value (tvm.tensor.Tensor): tensor to be unpacked tensor_format (str): data format, support "ND", "NHWC", "NCHW", "HWCN", "NC1HWC0". num (int): length of the dim axis, automatically inferred if None(default). axis (int): axis to unpack along Returns: The tuple of `tvm.tensor.Tensor` objects unpacked from value. """ shape = get_shape(value) dtype = value.dtype _check_params(shape, num, axis, tensor_format, dtype) # infer the value of num real_axis = axis + len(shape) if axis < 0 else axis num = shape[real_axis] return _unpack_compute(value, num, real_axis)
Python
def RealDiv(input1, input2, target=utils.CCE): """ Returns input1 / input2 element-wise for real types. Note: Realdiv supports broadcasting. Args: input1 (tvm.tensor.Tensor): Tensor of type float16, float32. input2 (tvm.tensor.Tensor): Tensor of type float16, float32. Returns: tvm.tensor.Tensor, has the same type of input1 and shaped by broadcasting. Supported Platforms: 'Ascend' """ utils.ops_dtype_check([input1.dtype, input2.dtype], utils.DtypeForDavinci.ALL_FLOAT) utils.elemwise_dtype_check(input1.dtype, input2.dtype) shape1 = [x.value for x in input1.shape] shape2 = [x.value for x in input2.shape] utils.check_shape(shape1) utils.check_shape(shape2) utils.auto_broadcast_check(shape1, shape2) n_shape1, n_shape2, out_shape = produce_shapes(shape1, shape2) if n_shape1 != out_shape: input1_cast = akg.topi.broadcast_to(input1, out_shape) else: input1_cast = input1 if n_shape2 != out_shape: input2_cast = akg.topi.broadcast_to(input2, out_shape) else: input2_cast = input2 res = akg.topi.divide(input1_cast, input2_cast) return res
def RealDiv(input1, input2, target=utils.CCE): """ Returns input1 / input2 element-wise for real types. Note: Realdiv supports broadcasting. Args: input1 (tvm.tensor.Tensor): Tensor of type float16, float32. input2 (tvm.tensor.Tensor): Tensor of type float16, float32. Returns: tvm.tensor.Tensor, has the same type of input1 and shaped by broadcasting. Supported Platforms: 'Ascend' """ utils.ops_dtype_check([input1.dtype, input2.dtype], utils.DtypeForDavinci.ALL_FLOAT) utils.elemwise_dtype_check(input1.dtype, input2.dtype) shape1 = [x.value for x in input1.shape] shape2 = [x.value for x in input2.shape] utils.check_shape(shape1) utils.check_shape(shape2) utils.auto_broadcast_check(shape1, shape2) n_shape1, n_shape2, out_shape = produce_shapes(shape1, shape2) if n_shape1 != out_shape: input1_cast = akg.topi.broadcast_to(input1, out_shape) else: input1_cast = input1 if n_shape2 != out_shape: input2_cast = akg.topi.broadcast_to(input2, out_shape) else: input2_cast = input2 res = akg.topi.divide(input1_cast, input2_cast) return res
Python
def args_to_workload(x, topi_compute_func=None): """Convert argument list to hashable workload tuple. This function will convert list to tuple, tvm node to python value and flatten tvm.tensor.Tensor to a tuple Parameters ---------- x: primitive hashable types or tensor.Tensor The original value topi_compute_func: topi compute function The function name will be added as first element of the workload tuple Returns ------- ret: hashable The hashable value """ if isinstance(x, tensor.Tensor): workload = get_const_tuple(x.shape) + (x.dtype, ) elif isinstance(x, (tuple, list, container.Array)): workload = tuple([args_to_workload(a) for a in x]) elif isinstance(x, (str, int, float, np.int, np.float, expr.Var)): workload = x elif isinstance(x, (expr.StringImm, expr.UIntImm, expr.IntImm, expr.FloatImm)): workload = x.value elif x is None: workload = 0 else: raise RuntimeError('Do not support type "%s" in argument. Consider to use' 'primitive types or tvm.expr.Var only' % type(x)) return (get_func_name(topi_compute_func), ) + workload if topi_compute_func else workload
def args_to_workload(x, topi_compute_func=None): """Convert argument list to hashable workload tuple. This function will convert list to tuple, tvm node to python value and flatten tvm.tensor.Tensor to a tuple Parameters ---------- x: primitive hashable types or tensor.Tensor The original value topi_compute_func: topi compute function The function name will be added as first element of the workload tuple Returns ------- ret: hashable The hashable value """ if isinstance(x, tensor.Tensor): workload = get_const_tuple(x.shape) + (x.dtype, ) elif isinstance(x, (tuple, list, container.Array)): workload = tuple([args_to_workload(a) for a in x]) elif isinstance(x, (str, int, float, np.int, np.float, expr.Var)): workload = x elif isinstance(x, (expr.StringImm, expr.UIntImm, expr.IntImm, expr.FloatImm)): workload = x.value elif x is None: workload = 0 else: raise RuntimeError('Do not support type "%s" in argument. Consider to use' 'primitive types or tvm.expr.Var only' % type(x)) return (get_func_name(topi_compute_func), ) + workload if topi_compute_func else workload
Python
def compute_flop(sch): """Calculate number of FLOP (floating number operations) of the compute ops in a schedule Parameters ---------- sch: tvm.schedule.Schedule schedule Returns ------- flop: int number of FLOP in this schedule """ def _prod_length(axes): """compute product of the lengths of a list of axes""" try: num_iter = int(np.prod([get_const_int(axis.dom.extent) for axis in axes])) except ValueError: raise FlopCalculationError("The length of axis is not constant. ") return num_iter def _count_flop(exp): """compute flop for a single expression""" if isinstance(exp, expr.Reduce): num_iter = _prod_length(exp.axis) combiner = exp.combiner.result source = exp.source if len(combiner) != 1: raise FlopCalculationError("Found multiple output in the combiner of reduce op") if len(source) != 1: raise FlopCalculationError("Found multiple output in the source of reduce op") return num_iter * (_count_flop(combiner[0]) + _count_flop(source[0])) if isinstance(exp, (expr.FloatImm, expr.IntImm, expr.UIntImm)): return 0 if isinstance(exp, expr.Cast): return _count_flop(exp.value) if isinstance(exp, expr.Var): return 0 if isinstance(exp, (expr.Add, expr.Sub, expr.Mul, expr.Div, expr.Mod, expr.FloorDiv, expr.FloorMod, expr.Max, expr.Min, expr.EQ, expr.NE, expr.LT, expr.LE, expr.GT, expr.GE, expr.And, expr.Or, expr.Not)): base = 1 if isinstance(exp, expr.Not): # unary return base + _count_flop(exp.a) return base + _count_flop(exp.a) + _count_flop(exp.b) if isinstance(exp, expr.Select): return _count_flop(exp.condition) + max(_count_flop(exp.true_value), _count_flop(exp.false_value)) if isinstance(exp, expr.Call): if exp.call_type == expr.Call.Halide: # Ignore flops from indexing expressions. return 0 return sum([_count_flop(x) for x in exp.args]) raise FlopCalculationError("Found unsupported operator in the compute expr") def traverse(ops): """accumulate flops""" ret = 0 for op in ops: if isinstance(op, tensor.ComputeOp): num_element = _prod_length(op.axis) body = op.body if len(body) != 1: raise FlopCalculationError("Found multiple output in the compute") exp = body[0] ret += num_element * _count_flop(exp) ret += traverse([t.op for t in op.input_tensors]) elif isinstance(op, tensor.PlaceholderOp): pass else: raise FlopCalculationError("Only support tvm.compute currently. " "Other ops like tvm.scan/tvm.extern is not supported") return ret try: ret = traverse(sch.outputs) except FlopCalculationError as exc: raise RuntimeError("FLOP estimator fails for this operator. Error msg: " + str(exc) + ". Please use `cfg.add_flop` to manually set " "FLOP for this operator") if ret == 0: raise RuntimeError("Cannot find float number operation in this operator. " "Please use `cfg.add_flop` to manually set " "FLOP for this operator") return ret
def compute_flop(sch): """Calculate number of FLOP (floating number operations) of the compute ops in a schedule Parameters ---------- sch: tvm.schedule.Schedule schedule Returns ------- flop: int number of FLOP in this schedule """ def _prod_length(axes): """compute product of the lengths of a list of axes""" try: num_iter = int(np.prod([get_const_int(axis.dom.extent) for axis in axes])) except ValueError: raise FlopCalculationError("The length of axis is not constant. ") return num_iter def _count_flop(exp): """compute flop for a single expression""" if isinstance(exp, expr.Reduce): num_iter = _prod_length(exp.axis) combiner = exp.combiner.result source = exp.source if len(combiner) != 1: raise FlopCalculationError("Found multiple output in the combiner of reduce op") if len(source) != 1: raise FlopCalculationError("Found multiple output in the source of reduce op") return num_iter * (_count_flop(combiner[0]) + _count_flop(source[0])) if isinstance(exp, (expr.FloatImm, expr.IntImm, expr.UIntImm)): return 0 if isinstance(exp, expr.Cast): return _count_flop(exp.value) if isinstance(exp, expr.Var): return 0 if isinstance(exp, (expr.Add, expr.Sub, expr.Mul, expr.Div, expr.Mod, expr.FloorDiv, expr.FloorMod, expr.Max, expr.Min, expr.EQ, expr.NE, expr.LT, expr.LE, expr.GT, expr.GE, expr.And, expr.Or, expr.Not)): base = 1 if isinstance(exp, expr.Not): # unary return base + _count_flop(exp.a) return base + _count_flop(exp.a) + _count_flop(exp.b) if isinstance(exp, expr.Select): return _count_flop(exp.condition) + max(_count_flop(exp.true_value), _count_flop(exp.false_value)) if isinstance(exp, expr.Call): if exp.call_type == expr.Call.Halide: # Ignore flops from indexing expressions. return 0 return sum([_count_flop(x) for x in exp.args]) raise FlopCalculationError("Found unsupported operator in the compute expr") def traverse(ops): """accumulate flops""" ret = 0 for op in ops: if isinstance(op, tensor.ComputeOp): num_element = _prod_length(op.axis) body = op.body if len(body) != 1: raise FlopCalculationError("Found multiple output in the compute") exp = body[0] ret += num_element * _count_flop(exp) ret += traverse([t.op for t in op.input_tensors]) elif isinstance(op, tensor.PlaceholderOp): pass else: raise FlopCalculationError("Only support tvm.compute currently. " "Other ops like tvm.scan/tvm.extern is not supported") return ret try: ret = traverse(sch.outputs) except FlopCalculationError as exc: raise RuntimeError("FLOP estimator fails for this operator. Error msg: " + str(exc) + ". Please use `cfg.add_flop` to manually set " "FLOP for this operator") if ret == 0: raise RuntimeError("Cannot find float number operation in this operator. " "Please use `cfg.add_flop` to manually set " "FLOP for this operator") return ret
Python
def _count_flop(exp): """compute flop for a single expression""" if isinstance(exp, expr.Reduce): num_iter = _prod_length(exp.axis) combiner = exp.combiner.result source = exp.source if len(combiner) != 1: raise FlopCalculationError("Found multiple output in the combiner of reduce op") if len(source) != 1: raise FlopCalculationError("Found multiple output in the source of reduce op") return num_iter * (_count_flop(combiner[0]) + _count_flop(source[0])) if isinstance(exp, (expr.FloatImm, expr.IntImm, expr.UIntImm)): return 0 if isinstance(exp, expr.Cast): return _count_flop(exp.value) if isinstance(exp, expr.Var): return 0 if isinstance(exp, (expr.Add, expr.Sub, expr.Mul, expr.Div, expr.Mod, expr.FloorDiv, expr.FloorMod, expr.Max, expr.Min, expr.EQ, expr.NE, expr.LT, expr.LE, expr.GT, expr.GE, expr.And, expr.Or, expr.Not)): base = 1 if isinstance(exp, expr.Not): # unary return base + _count_flop(exp.a) return base + _count_flop(exp.a) + _count_flop(exp.b) if isinstance(exp, expr.Select): return _count_flop(exp.condition) + max(_count_flop(exp.true_value), _count_flop(exp.false_value)) if isinstance(exp, expr.Call): if exp.call_type == expr.Call.Halide: # Ignore flops from indexing expressions. return 0 return sum([_count_flop(x) for x in exp.args]) raise FlopCalculationError("Found unsupported operator in the compute expr")
def _count_flop(exp): """compute flop for a single expression""" if isinstance(exp, expr.Reduce): num_iter = _prod_length(exp.axis) combiner = exp.combiner.result source = exp.source if len(combiner) != 1: raise FlopCalculationError("Found multiple output in the combiner of reduce op") if len(source) != 1: raise FlopCalculationError("Found multiple output in the source of reduce op") return num_iter * (_count_flop(combiner[0]) + _count_flop(source[0])) if isinstance(exp, (expr.FloatImm, expr.IntImm, expr.UIntImm)): return 0 if isinstance(exp, expr.Cast): return _count_flop(exp.value) if isinstance(exp, expr.Var): return 0 if isinstance(exp, (expr.Add, expr.Sub, expr.Mul, expr.Div, expr.Mod, expr.FloorDiv, expr.FloorMod, expr.Max, expr.Min, expr.EQ, expr.NE, expr.LT, expr.LE, expr.GT, expr.GE, expr.And, expr.Or, expr.Not)): base = 1 if isinstance(exp, expr.Not): # unary return base + _count_flop(exp.a) return base + _count_flop(exp.a) + _count_flop(exp.b) if isinstance(exp, expr.Select): return _count_flop(exp.condition) + max(_count_flop(exp.true_value), _count_flop(exp.false_value)) if isinstance(exp, expr.Call): if exp.call_type == expr.Call.Halide: # Ignore flops from indexing expressions. return 0 return sum([_count_flop(x) for x in exp.args]) raise FlopCalculationError("Found unsupported operator in the compute expr")
Python
def batchmatmul_tiling_strategy(shape, align_dtype, attrs): """This is an efficient version of tiling strategy for batchmatmul.""" if len(shape) < 3: raise RuntimeError("Shape must be in the form of [(Batch_out, Batch_in,) M, N, K]. " "Current length of shape is {}".format(len(shape))) strategy = list() m, n, k = shape[-3:] batch_pos, mnk = get_shape_pos_map(shape) total_size = reduce(lambda x, y: int(x) * int(y), shape) # set minimal tile for n as the basic block size for alignment align_elem = int(ct_util.BLOCK_SIZE / get_bytes(align_dtype)) tile_n = get_best_align_elem(n, align_dtype) # if n is smaller than block size, it is not safe to open multi-core for now if n < align_elem: n_constraint = [ct_util.TileConstraint.FACTOR] used_core = CORE_NUM attrs["enable_multicore"] = 0 else: n_constraint = [ct_util.TileConstraint.MOD, ct_util.TileConstraint.MIN] used_core = 1 if total_size >= MINIMAL_FOR_MULTICORE and used_core < CORE_NUM: # set maximal tile for batch according to multi-core usage for i, p in enumerate(batch_pos): use = min(shape[p], int((CORE_NUM - 1 + used_core) / used_core)) used_core *= use max_b = int(shape[p] / use) strategy.append(ct_util.create_constraint_on_axis(values=max_b, constraints=ct_util.TileConstraint.MAX, band=0, axis=i)[0]) tile_k = get_best_align_elem(k, align_dtype) k_constraint = ct_util.TileConstraint.MIN total_size /= max(1, int(k / tile_k)) # set minimal tile for m according to multi-core usage when there is no expansion tile_m = -1 m_constraint = ct_util.TileConstraint.MAX m_per_block = m max_core = min(CORE_NUM, int(total_size / MINIMAL_FOR_MULTICORE)) if greatest_common_divisor(n, align_elem) != 1 and used_core < max_core: left_core = int((max_core - 1 + used_core) / used_core) core_limit = max(1, int(m / greatest_common_divisor(left_core, m))) nk_in_mem = int(n / max(1, tile_n)) * int(k / tile_k) balance_limit = max(1, int(m / greatest_common_divisor(nk_in_mem, m))) tile_m = min(core_limit, balance_limit) m_per_block = int(m / tile_m) # for large m case, it is more efficient to balance memory bound and calculation bound if m_per_block > int(n / max(1, tile_n)) * int(k / tile_k): tile_m = max(min(m, align_elem), tile_m) k_constraint = ct_util.TileConstraint.FACTOR # create constraints based on previous analysis if m != 1: strategy.append(ct_util.create_constraint_on_axis(values=tile_m, constraints=m_constraint, band=0, axis=mnk["m"])[0]) if n != 1: for constraint in n_constraint: strategy.append(ct_util.create_constraint_on_axis(values=tile_n, constraints=constraint, band=0, axis=mnk["n"])[0]) if k != 1: strategy.append(ct_util.create_constraint_on_axis(values=tile_k, constraints=k_constraint, band=0, axis=mnk["k"])[0]) higher_priority_pos = mnk["k"] if k >= n else mnk["n"] strategy.append(ct_util.create_constraint_on_axis(values=0, constraints=ct_util.TileConstraint.SET_PRIORITY, band=0, axis=higher_priority_pos)[0]) strategy.append(ct_util.modify_common_constraints(0.7, ct_util.TileConstraint.SET_MEM_RATIO)) attrs["custom_tiling"] = strategy return attrs
def batchmatmul_tiling_strategy(shape, align_dtype, attrs): """This is an efficient version of tiling strategy for batchmatmul.""" if len(shape) < 3: raise RuntimeError("Shape must be in the form of [(Batch_out, Batch_in,) M, N, K]. " "Current length of shape is {}".format(len(shape))) strategy = list() m, n, k = shape[-3:] batch_pos, mnk = get_shape_pos_map(shape) total_size = reduce(lambda x, y: int(x) * int(y), shape) # set minimal tile for n as the basic block size for alignment align_elem = int(ct_util.BLOCK_SIZE / get_bytes(align_dtype)) tile_n = get_best_align_elem(n, align_dtype) # if n is smaller than block size, it is not safe to open multi-core for now if n < align_elem: n_constraint = [ct_util.TileConstraint.FACTOR] used_core = CORE_NUM attrs["enable_multicore"] = 0 else: n_constraint = [ct_util.TileConstraint.MOD, ct_util.TileConstraint.MIN] used_core = 1 if total_size >= MINIMAL_FOR_MULTICORE and used_core < CORE_NUM: # set maximal tile for batch according to multi-core usage for i, p in enumerate(batch_pos): use = min(shape[p], int((CORE_NUM - 1 + used_core) / used_core)) used_core *= use max_b = int(shape[p] / use) strategy.append(ct_util.create_constraint_on_axis(values=max_b, constraints=ct_util.TileConstraint.MAX, band=0, axis=i)[0]) tile_k = get_best_align_elem(k, align_dtype) k_constraint = ct_util.TileConstraint.MIN total_size /= max(1, int(k / tile_k)) # set minimal tile for m according to multi-core usage when there is no expansion tile_m = -1 m_constraint = ct_util.TileConstraint.MAX m_per_block = m max_core = min(CORE_NUM, int(total_size / MINIMAL_FOR_MULTICORE)) if greatest_common_divisor(n, align_elem) != 1 and used_core < max_core: left_core = int((max_core - 1 + used_core) / used_core) core_limit = max(1, int(m / greatest_common_divisor(left_core, m))) nk_in_mem = int(n / max(1, tile_n)) * int(k / tile_k) balance_limit = max(1, int(m / greatest_common_divisor(nk_in_mem, m))) tile_m = min(core_limit, balance_limit) m_per_block = int(m / tile_m) # for large m case, it is more efficient to balance memory bound and calculation bound if m_per_block > int(n / max(1, tile_n)) * int(k / tile_k): tile_m = max(min(m, align_elem), tile_m) k_constraint = ct_util.TileConstraint.FACTOR # create constraints based on previous analysis if m != 1: strategy.append(ct_util.create_constraint_on_axis(values=tile_m, constraints=m_constraint, band=0, axis=mnk["m"])[0]) if n != 1: for constraint in n_constraint: strategy.append(ct_util.create_constraint_on_axis(values=tile_n, constraints=constraint, band=0, axis=mnk["n"])[0]) if k != 1: strategy.append(ct_util.create_constraint_on_axis(values=tile_k, constraints=k_constraint, band=0, axis=mnk["k"])[0]) higher_priority_pos = mnk["k"] if k >= n else mnk["n"] strategy.append(ct_util.create_constraint_on_axis(values=0, constraints=ct_util.TileConstraint.SET_PRIORITY, band=0, axis=higher_priority_pos)[0]) strategy.append(ct_util.modify_common_constraints(0.7, ct_util.TileConstraint.SET_MEM_RATIO)) attrs["custom_tiling"] = strategy return attrs
Python
def batchmatmul_tiling_strategy_dynamic(shape, output, attrs): """This is an efficient version of tiling strategy for batchmatmul.""" if len(shape) < 3: raise RuntimeError("Shape must be in the form of [(Batch_out, Batch_in,) M, N, K]. " "Current length of shape is {}".format(len(shape))) strategy = list() _, mnk = get_shape_pos_map(shape) # create constraints based on previous analysis strategy.append(ct_util.create_constraint_on_axis(values=1, constraints=ct_util.TileConstraint.FACTOR, band=0, axis=mnk["m"])[0]) strategy.append(ct_util.create_constraint_on_axis(values="FULL", constraints=ct_util.TileConstraint.MAX, band=0, axis=mnk["n"])[0]) strategy.append(ct_util.create_constraint_on_axis(values=8, constraints=ct_util.TileConstraint.FACTOR, band=0, axis=mnk["k"])[0]) strategy.append(ct_util.modify_common_constraints(0.7, ct_util.TileConstraint.SET_MEM_RATIO)) attrs["custom_tiling"] = strategy attrs["dynamic_shape"] = ds.set_dynamic_shape_limit_for_tensor(output, 2048, [1,]) return attrs
def batchmatmul_tiling_strategy_dynamic(shape, output, attrs): """This is an efficient version of tiling strategy for batchmatmul.""" if len(shape) < 3: raise RuntimeError("Shape must be in the form of [(Batch_out, Batch_in,) M, N, K]. " "Current length of shape is {}".format(len(shape))) strategy = list() _, mnk = get_shape_pos_map(shape) # create constraints based on previous analysis strategy.append(ct_util.create_constraint_on_axis(values=1, constraints=ct_util.TileConstraint.FACTOR, band=0, axis=mnk["m"])[0]) strategy.append(ct_util.create_constraint_on_axis(values="FULL", constraints=ct_util.TileConstraint.MAX, band=0, axis=mnk["n"])[0]) strategy.append(ct_util.create_constraint_on_axis(values=8, constraints=ct_util.TileConstraint.FACTOR, band=0, axis=mnk["k"])[0]) strategy.append(ct_util.modify_common_constraints(0.7, ct_util.TileConstraint.SET_MEM_RATIO)) attrs["custom_tiling"] = strategy attrs["dynamic_shape"] = ds.set_dynamic_shape_limit_for_tensor(output, 2048, [1,]) return attrs
Python
def batchmatmul_set_dim(a_value, b_value, trans_a, trans_b): """This function is used to set dim info in attrs by set_dim_map.""" shape_a_list = get_shape(a_value) shape_b_list = get_shape(b_value) m, n, k = get_mnk_from_matrix(shape_a_list, shape_b_list, trans_a, trans_b) key = () if len(shape_a_list) > 2: key += tuple(shape_a_list[:-2]) key += (m, n, k, a_value.dtype, trans_a, trans_b) set_dims = ct_util.set_dims_by_key(str(key), batchmatmul_set_dim_map) return set_dims, str(key)
def batchmatmul_set_dim(a_value, b_value, trans_a, trans_b): """This function is used to set dim info in attrs by set_dim_map.""" shape_a_list = get_shape(a_value) shape_b_list = get_shape(b_value) m, n, k = get_mnk_from_matrix(shape_a_list, shape_b_list, trans_a, trans_b) key = () if len(shape_a_list) > 2: key += tuple(shape_a_list[:-2]) key += (m, n, k, a_value.dtype, trans_a, trans_b) set_dims = ct_util.set_dims_by_key(str(key), batchmatmul_set_dim_map) return set_dims, str(key)
Python
def BatchMatMulBias(a_value, b_value, bias_value, trans_a, trans_b): """ Multiplies two tensors in batches and adds bias to the output. Args: a_value (tvm.tensor.Tensor): 2D or 3D or 4D tensor of type float16 or float32 with shape(..., r_A, c_A). b_value (tvm.tensor.Tensor): 2D or 3D or 4D tensor of same type as a_value with shape(..., r_B, c_B). bias_value (tvm.tensor.Tensor): The bias tensor added to the result of a_value * b_value. Should be of same type as a_value, broadcast is allowed. trans_a (bool): Specifies whether a_value is transposed or not, default value is False. trans_b (bool): Specifies whether b_value is transposed or not, default value is False. Returns: tvm.tensor.Tensor of same type as a_value with shape(..., r_C, c_C). r_C = c_A if trans_a else r_A c_C = r_B if trans_b else c_B """ if not isinstance(trans_a, bool): raise TypeError("trans_a should be of type Boolean.") if not isinstance(trans_b, bool): raise TypeError("trans_b should be of type Boolean.") utils.ops_dtype_check([a_value.dtype, b_value.dtype, bias_value.dtype], utils.DtypeForDavinci.ALL_FLOAT) utils.elemwise_dtype_check(a_value.dtype, b_value.dtype) utils.elemwise_dtype_check(a_value.dtype, bias_value.dtype) utils.gemm_format_check(get_shape(a_value), get_shape(b_value), trans_a, trans_b) if len(a_value.shape) not in [2, 3, 4]: raise ValueError("Batch matmul only support 2D, 3D and 4D now.") c_value = BatchMatMul(a_value, b_value, trans_a, trans_b) if isinstance(c_value, (tuple, list)): c_value = c_value[0] utils.auto_broadcast_check(get_shape(bias_value), get_shape(c_value)) shape_c_list = get_shape(c_value) bias_value = akg.topi.broadcast_to(bias_value, shape_c_list) dim_info = batchmatmul_bias_set_dim(a_value, b_value, bias_value, trans_a, trans_b) if isinstance(dim_info, (tuple, list)): dim_info = dim_info[0] attrs = {} attrs["enable_compute_in_place"] = True if dim_info != "": attrs["dim"] = dim_info batch = get_shape(a_value)[:-2] mnk = get_mnk_from_matrix(get_shape(a_value), get_shape(b_value), trans_a, trans_b) attrs = batchmatmul_tiling_strategy(batch + mnk, c_value.dtype, attrs) return akg.tvm.compute(bias_value.shape, lambda *indice: c_value(*indice) + bias_value(*indice), name='matmul_bias_output'), attrs
def BatchMatMulBias(a_value, b_value, bias_value, trans_a, trans_b): """ Multiplies two tensors in batches and adds bias to the output. Args: a_value (tvm.tensor.Tensor): 2D or 3D or 4D tensor of type float16 or float32 with shape(..., r_A, c_A). b_value (tvm.tensor.Tensor): 2D or 3D or 4D tensor of same type as a_value with shape(..., r_B, c_B). bias_value (tvm.tensor.Tensor): The bias tensor added to the result of a_value * b_value. Should be of same type as a_value, broadcast is allowed. trans_a (bool): Specifies whether a_value is transposed or not, default value is False. trans_b (bool): Specifies whether b_value is transposed or not, default value is False. Returns: tvm.tensor.Tensor of same type as a_value with shape(..., r_C, c_C). r_C = c_A if trans_a else r_A c_C = r_B if trans_b else c_B """ if not isinstance(trans_a, bool): raise TypeError("trans_a should be of type Boolean.") if not isinstance(trans_b, bool): raise TypeError("trans_b should be of type Boolean.") utils.ops_dtype_check([a_value.dtype, b_value.dtype, bias_value.dtype], utils.DtypeForDavinci.ALL_FLOAT) utils.elemwise_dtype_check(a_value.dtype, b_value.dtype) utils.elemwise_dtype_check(a_value.dtype, bias_value.dtype) utils.gemm_format_check(get_shape(a_value), get_shape(b_value), trans_a, trans_b) if len(a_value.shape) not in [2, 3, 4]: raise ValueError("Batch matmul only support 2D, 3D and 4D now.") c_value = BatchMatMul(a_value, b_value, trans_a, trans_b) if isinstance(c_value, (tuple, list)): c_value = c_value[0] utils.auto_broadcast_check(get_shape(bias_value), get_shape(c_value)) shape_c_list = get_shape(c_value) bias_value = akg.topi.broadcast_to(bias_value, shape_c_list) dim_info = batchmatmul_bias_set_dim(a_value, b_value, bias_value, trans_a, trans_b) if isinstance(dim_info, (tuple, list)): dim_info = dim_info[0] attrs = {} attrs["enable_compute_in_place"] = True if dim_info != "": attrs["dim"] = dim_info batch = get_shape(a_value)[:-2] mnk = get_mnk_from_matrix(get_shape(a_value), get_shape(b_value), trans_a, trans_b) attrs = batchmatmul_tiling_strategy(batch + mnk, c_value.dtype, attrs) return akg.tvm.compute(bias_value.shape, lambda *indice: c_value(*indice) + bias_value(*indice), name='matmul_bias_output'), attrs
Python
def vectormatmul_3d(a_value, b_value, trans_a, trans_b): """hybrid implementation for 3D batchmatmul.""" if trans_a: bs, k, m = a_value.shape else: bs, m, k = a_value.shape if trans_b: n = b_value.shape[-2] else: n = b_value.shape[-1] dtype = a_value.dtype zero = akg.tvm.const(0.0, dtype=dtype) @script(capture=locals()) def matmul_hybrid_f_f(a, b, zero): t_1 = allocate((bs, m, k, n), a.dtype, 'local') t_2 = allocate((bs, m, n), a.dtype, 'local') for i_bs in range(0, bs): for i_m in range(0, m): for i_k in range(0, k): for i_n in range(0, n): t_1[i_bs, i_m, i_k, i_n] = a[i_bs, i_m, i_k] * b[i_bs, i_k, i_n] for i1_n in range(0, n): t_2[i_bs, i_m, i1_n] = zero for i1_k in range(0, k): for i1_n in range(0, n): t_2[i_bs, i_m, i1_n] = t_2[i_bs, i_m, i1_n] + t_1[i_bs, i_m, i1_k, i1_n] return t_2 @script(capture=locals()) def matmul_hybrid_f_t(a, b, zero): t_1 = allocate((bs, m, n, k), a.dtype, 'local') t_2 = allocate((bs, m, n), a.dtype, 'local') for i_bs in range(0, bs): for i_m in range(0, m): for i_n in range(0, n): t_2[i_bs, i_m, i_n] = zero for i_k in range(0, k): t_1[i_bs, i_m, i_n, i_k] = a[i_bs, i_m, i_k] * b[i_bs, i_n, i_k] t_2[i_bs, i_m, i_n] = t_1[i_bs, i_m, i_n, i_k] + t_2[i_bs, i_m, i_n] return t_2 @script(capture=locals()) def matmul_hybrid_t_f(a, b, zero): t_1 = allocate((bs, m, k, n), a.dtype, 'local') t_2 = allocate((bs, m, n), a.dtype, 'local') for i_bs in range(0, bs): for i_m in range(0, m): for i_k in range(0, k): for i_n in range(0, n): t_1[i_bs, i_m, i_k, i_n] = a[i_bs, i_k, i_m] * b[i_bs, i_k, i_n] for i1_n in range(0, n): t_2[i_bs, i_m, i1_n] = zero for i1_k in range(0, k): for i1_n in range(0, n): t_2[i_bs, i_m, i1_n] = t_2[i_bs, i_m, i1_n] + t_1[i_bs, i_m, i1_k, i1_n] return t_2 if not trans_a and not trans_b: c_value = matmul_hybrid_f_f(a_value, b_value, zero) elif not trans_a and trans_b: c_value = matmul_hybrid_f_t(a_value, b_value, zero) elif trans_a and not trans_b: c_value = matmul_hybrid_t_f(a_value, b_value, zero) else: raise ValueError('Not support both transpose yet') return c_value
def vectormatmul_3d(a_value, b_value, trans_a, trans_b): """hybrid implementation for 3D batchmatmul.""" if trans_a: bs, k, m = a_value.shape else: bs, m, k = a_value.shape if trans_b: n = b_value.shape[-2] else: n = b_value.shape[-1] dtype = a_value.dtype zero = akg.tvm.const(0.0, dtype=dtype) @script(capture=locals()) def matmul_hybrid_f_f(a, b, zero): t_1 = allocate((bs, m, k, n), a.dtype, 'local') t_2 = allocate((bs, m, n), a.dtype, 'local') for i_bs in range(0, bs): for i_m in range(0, m): for i_k in range(0, k): for i_n in range(0, n): t_1[i_bs, i_m, i_k, i_n] = a[i_bs, i_m, i_k] * b[i_bs, i_k, i_n] for i1_n in range(0, n): t_2[i_bs, i_m, i1_n] = zero for i1_k in range(0, k): for i1_n in range(0, n): t_2[i_bs, i_m, i1_n] = t_2[i_bs, i_m, i1_n] + t_1[i_bs, i_m, i1_k, i1_n] return t_2 @script(capture=locals()) def matmul_hybrid_f_t(a, b, zero): t_1 = allocate((bs, m, n, k), a.dtype, 'local') t_2 = allocate((bs, m, n), a.dtype, 'local') for i_bs in range(0, bs): for i_m in range(0, m): for i_n in range(0, n): t_2[i_bs, i_m, i_n] = zero for i_k in range(0, k): t_1[i_bs, i_m, i_n, i_k] = a[i_bs, i_m, i_k] * b[i_bs, i_n, i_k] t_2[i_bs, i_m, i_n] = t_1[i_bs, i_m, i_n, i_k] + t_2[i_bs, i_m, i_n] return t_2 @script(capture=locals()) def matmul_hybrid_t_f(a, b, zero): t_1 = allocate((bs, m, k, n), a.dtype, 'local') t_2 = allocate((bs, m, n), a.dtype, 'local') for i_bs in range(0, bs): for i_m in range(0, m): for i_k in range(0, k): for i_n in range(0, n): t_1[i_bs, i_m, i_k, i_n] = a[i_bs, i_k, i_m] * b[i_bs, i_k, i_n] for i1_n in range(0, n): t_2[i_bs, i_m, i1_n] = zero for i1_k in range(0, k): for i1_n in range(0, n): t_2[i_bs, i_m, i1_n] = t_2[i_bs, i_m, i1_n] + t_1[i_bs, i_m, i1_k, i1_n] return t_2 if not trans_a and not trans_b: c_value = matmul_hybrid_f_f(a_value, b_value, zero) elif not trans_a and trans_b: c_value = matmul_hybrid_f_t(a_value, b_value, zero) elif trans_a and not trans_b: c_value = matmul_hybrid_t_f(a_value, b_value, zero) else: raise ValueError('Not support both transpose yet') return c_value
Python
def vectormatmul_4d(a_value, b_value, trans_a, trans_b): """hybrid implementation for 4D batchmatmul.""" if trans_a: bs1, bs2, k, m = a_value.shape else: bs1, bs2, m, k = a_value.shape if trans_b: n = b_value.shape[-2] else: n = b_value.shape[-1] dtype = a_value.dtype zero = akg.tvm.const(0.0, dtype=dtype) @script(capture=locals()) def matmul_hybrid_f_f(a, b, zero): t_1 = allocate((bs1, bs2, m, k, n), a.dtype, 'local') t_2 = allocate((bs1, bs2, m, n), a.dtype, 'local') for i_bs1 in range(0, bs1): for i_bs2 in range(0, bs2): for i_m in range(0, m): for i_k in range(0, k): for i_n in range(0, n): t_1[i_bs1, i_bs2, i_m, i_k, i_n] = a[i_bs1, i_bs2, i_m, i_k] * b[i_bs1, i_bs2, i_k, i_n] for i1_n in range(0, n): t_2[i_bs1, i_bs2, i_m, i1_n] = zero for i1_k in range(0, k): for i1_n in range(0, n): t_2[i_bs1, i_bs2, i_m, i1_n] = t_2[i_bs1, i_bs2, i_m, i1_n] + \ t_1[i_bs1, i_bs2, i_m, i1_k, i1_n] return t_2 @script(capture=locals()) def matmul_hybrid_f_t(a, b, zero): t_1 = allocate((bs1, bs2, m, n, k), a.dtype, 'local') t_2 = allocate((bs1, bs2, m, n), a.dtype, 'local') for i_bs1 in range(0, bs1): for i_bs2 in range(0, bs2): for i_m in range(0, m): for i_n in range(0, n): t_2[i_bs1, i_bs2, i_m, i_n] = zero for i_k in range(0, k): t_1[i_bs1, i_bs2, i_m, i_n, i_k] = a[i_bs1, i_bs2, i_m, i_k] * b[i_bs1, i_bs2, i_n, i_k] t_2[i_bs1, i_bs2, i_m, i_n] = t_1[i_bs1, i_bs2, i_m, i_n, i_k] + t_2[i_bs1, i_bs2, i_m, i_n] return t_2 @script(capture=locals()) def matmul_hybrid_t_f(a, b, zero): t_1 = allocate((bs1, bs2, m, k, n), a.dtype, 'local') t_2 = allocate((bs1, bs2, m, n), a.dtype, 'local') for i_bs1 in range(0, bs1): for i_bs2 in range(0, bs2): for i_m in range(0, m): for i_k in range(0, k): for i_n in range(0, n): t_1[i_bs1, i_bs2, i_m, i_k, i_n] = a[i_bs1, i_bs2, i_k, i_m] * b[i_bs1, i_bs2, i_k, i_n] for i1_n in range(0, n): t_2[i_bs1, i_bs2, i_m, i1_n] = zero for i1_k in range(0, k): for i1_n in range(0, n): t_2[i_bs1, i_bs2, i_m, i1_n] = t_2[i_bs1, i_bs2, i_m, i1_n] + \ t_1[i_bs1, i_bs2, i_m, i1_k, i1_n] return t_2 if not trans_a and not trans_b: c_value = matmul_hybrid_f_f(a_value, b_value, zero) elif not trans_a and trans_b: c_value = matmul_hybrid_f_t(a_value, b_value, zero) elif trans_a and not trans_b: c_value = matmul_hybrid_t_f(a_value, b_value, zero) else: raise ValueError('Not support both transpose yet') return c_value
def vectormatmul_4d(a_value, b_value, trans_a, trans_b): """hybrid implementation for 4D batchmatmul.""" if trans_a: bs1, bs2, k, m = a_value.shape else: bs1, bs2, m, k = a_value.shape if trans_b: n = b_value.shape[-2] else: n = b_value.shape[-1] dtype = a_value.dtype zero = akg.tvm.const(0.0, dtype=dtype) @script(capture=locals()) def matmul_hybrid_f_f(a, b, zero): t_1 = allocate((bs1, bs2, m, k, n), a.dtype, 'local') t_2 = allocate((bs1, bs2, m, n), a.dtype, 'local') for i_bs1 in range(0, bs1): for i_bs2 in range(0, bs2): for i_m in range(0, m): for i_k in range(0, k): for i_n in range(0, n): t_1[i_bs1, i_bs2, i_m, i_k, i_n] = a[i_bs1, i_bs2, i_m, i_k] * b[i_bs1, i_bs2, i_k, i_n] for i1_n in range(0, n): t_2[i_bs1, i_bs2, i_m, i1_n] = zero for i1_k in range(0, k): for i1_n in range(0, n): t_2[i_bs1, i_bs2, i_m, i1_n] = t_2[i_bs1, i_bs2, i_m, i1_n] + \ t_1[i_bs1, i_bs2, i_m, i1_k, i1_n] return t_2 @script(capture=locals()) def matmul_hybrid_f_t(a, b, zero): t_1 = allocate((bs1, bs2, m, n, k), a.dtype, 'local') t_2 = allocate((bs1, bs2, m, n), a.dtype, 'local') for i_bs1 in range(0, bs1): for i_bs2 in range(0, bs2): for i_m in range(0, m): for i_n in range(0, n): t_2[i_bs1, i_bs2, i_m, i_n] = zero for i_k in range(0, k): t_1[i_bs1, i_bs2, i_m, i_n, i_k] = a[i_bs1, i_bs2, i_m, i_k] * b[i_bs1, i_bs2, i_n, i_k] t_2[i_bs1, i_bs2, i_m, i_n] = t_1[i_bs1, i_bs2, i_m, i_n, i_k] + t_2[i_bs1, i_bs2, i_m, i_n] return t_2 @script(capture=locals()) def matmul_hybrid_t_f(a, b, zero): t_1 = allocate((bs1, bs2, m, k, n), a.dtype, 'local') t_2 = allocate((bs1, bs2, m, n), a.dtype, 'local') for i_bs1 in range(0, bs1): for i_bs2 in range(0, bs2): for i_m in range(0, m): for i_k in range(0, k): for i_n in range(0, n): t_1[i_bs1, i_bs2, i_m, i_k, i_n] = a[i_bs1, i_bs2, i_k, i_m] * b[i_bs1, i_bs2, i_k, i_n] for i1_n in range(0, n): t_2[i_bs1, i_bs2, i_m, i1_n] = zero for i1_k in range(0, k): for i1_n in range(0, n): t_2[i_bs1, i_bs2, i_m, i1_n] = t_2[i_bs1, i_bs2, i_m, i1_n] + \ t_1[i_bs1, i_bs2, i_m, i1_k, i1_n] return t_2 if not trans_a and not trans_b: c_value = matmul_hybrid_f_f(a_value, b_value, zero) elif not trans_a and trans_b: c_value = matmul_hybrid_f_t(a_value, b_value, zero) elif trans_a and not trans_b: c_value = matmul_hybrid_t_f(a_value, b_value, zero) else: raise ValueError('Not support both transpose yet') return c_value
Python
def vectormatmul_4d_cast(a_value, b_value, trans_a, trans_b, cast_dtype): """dsl implementation with data type cast for 4D batchmatmul.""" if trans_a: b1, b2, k, m = a_value.shape else: b1, b2, m, k = a_value.shape if trans_b: n = b_value.shape[-2] else: n = b_value.shape[-1] dtype = a_value.dtype def matmul_4d_dsl(a_value, b_value, trans_a, trans_b): if not trans_a and not trans_b: ele_mul = akg.tvm.compute((b1, b2, m, n, k), lambda i_b1, i_b2, i_m, i_n, i_k: a_value[i_b1, i_b2, i_m, i_k].astype(cast_dtype) * b_value[i_b1, i_b2, i_k, i_n].astype(cast_dtype), name="ele_mul") elif not trans_a and trans_b: ele_mul = akg.tvm.compute((b1, b2, m, n, k), lambda i_b1, i_b2, i_m, i_n, i_k: a_value[i_b1, i_b2, i_m, i_k].astype(cast_dtype) * b_value[i_b1, i_b2, i_n, i_k].astype(cast_dtype), name="ele_mul") elif trans_a and not trans_b: ele_mul = akg.tvm.compute((b1, b2, m, n, k), lambda i_b1, i_b2, i_m, i_n, i_k: a_value[i_b1, i_b2, i_k, i_m].astype(cast_dtype) * b_value[i_b1, i_b2, i_k, i_n].astype(cast_dtype), name="ele_mul") elif trans_a and trans_b: ele_mul = akg.tvm.compute((b1, b2, m, n, k), lambda i_b1, i_b2, i_m, i_n, i_k: b_value[i_b1, i_b2, i_n, i_k].astype(cast_dtype) * a_value[i_b1, i_b2, i_k, i_m].astype(cast_dtype), name="ele_mul") reduce_axis = akg.tvm.reduce_axis((0, k), name='reduce_axis') output_shape = (b1, b2, m, n) m_c = akg.tvm.compute(output_shape, lambda *i: akg.tvm.sum(ele_mul[i + (reduce_axis,)], axis=reduce_axis), name="matmul_compute") return m_c c_cast = matmul_4d_dsl(a_value, b_value, trans_a, trans_b) c_value = Cast(c_cast, dtype, utils.CCE) if trans_a and trans_b: c_res = akg.topi.transpose(c_value, (1, 0)) return c_res return c_value
def vectormatmul_4d_cast(a_value, b_value, trans_a, trans_b, cast_dtype): """dsl implementation with data type cast for 4D batchmatmul.""" if trans_a: b1, b2, k, m = a_value.shape else: b1, b2, m, k = a_value.shape if trans_b: n = b_value.shape[-2] else: n = b_value.shape[-1] dtype = a_value.dtype def matmul_4d_dsl(a_value, b_value, trans_a, trans_b): if not trans_a and not trans_b: ele_mul = akg.tvm.compute((b1, b2, m, n, k), lambda i_b1, i_b2, i_m, i_n, i_k: a_value[i_b1, i_b2, i_m, i_k].astype(cast_dtype) * b_value[i_b1, i_b2, i_k, i_n].astype(cast_dtype), name="ele_mul") elif not trans_a and trans_b: ele_mul = akg.tvm.compute((b1, b2, m, n, k), lambda i_b1, i_b2, i_m, i_n, i_k: a_value[i_b1, i_b2, i_m, i_k].astype(cast_dtype) * b_value[i_b1, i_b2, i_n, i_k].astype(cast_dtype), name="ele_mul") elif trans_a and not trans_b: ele_mul = akg.tvm.compute((b1, b2, m, n, k), lambda i_b1, i_b2, i_m, i_n, i_k: a_value[i_b1, i_b2, i_k, i_m].astype(cast_dtype) * b_value[i_b1, i_b2, i_k, i_n].astype(cast_dtype), name="ele_mul") elif trans_a and trans_b: ele_mul = akg.tvm.compute((b1, b2, m, n, k), lambda i_b1, i_b2, i_m, i_n, i_k: b_value[i_b1, i_b2, i_n, i_k].astype(cast_dtype) * a_value[i_b1, i_b2, i_k, i_m].astype(cast_dtype), name="ele_mul") reduce_axis = akg.tvm.reduce_axis((0, k), name='reduce_axis') output_shape = (b1, b2, m, n) m_c = akg.tvm.compute(output_shape, lambda *i: akg.tvm.sum(ele_mul[i + (reduce_axis,)], axis=reduce_axis), name="matmul_compute") return m_c c_cast = matmul_4d_dsl(a_value, b_value, trans_a, trans_b) c_value = Cast(c_cast, dtype, utils.CCE) if trans_a and trans_b: c_res = akg.topi.transpose(c_value, (1, 0)) return c_res return c_value
Python
def vectormatmul_3d_cast(a_value, b_value, trans_a, trans_b, cast_dtype): """dsl implementation with data type cast for 3D batchmatmul.""" if trans_a: b, k, m = a_value.shape else: b, m, k = a_value.shape if trans_b: n = b_value.shape[-2] else: n = b_value.shape[-1] dtype = a_value.dtype def matmul_3d_dsl(a_value, b_value, trans_a, trans_b): if not trans_a and not trans_b: ele_mul = akg.tvm.compute((b, m, n, k), lambda i_b, i_m, i_n, i_k: a_value[i_b, i_m, i_k].astype(cast_dtype) * b_value[i_b, i_k, i_n].astype(cast_dtype), name="ele_mul") elif not trans_a and trans_b: ele_mul = akg.tvm.compute((b, m, n, k), lambda i_b, i_m, i_n, i_k: a_value[i_b, i_m, i_k].astype(cast_dtype) * b_value[i_b, i_n, i_k].astype(cast_dtype), name="ele_mul") elif trans_a and not trans_b: ele_mul = akg.tvm.compute((b, m, n, k), lambda i_b, i_m, i_n, i_k: a_value[i_b, i_k, i_m].astype(cast_dtype) * b_value[i_b, i_k, i_n].astype(cast_dtype), name="ele_mul") elif trans_a and trans_b: ele_mul = akg.tvm.compute((b, m, n, k), lambda i_b, i_m, i_n, i_k: b_value[i_b, i_n, i_k].astype(cast_dtype) * a_value[i_b, i_k, i_m].astype(cast_dtype), name="ele_mul") reduce_axis = akg.tvm.reduce_axis((0, k), name='reduce_axis') output_shape = (b, m, n) m_c = akg.tvm.compute(output_shape, lambda *i: akg.tvm.sum(ele_mul[i + (reduce_axis,)], axis=reduce_axis), name="matmul_compute") return m_c c_cast = matmul_3d_dsl(a_value, b_value, trans_a, trans_b) c_value = Cast(c_cast, dtype, utils.CCE) if trans_a and trans_b: c_res = akg.topi.transpose(c_value, (1, 0)) return c_res return c_value
def vectormatmul_3d_cast(a_value, b_value, trans_a, trans_b, cast_dtype): """dsl implementation with data type cast for 3D batchmatmul.""" if trans_a: b, k, m = a_value.shape else: b, m, k = a_value.shape if trans_b: n = b_value.shape[-2] else: n = b_value.shape[-1] dtype = a_value.dtype def matmul_3d_dsl(a_value, b_value, trans_a, trans_b): if not trans_a and not trans_b: ele_mul = akg.tvm.compute((b, m, n, k), lambda i_b, i_m, i_n, i_k: a_value[i_b, i_m, i_k].astype(cast_dtype) * b_value[i_b, i_k, i_n].astype(cast_dtype), name="ele_mul") elif not trans_a and trans_b: ele_mul = akg.tvm.compute((b, m, n, k), lambda i_b, i_m, i_n, i_k: a_value[i_b, i_m, i_k].astype(cast_dtype) * b_value[i_b, i_n, i_k].astype(cast_dtype), name="ele_mul") elif trans_a and not trans_b: ele_mul = akg.tvm.compute((b, m, n, k), lambda i_b, i_m, i_n, i_k: a_value[i_b, i_k, i_m].astype(cast_dtype) * b_value[i_b, i_k, i_n].astype(cast_dtype), name="ele_mul") elif trans_a and trans_b: ele_mul = akg.tvm.compute((b, m, n, k), lambda i_b, i_m, i_n, i_k: b_value[i_b, i_n, i_k].astype(cast_dtype) * a_value[i_b, i_k, i_m].astype(cast_dtype), name="ele_mul") reduce_axis = akg.tvm.reduce_axis((0, k), name='reduce_axis') output_shape = (b, m, n) m_c = akg.tvm.compute(output_shape, lambda *i: akg.tvm.sum(ele_mul[i + (reduce_axis,)], axis=reduce_axis), name="matmul_compute") return m_c c_cast = matmul_3d_dsl(a_value, b_value, trans_a, trans_b) c_value = Cast(c_cast, dtype, utils.CCE) if trans_a and trans_b: c_res = akg.topi.transpose(c_value, (1, 0)) return c_res return c_value
Python
def vectormatmul_2d_cast(a_value, b_value, trans_a, trans_b, cast_dtype): """hybrid implementation with data type cast for 2D batchmatmul.""" if trans_a: k, m = a_value.shape else: m, k = a_value.shape if trans_b: n = b_value.shape[-2] else: n = b_value.shape[-1] dtype = a_value.dtype # When the float16 cast to float32 directly, the AutoPoly pass cost a long time. # Therefore, the cast be done in single element. def matmul_2d(a_value, b_value, trans_a, trans_b): if not trans_a and not trans_b: ele_mul = akg.tvm.compute((m, n, k), lambda i_m, i_n, i_k: a_value[i_m, i_k].astype(cast_dtype) * b_value[i_k, i_n].astype(cast_dtype), name="ele_mul") elif not trans_a and trans_b: ele_mul = akg.tvm.compute((m, n, k), lambda i_m, i_n, i_k: a_value[i_m, i_k].astype(cast_dtype) * b_value[i_n, i_k].astype(cast_dtype), name="ele_mul") elif trans_a and not trans_b: ele_mul = akg.tvm.compute((m, n, k), lambda i_m, i_n, i_k: a_value[i_k, i_m].astype(cast_dtype) * b_value[i_k, i_n].astype(cast_dtype), name="ele_mul") elif trans_a and trans_b: ele_mul = akg.tvm.compute((m, n, k), lambda i_m, i_n, i_k: b_value[i_n, i_k].astype(cast_dtype) * a_value[i_k, i_m].astype(cast_dtype), name="ele_mul") reduce_axis = akg.tvm.reduce_axis((0, k), name='reduce_axis') output_shape = (m, n) m_c = akg.tvm.compute(output_shape, lambda *i: akg.tvm.sum(ele_mul[i + (reduce_axis,)], axis=reduce_axis), name="matmul_compute") return m_c c_cast = matmul_2d(a_value, b_value, trans_a, trans_b) c_value = Cast(c_cast, dtype, utils.CCE) if trans_a and trans_b: c_res = akg.topi.transpose(c_value, (1, 0)) return c_res return c_value
def vectormatmul_2d_cast(a_value, b_value, trans_a, trans_b, cast_dtype): """hybrid implementation with data type cast for 2D batchmatmul.""" if trans_a: k, m = a_value.shape else: m, k = a_value.shape if trans_b: n = b_value.shape[-2] else: n = b_value.shape[-1] dtype = a_value.dtype # When the float16 cast to float32 directly, the AutoPoly pass cost a long time. # Therefore, the cast be done in single element. def matmul_2d(a_value, b_value, trans_a, trans_b): if not trans_a and not trans_b: ele_mul = akg.tvm.compute((m, n, k), lambda i_m, i_n, i_k: a_value[i_m, i_k].astype(cast_dtype) * b_value[i_k, i_n].astype(cast_dtype), name="ele_mul") elif not trans_a and trans_b: ele_mul = akg.tvm.compute((m, n, k), lambda i_m, i_n, i_k: a_value[i_m, i_k].astype(cast_dtype) * b_value[i_n, i_k].astype(cast_dtype), name="ele_mul") elif trans_a and not trans_b: ele_mul = akg.tvm.compute((m, n, k), lambda i_m, i_n, i_k: a_value[i_k, i_m].astype(cast_dtype) * b_value[i_k, i_n].astype(cast_dtype), name="ele_mul") elif trans_a and trans_b: ele_mul = akg.tvm.compute((m, n, k), lambda i_m, i_n, i_k: b_value[i_n, i_k].astype(cast_dtype) * a_value[i_k, i_m].astype(cast_dtype), name="ele_mul") reduce_axis = akg.tvm.reduce_axis((0, k), name='reduce_axis') output_shape = (m, n) m_c = akg.tvm.compute(output_shape, lambda *i: akg.tvm.sum(ele_mul[i + (reduce_axis,)], axis=reduce_axis), name="matmul_compute") return m_c c_cast = matmul_2d(a_value, b_value, trans_a, trans_b) c_value = Cast(c_cast, dtype, utils.CCE) if trans_a and trans_b: c_res = akg.topi.transpose(c_value, (1, 0)) return c_res return c_value
Python
def vectormatmul_2d(a_value, b_value, trans_a, trans_b): """hybrid implementation for 2D batchmatmul.""" if trans_a: k, m = a_value.shape else: m, k = a_value.shape if trans_b: n = b_value.shape[-2] else: n = b_value.shape[-1] dtype = a_value.dtype zero = akg.tvm.const(0.0, dtype=dtype) @script(capture=locals()) def matmul_hybrid_f_f(a, b, zero, mv, nv, kv): t_1 = allocate((mv, kv, nv), a.dtype, 'local') t_2 = output_tensor((mv, nv), a.dtype) for i_m in range(0, mv): for i_k in range(0, kv): for i_n in range(0, nv): t_1[i_m, i_k, i_n] = a[i_m, i_k] * b[i_k, i_n] for i1_n in range(0, nv): t_2[i_m, i1_n] = zero for i1_k in range(0, kv): for i1_n in range(0, nv): t_2[i_m, i1_n] = t_2[i_m, i1_n] + t_1[i_m, i1_k, i1_n] return t_2 @script(capture=locals()) def matmul_hybrid_f_t(a, b, zero, mv, nv, kv): t_1 = allocate((mv, nv, kv), a.dtype, 'local') t_2 = allocate((mv, nv), a.dtype, 'local') for i_m in range(0, mv): for i_n in range(0, nv): t_2[i_m, i_n] = zero for i_k in range(0, kv): t_1[i_m, i_n, i_k] = a[i_m, i_k] * b[i_n, i_k] t_2[i_m, i_n] = t_1[i_m, i_n, i_k] + t_2[i_m, i_n] return t_2 @script(capture=locals()) def matmul_hybrid_t_f(a, b, zero, mv, nv, kv): t_1 = allocate((mv, kv, nv), a.dtype, 'local') t_2 = allocate((mv, nv), a.dtype, 'local') for i_m in range(0, mv): for i_k in range(0, kv): for i_n in range(0, nv): t_1[i_m, i_k, i_n] = a[i_k, i_m] * b[i_k, i_n] for i1_n in range(0, nv): t_2[i_m, i1_n] = zero for i1_k in range(0, kv): for i1_n in range(0, nv): t_2[i_m, i1_n] = t_2[i_m, i1_n] + t_1[i_m, i1_k, i1_n] return t_2 @script(capture=locals()) def matmul_hybrid_t_t(a, b, zero, mv, nv, kv): t_1 = allocate((nv, kv, mv), a.dtype, 'local') t_2 = allocate((nv, mv), a.dtype, 'local') for i_n in range(0, nv): for i_m in range(0, mv): for i_k in range(0, kv): t_1[i_n, i_k, i_m] = b[i_n, i_k] * a[i_k, i_m] for i1_m in range(0, mv): t_2[i_n, i1_m] = zero for i1_k in range(0, kv): for i2_m in range(0, mv): t_2[i_n, i2_m] = t_2[i_n, i2_m] + t_1[i_n, i1_k, i2_m] return t_2 if not trans_a and not trans_b: c_value = matmul_hybrid_f_f(a_value, b_value, zero, m, n, k) elif not trans_a and trans_b: c_value = matmul_hybrid_f_t(a_value, b_value, zero, m, n, k) elif trans_a and not trans_b: c_value = matmul_hybrid_t_f(a_value, b_value, zero, m, n, k) else: c1 = matmul_hybrid_t_t(a_value, b_value, zero, m, n, k) c_value = akg.topi.transpose(c1, (1, 0)) return c_value
def vectormatmul_2d(a_value, b_value, trans_a, trans_b): """hybrid implementation for 2D batchmatmul.""" if trans_a: k, m = a_value.shape else: m, k = a_value.shape if trans_b: n = b_value.shape[-2] else: n = b_value.shape[-1] dtype = a_value.dtype zero = akg.tvm.const(0.0, dtype=dtype) @script(capture=locals()) def matmul_hybrid_f_f(a, b, zero, mv, nv, kv): t_1 = allocate((mv, kv, nv), a.dtype, 'local') t_2 = output_tensor((mv, nv), a.dtype) for i_m in range(0, mv): for i_k in range(0, kv): for i_n in range(0, nv): t_1[i_m, i_k, i_n] = a[i_m, i_k] * b[i_k, i_n] for i1_n in range(0, nv): t_2[i_m, i1_n] = zero for i1_k in range(0, kv): for i1_n in range(0, nv): t_2[i_m, i1_n] = t_2[i_m, i1_n] + t_1[i_m, i1_k, i1_n] return t_2 @script(capture=locals()) def matmul_hybrid_f_t(a, b, zero, mv, nv, kv): t_1 = allocate((mv, nv, kv), a.dtype, 'local') t_2 = allocate((mv, nv), a.dtype, 'local') for i_m in range(0, mv): for i_n in range(0, nv): t_2[i_m, i_n] = zero for i_k in range(0, kv): t_1[i_m, i_n, i_k] = a[i_m, i_k] * b[i_n, i_k] t_2[i_m, i_n] = t_1[i_m, i_n, i_k] + t_2[i_m, i_n] return t_2 @script(capture=locals()) def matmul_hybrid_t_f(a, b, zero, mv, nv, kv): t_1 = allocate((mv, kv, nv), a.dtype, 'local') t_2 = allocate((mv, nv), a.dtype, 'local') for i_m in range(0, mv): for i_k in range(0, kv): for i_n in range(0, nv): t_1[i_m, i_k, i_n] = a[i_k, i_m] * b[i_k, i_n] for i1_n in range(0, nv): t_2[i_m, i1_n] = zero for i1_k in range(0, kv): for i1_n in range(0, nv): t_2[i_m, i1_n] = t_2[i_m, i1_n] + t_1[i_m, i1_k, i1_n] return t_2 @script(capture=locals()) def matmul_hybrid_t_t(a, b, zero, mv, nv, kv): t_1 = allocate((nv, kv, mv), a.dtype, 'local') t_2 = allocate((nv, mv), a.dtype, 'local') for i_n in range(0, nv): for i_m in range(0, mv): for i_k in range(0, kv): t_1[i_n, i_k, i_m] = b[i_n, i_k] * a[i_k, i_m] for i1_m in range(0, mv): t_2[i_n, i1_m] = zero for i1_k in range(0, kv): for i2_m in range(0, mv): t_2[i_n, i2_m] = t_2[i_n, i2_m] + t_1[i_n, i1_k, i2_m] return t_2 if not trans_a and not trans_b: c_value = matmul_hybrid_f_f(a_value, b_value, zero, m, n, k) elif not trans_a and trans_b: c_value = matmul_hybrid_f_t(a_value, b_value, zero, m, n, k) elif trans_a and not trans_b: c_value = matmul_hybrid_t_f(a_value, b_value, zero, m, n, k) else: c1 = matmul_hybrid_t_t(a_value, b_value, zero, m, n, k) c_value = akg.topi.transpose(c1, (1, 0)) return c_value
Python
def BatchMatMul(a_value, b_value, trans_a=False, trans_b=False, target=utils.CCE): """ Multiplies two tensors in batches. Args: a_value (tvm.tensor.Tensor): 2D or 3D or 4D tensor of type float16 or float32 with shape(..., r_A, c_A). b_value (tvm.tensor.Tensor): 2D or 3D or 4D tensor of same type as a_value with shape(..., r_B, c_B). trans_a (bool): Specifies whether a_value is transposed or not, default value is False. trans_b (bool): Specifies whether b_value is transposed or not, default value is False. Returns: tvm.tensor.Tensor of same type as a_value with shape(..., r_C, c_C). r_C = c_A if trans_a else r_A c_C = r_B if trans_b else c_B Supported Platforms: 'Ascend' """ if not isinstance(trans_a, bool): raise TypeError("trans_a should be of type Boolean.") if not isinstance(trans_b, bool): raise TypeError("trans_b should be of type Boolean.") utils.ops_dtype_check([a_value.dtype, b_value.dtype], utils.DtypeForDavinci.ALL_FLOAT) utils.elemwise_dtype_check(a_value.dtype, b_value.dtype) utils.gemm_format_check(get_shape(a_value), get_shape(b_value), trans_a, trans_b) if len(a_value.shape) not in [2, 3, 4]: raise ValueError("Batch matmul only support 2D, 3D and 4D now.") dtype = a_value.dtype if dtype == 'float16': if len(a_value.shape) == 2: c_value = vectormatmul_2d_cast(a_value, b_value, trans_a, trans_b, "float32") elif len(a_value.shape) == 3: c_value = vectormatmul_3d_cast(a_value, b_value, trans_a, trans_b, "float32") else: c_value = vectormatmul_4d_cast(a_value, b_value, trans_a, trans_b, "float32") else: if len(a_value.shape) == 2: c_value = vectormatmul_2d(a_value, b_value, trans_a, trans_b) elif len(a_value.shape) == 3: c_value = vectormatmul_3d(a_value, b_value, trans_a, trans_b) else: c_value = vectormatmul_4d(a_value, b_value, trans_a, trans_b) dim_info = batchmatmul_no_bias_set_dim(a_value, b_value, trans_a, trans_b) if isinstance(dim_info, (tuple, list)): dim_info = dim_info[0] attrs = {} attrs["enable_compute_in_place"] = True if dim_info != "": attrs["dim"] = dim_info mnk = get_mnk_from_matrix(get_shape(a_value), get_shape(b_value), trans_a, trans_b) batch = get_shape(a_value)[:-2] is_dynamic = ds.shape_is_dynamic([a_value, b_value]) if not is_dynamic: attrs = batchmatmul_tiling_strategy(batch + mnk, c_value.dtype, attrs) else: attrs = batchmatmul_tiling_strategy_dynamic(batch + mnk, c_value, attrs) attrs["enable_pre_storage_write_simplify"] = True attrs["enable_sink_allocate"] = True attrs["enable_double_buffer"] = False return c_value, attrs
def BatchMatMul(a_value, b_value, trans_a=False, trans_b=False, target=utils.CCE): """ Multiplies two tensors in batches. Args: a_value (tvm.tensor.Tensor): 2D or 3D or 4D tensor of type float16 or float32 with shape(..., r_A, c_A). b_value (tvm.tensor.Tensor): 2D or 3D or 4D tensor of same type as a_value with shape(..., r_B, c_B). trans_a (bool): Specifies whether a_value is transposed or not, default value is False. trans_b (bool): Specifies whether b_value is transposed or not, default value is False. Returns: tvm.tensor.Tensor of same type as a_value with shape(..., r_C, c_C). r_C = c_A if trans_a else r_A c_C = r_B if trans_b else c_B Supported Platforms: 'Ascend' """ if not isinstance(trans_a, bool): raise TypeError("trans_a should be of type Boolean.") if not isinstance(trans_b, bool): raise TypeError("trans_b should be of type Boolean.") utils.ops_dtype_check([a_value.dtype, b_value.dtype], utils.DtypeForDavinci.ALL_FLOAT) utils.elemwise_dtype_check(a_value.dtype, b_value.dtype) utils.gemm_format_check(get_shape(a_value), get_shape(b_value), trans_a, trans_b) if len(a_value.shape) not in [2, 3, 4]: raise ValueError("Batch matmul only support 2D, 3D and 4D now.") dtype = a_value.dtype if dtype == 'float16': if len(a_value.shape) == 2: c_value = vectormatmul_2d_cast(a_value, b_value, trans_a, trans_b, "float32") elif len(a_value.shape) == 3: c_value = vectormatmul_3d_cast(a_value, b_value, trans_a, trans_b, "float32") else: c_value = vectormatmul_4d_cast(a_value, b_value, trans_a, trans_b, "float32") else: if len(a_value.shape) == 2: c_value = vectormatmul_2d(a_value, b_value, trans_a, trans_b) elif len(a_value.shape) == 3: c_value = vectormatmul_3d(a_value, b_value, trans_a, trans_b) else: c_value = vectormatmul_4d(a_value, b_value, trans_a, trans_b) dim_info = batchmatmul_no_bias_set_dim(a_value, b_value, trans_a, trans_b) if isinstance(dim_info, (tuple, list)): dim_info = dim_info[0] attrs = {} attrs["enable_compute_in_place"] = True if dim_info != "": attrs["dim"] = dim_info mnk = get_mnk_from_matrix(get_shape(a_value), get_shape(b_value), trans_a, trans_b) batch = get_shape(a_value)[:-2] is_dynamic = ds.shape_is_dynamic([a_value, b_value]) if not is_dynamic: attrs = batchmatmul_tiling_strategy(batch + mnk, c_value.dtype, attrs) else: attrs = batchmatmul_tiling_strategy_dynamic(batch + mnk, c_value, attrs) attrs["enable_pre_storage_write_simplify"] = True attrs["enable_sink_allocate"] = True attrs["enable_double_buffer"] = False return c_value, attrs
Python
def reduction_layer(data, axis, op, coeff): """ Reduce data on axis and scale by coeff. Args: data (tvm.tensor.Tensor): tensor with type float16 or float32, int8, uint8. axis (int): the beginning axis to reduce, -1 means the last axis. if 0, reduction to scalar. op (str): one of "SUM", "ASUM"(abs and sum), "SUMSQ"(sqr and sum), "MEAN". coeff ([int, float]): scale Returns: tvm.tensor.Tensor. """ dtype = data.dtype utils.ops_dtype_check(data.dtype, [utils.DtypeForDavinci.ALL_FLOAT, utils.DtypeForDavinci.INT8, utils.DtypeForDavinci.UINT8]) utils.check_shape(data.shape) if op not in ["SUM", "ASUM", "SUMSQ", "MEAN"]: raise RuntimeError("op can only be one of SUM, ASUM, SUMSQ, MEAN") shape = get_shape(data) utils.reduce_axis_check(shape, axis) axis = _get_axis_list(axis, shape) if dtype in ["int8", "uint8"]: data = topi.cast(data, "float16") data = topi.cast(data, "float32") cof = tvm.const(coeff, "float32") if op == "ASUM": tmp = _asum(data, axis, cof) elif op == "SUMSQ": tmp =_sumsq(data, axis, cof) elif op == "MEAN": tmp = _mean(data, axis, cof, shape) elif op == "SUM": tmp = _sum(data, axis, cof) if dtype in ["int8", "uint8"]: tmp = topi.cast(tmp, "float16") res = topi.cast(tmp, dtype) return res
def reduction_layer(data, axis, op, coeff): """ Reduce data on axis and scale by coeff. Args: data (tvm.tensor.Tensor): tensor with type float16 or float32, int8, uint8. axis (int): the beginning axis to reduce, -1 means the last axis. if 0, reduction to scalar. op (str): one of "SUM", "ASUM"(abs and sum), "SUMSQ"(sqr and sum), "MEAN". coeff ([int, float]): scale Returns: tvm.tensor.Tensor. """ dtype = data.dtype utils.ops_dtype_check(data.dtype, [utils.DtypeForDavinci.ALL_FLOAT, utils.DtypeForDavinci.INT8, utils.DtypeForDavinci.UINT8]) utils.check_shape(data.shape) if op not in ["SUM", "ASUM", "SUMSQ", "MEAN"]: raise RuntimeError("op can only be one of SUM, ASUM, SUMSQ, MEAN") shape = get_shape(data) utils.reduce_axis_check(shape, axis) axis = _get_axis_list(axis, shape) if dtype in ["int8", "uint8"]: data = topi.cast(data, "float16") data = topi.cast(data, "float32") cof = tvm.const(coeff, "float32") if op == "ASUM": tmp = _asum(data, axis, cof) elif op == "SUMSQ": tmp =_sumsq(data, axis, cof) elif op == "MEAN": tmp = _mean(data, axis, cof, shape) elif op == "SUM": tmp = _sum(data, axis, cof) if dtype in ["int8", "uint8"]: tmp = topi.cast(tmp, "float16") res = topi.cast(tmp, dtype) return res
Python
def normal_diag_sample_ad(head, mean, scale, eps): """ An example of differentiating normal_diag.sample in all inputs and paramters Args: head: The adjoint of the output, in other words, some tensors, by which the Jacobians will be multiplied x: input mean: vector of means of MVN scale: vector of sigma of MVN with diagonal covariance """ mod = normal_diag.normal_diag(mean, scale).sample(eps) auto_diff_outs = list(akg.differentiate(mod, [mean, scale], head)) return auto_diff_outs
def normal_diag_sample_ad(head, mean, scale, eps): """ An example of differentiating normal_diag.sample in all inputs and paramters Args: head: The adjoint of the output, in other words, some tensors, by which the Jacobians will be multiplied x: input mean: vector of means of MVN scale: vector of sigma of MVN with diagonal covariance """ mod = normal_diag.normal_diag(mean, scale).sample(eps) auto_diff_outs = list(akg.differentiate(mod, [mean, scale], head)) return auto_diff_outs
Python
def apply_adadelta(var, accum, accum_update, grad, lr, rho, epsilon, target=utils.CCE): """ Update var according to the adadelta scheme. accum = rho * accum + (1 - rho) * grad^2 update = sqrt(accum_update + epsilon).sqrt() / sqrt(accum + epsilon) * grad accum_update = rho * accum_update + (1 - rho) * update^2 var -= update * lr Args: var (tvm.tensor.Tensor): The tensor to be updated. Should be float32. accum (tvm.tensor.Tensor): The accumulate gradient, a tensor of same shape and type as var. accum_update (tvm.tensor.Tensor): The accumulate updates, tensor of same shape and type as var. grad (tvm.tensor.Tensor): A tensor of same shape and type as var. lr (tvm.tensor.Tensor): Learning rate, a scalar tensor of same type as var. rho (tvm.tensor.Tensor): Coefficient for calculate new accum, 0.0 <= rho <= 1.0. epsilon (float): A small value to prevent division by 0. Returns: tvm.tensor.Tensor, Updated var. tvm.tensor.Tensor, Updated accum. tvm.tensor.Tensor, Updated accum_update. """ _check_inputs(var, accum, accum_update, grad, lr, rho, epsilon) out_var, out_accum, out_accum_update = _apply_adadelta_compute(var, accum, accum_update, grad, lr, rho, epsilon) # reuse var, accum and accum_update out_var, binds_info = TensorUtils.inplace_set(var, out_var, "var_buf") out_accum, binds_info2 = TensorUtils.inplace_set(accum, out_accum, "accum_buf") out_accum_update, binds_info3 = TensorUtils.inplace_set(accum_update, out_accum_update, "accum_update_buf") binds_info.update(binds_info2) binds_info.update(binds_info3) attrs = {utils.BINDS: binds_info} return out_var, out_accum, out_accum_update, attrs
def apply_adadelta(var, accum, accum_update, grad, lr, rho, epsilon, target=utils.CCE): """ Update var according to the adadelta scheme. accum = rho * accum + (1 - rho) * grad^2 update = sqrt(accum_update + epsilon).sqrt() / sqrt(accum + epsilon) * grad accum_update = rho * accum_update + (1 - rho) * update^2 var -= update * lr Args: var (tvm.tensor.Tensor): The tensor to be updated. Should be float32. accum (tvm.tensor.Tensor): The accumulate gradient, a tensor of same shape and type as var. accum_update (tvm.tensor.Tensor): The accumulate updates, tensor of same shape and type as var. grad (tvm.tensor.Tensor): A tensor of same shape and type as var. lr (tvm.tensor.Tensor): Learning rate, a scalar tensor of same type as var. rho (tvm.tensor.Tensor): Coefficient for calculate new accum, 0.0 <= rho <= 1.0. epsilon (float): A small value to prevent division by 0. Returns: tvm.tensor.Tensor, Updated var. tvm.tensor.Tensor, Updated accum. tvm.tensor.Tensor, Updated accum_update. """ _check_inputs(var, accum, accum_update, grad, lr, rho, epsilon) out_var, out_accum, out_accum_update = _apply_adadelta_compute(var, accum, accum_update, grad, lr, rho, epsilon) # reuse var, accum and accum_update out_var, binds_info = TensorUtils.inplace_set(var, out_var, "var_buf") out_accum, binds_info2 = TensorUtils.inplace_set(accum, out_accum, "accum_buf") out_accum_update, binds_info3 = TensorUtils.inplace_set(accum_update, out_accum_update, "accum_update_buf") binds_info.update(binds_info2) binds_info.update(binds_info3) attrs = {utils.BINDS: binds_info} return out_var, out_accum, out_accum_update, attrs
Python
def collect_subtensors_by_name(tensor, name, result): """ find all the subtensors with names matched the pattern `name`. Args: tensor: An input tensor. name: the `name` pattern to be matched. result: list of all subtensors found with name matched. Returns: list of all subtensors found with name matched. """ for child in tensor.op.input_tensors: child_result = collect_by_name(child, name, result) result.extend(child_result) if tensor.op.name.find(name) != -1: result.append([tensor]) return result
def collect_subtensors_by_name(tensor, name, result): """ find all the subtensors with names matched the pattern `name`. Args: tensor: An input tensor. name: the `name` pattern to be matched. result: list of all subtensors found with name matched. Returns: list of all subtensors found with name matched. """ for child in tensor.op.input_tensors: child_result = collect_by_name(child, name, result) result.extend(child_result) if tensor.op.name.find(name) != -1: result.append([tensor]) return result
Python
def register_variables(name, input, output): """register variables as a dictionary.""" if not isinstance(name, str): raise ValueError("key {} is not str.".format(name)) variable_map[name] = [output, input]
def register_variables(name, input, output): """register variables as a dictionary.""" if not isinstance(name, str): raise ValueError("key {} is not str.".format(name)) variable_map[name] = [output, input]
Python
def differentiate(output, inputs=None, head=None, ad_attrs=None, new_pld_array=None, override=None, fdiff=None): """ Perform operator-level automatic differentiation. Args: output (tvm.tensor.Tensor): The tensor to differentiate. inputs (list[tvm.tensor.Tensor]): The list of input tensors. When the list is empty or None, will perform differentiation with respect to all tensors the output depends on (i.e. will compute all adjoints and populate the corresponding dict, but the list of results will be empty). Default: None. head (tvm.tensor.Tensor): The adjoint of the output. in other words, some tensors, by which the Jacobians will be multiplied. Its shape must be of the form `prefix + output.shape`. For example, if the shape of `output` is (2, 3), the shape of `head` could be (2, 3), (?, 2, 3) and etc. If `None` is passed, the identity tensor of shape `output.shape + output.shape` will be used. Default: None. ad_attrs (dict): The additional attributes for the auto-differentiate computation. Default: None. new_pld_array (list): List of additional variables which could be used in differentiation. Default: None. override (dict): A dictionary to override differentiation for certain tensors. Override is a dictionary with types: {tvm.tensor.Tensor: (list[tvm.tensor.Tensor], callable[tvm.tensor.Tensor, list[tvm.tensor.Tensor], tvm.tensor.Tensor, list[tvm.tensor.Tensor]])}. This dict maps tensors `t` to pairs `(dependencies, custom_diff)` where `dependencies` is a list of tensors which are considered to be inputs of `t` (which may differ from the immediate inputs), and `custom_diff` is a custom differentiation function which will be called as `custom_diff(t, dependencies, adjoint, new_pld_array)` and should return a list of adjoints corresponding to dependencies. Note that this function differs from the one required for `fdiff` in that it takes a list of inputs instead of a single input and returns a list of adjoints instead of a single adjoint. Default: None. fdiff (callable[tvm.tensor.Tensor, tvm.tensor.Tensor, tvm.tensor.Tensor, tvm.tensor.Tensor]): The default function performing differentiation and multiplication, by default `akg.autodiff.DiffBuildingBlock` is used. The function must accept parameters: - `output` - an output tensor - `input` - an input tensor - `head` - the adjoint of the output tensor - `ad_attrs` - the additional attributes for the auto-differentiate computation - `new_pld_array` - the additional tensors with information for the auto-differentiate computation The result should be `head` multiplied by the Jacobians of `output` wrt `input`. Default: None. Returns: DifferentiationResult. class DifferentiationResult is used to represent a differentiation result, including: - result (list[tvm.tensor.Tensor]): The requested adjoints, i.e. the Jacobians or gradients of the given output with respect to the given inputs. - adjoints (dict{tvm.tensor.Tensor: tvm.tensor.Tensor}): A dict from tensors to the corresponding adjoints (including internal nodes). - adjoint_summands (dict{tvm.tensor.Tensor: dict{tvm.tensor.Tensor: tvm.tensor.Tensor}}): Single summands of the adjoints. Raises: ValueError: If the shape of `head` is invalid. Examples: >>> x = akg.tvm.placeholder((32, 3, 28, 28), name='x') >>> w1 = akg.tvm.placeholder((10, 3, 3, 3), name='w1') >>> z1 = akg.topi.nn.conv2d(x, w1, 1, 0, 1) >>> z2 = akg.topi.nn.flatten(z1) >>> y = akg.topi.sum(z2) >>> >>> # produce gradients >>> [dw1, dw2] = akg.differentiate(y, [x, w1]) >>> >>> # produce Jacobians >>> [jw1, jw2] = akg.differentiate(z2, [x, w1]) >>> >>> # produce Jacobians, the head adjoint for z2 is provided manually >>> [dw1, dw2] = akg.differentiate(z2, [x, w1], akg.topi.full_like(z2, 1.0)) >>> >>> # produce gradients wrt all inputs >>> res = akg.differentiate(y) >>> dw1 = res.adjoints[x] >>> dw2 = res.adjoints[w1] >>> >>> # a custom differentiation function >>> head = akg.tvm.placeholder((1,), name = 'head') >>> def my_fdiff(out, inp, head, ad_attrs, new_pld_array): >>> return [akg.tvm.compute(inp[0].shape, lambda ax0, ax1, ax2, ax3: head[ax0, ax3 + ax2*26 + ax1*676])] >>> >>> # using a custom differentiation function only for z2 >>> res = akg.differentiate(y, [x, w1], head, None, None, override={z2: ([z1], my_fdiff)}) """ # check whether head shape is compatible with output shape. if head is not None: output_shape = get_shape(output) head_shape = get_shape(head) output_dim = len(output_shape) head_last_shape = head_shape[-output_dim:] if head_last_shape != output_shape: raise ValueError("operands could not be broadcast together with head shape %s and output shape %s" % (str(head_shape), str(output_shape))) if inputs is None: inputs = [] if override is not None: override_deps = [] if fdiff is None: fdiff = DiffBuildingBlock if override is not None: def modified_fdiff(out, inp, head, ad_attrs, new_pld_array, override=override, old_fdiff=fdiff, cache=None): if cache is None: cache = {} if out in override: if (out, head) not in cache: cache[(out, head)] = override[out][1](out, override[out][0], head, ad_attrs, new_pld_array) idx = override[out][0].index(inp) return cache[(out, head)][idx] return old_fdiff(out, inp, head, ad_attrs, new_pld_array) fdiff = modified_fdiff override_deps = {t: deps for t, (deps, _) in override.items()} return akg.autodiff.Differentiate(output, inputs, head, ad_attrs, None, fdiff, override_deps) if new_pld_array is None: return akg.autodiff.Differentiate(output, inputs, head, ad_attrs, [], fdiff) return akg.autodiff.Differentiate(output, inputs, head, ad_attrs, new_pld_array, fdiff)
def differentiate(output, inputs=None, head=None, ad_attrs=None, new_pld_array=None, override=None, fdiff=None): """ Perform operator-level automatic differentiation. Args: output (tvm.tensor.Tensor): The tensor to differentiate. inputs (list[tvm.tensor.Tensor]): The list of input tensors. When the list is empty or None, will perform differentiation with respect to all tensors the output depends on (i.e. will compute all adjoints and populate the corresponding dict, but the list of results will be empty). Default: None. head (tvm.tensor.Tensor): The adjoint of the output. in other words, some tensors, by which the Jacobians will be multiplied. Its shape must be of the form `prefix + output.shape`. For example, if the shape of `output` is (2, 3), the shape of `head` could be (2, 3), (?, 2, 3) and etc. If `None` is passed, the identity tensor of shape `output.shape + output.shape` will be used. Default: None. ad_attrs (dict): The additional attributes for the auto-differentiate computation. Default: None. new_pld_array (list): List of additional variables which could be used in differentiation. Default: None. override (dict): A dictionary to override differentiation for certain tensors. Override is a dictionary with types: {tvm.tensor.Tensor: (list[tvm.tensor.Tensor], callable[tvm.tensor.Tensor, list[tvm.tensor.Tensor], tvm.tensor.Tensor, list[tvm.tensor.Tensor]])}. This dict maps tensors `t` to pairs `(dependencies, custom_diff)` where `dependencies` is a list of tensors which are considered to be inputs of `t` (which may differ from the immediate inputs), and `custom_diff` is a custom differentiation function which will be called as `custom_diff(t, dependencies, adjoint, new_pld_array)` and should return a list of adjoints corresponding to dependencies. Note that this function differs from the one required for `fdiff` in that it takes a list of inputs instead of a single input and returns a list of adjoints instead of a single adjoint. Default: None. fdiff (callable[tvm.tensor.Tensor, tvm.tensor.Tensor, tvm.tensor.Tensor, tvm.tensor.Tensor]): The default function performing differentiation and multiplication, by default `akg.autodiff.DiffBuildingBlock` is used. The function must accept parameters: - `output` - an output tensor - `input` - an input tensor - `head` - the adjoint of the output tensor - `ad_attrs` - the additional attributes for the auto-differentiate computation - `new_pld_array` - the additional tensors with information for the auto-differentiate computation The result should be `head` multiplied by the Jacobians of `output` wrt `input`. Default: None. Returns: DifferentiationResult. class DifferentiationResult is used to represent a differentiation result, including: - result (list[tvm.tensor.Tensor]): The requested adjoints, i.e. the Jacobians or gradients of the given output with respect to the given inputs. - adjoints (dict{tvm.tensor.Tensor: tvm.tensor.Tensor}): A dict from tensors to the corresponding adjoints (including internal nodes). - adjoint_summands (dict{tvm.tensor.Tensor: dict{tvm.tensor.Tensor: tvm.tensor.Tensor}}): Single summands of the adjoints. Raises: ValueError: If the shape of `head` is invalid. Examples: >>> x = akg.tvm.placeholder((32, 3, 28, 28), name='x') >>> w1 = akg.tvm.placeholder((10, 3, 3, 3), name='w1') >>> z1 = akg.topi.nn.conv2d(x, w1, 1, 0, 1) >>> z2 = akg.topi.nn.flatten(z1) >>> y = akg.topi.sum(z2) >>> >>> # produce gradients >>> [dw1, dw2] = akg.differentiate(y, [x, w1]) >>> >>> # produce Jacobians >>> [jw1, jw2] = akg.differentiate(z2, [x, w1]) >>> >>> # produce Jacobians, the head adjoint for z2 is provided manually >>> [dw1, dw2] = akg.differentiate(z2, [x, w1], akg.topi.full_like(z2, 1.0)) >>> >>> # produce gradients wrt all inputs >>> res = akg.differentiate(y) >>> dw1 = res.adjoints[x] >>> dw2 = res.adjoints[w1] >>> >>> # a custom differentiation function >>> head = akg.tvm.placeholder((1,), name = 'head') >>> def my_fdiff(out, inp, head, ad_attrs, new_pld_array): >>> return [akg.tvm.compute(inp[0].shape, lambda ax0, ax1, ax2, ax3: head[ax0, ax3 + ax2*26 + ax1*676])] >>> >>> # using a custom differentiation function only for z2 >>> res = akg.differentiate(y, [x, w1], head, None, None, override={z2: ([z1], my_fdiff)}) """ # check whether head shape is compatible with output shape. if head is not None: output_shape = get_shape(output) head_shape = get_shape(head) output_dim = len(output_shape) head_last_shape = head_shape[-output_dim:] if head_last_shape != output_shape: raise ValueError("operands could not be broadcast together with head shape %s and output shape %s" % (str(head_shape), str(output_shape))) if inputs is None: inputs = [] if override is not None: override_deps = [] if fdiff is None: fdiff = DiffBuildingBlock if override is not None: def modified_fdiff(out, inp, head, ad_attrs, new_pld_array, override=override, old_fdiff=fdiff, cache=None): if cache is None: cache = {} if out in override: if (out, head) not in cache: cache[(out, head)] = override[out][1](out, override[out][0], head, ad_attrs, new_pld_array) idx = override[out][0].index(inp) return cache[(out, head)][idx] return old_fdiff(out, inp, head, ad_attrs, new_pld_array) fdiff = modified_fdiff override_deps = {t: deps for t, (deps, _) in override.items()} return akg.autodiff.Differentiate(output, inputs, head, ad_attrs, None, fdiff, override_deps) if new_pld_array is None: return akg.autodiff.Differentiate(output, inputs, head, ad_attrs, [], fdiff) return akg.autodiff.Differentiate(output, inputs, head, ad_attrs, new_pld_array, fdiff)
Python
def cos_ad(head, a, target="cce"): """ Computes cosine derivative value of a tensor. Args: head (tvm,tensor.Tensor): Tensor of type float16, float32 a (tvm,tensor.Tensor): Tensor of type float16, float32 Returns: akg.tvm.Tensor of same type and shape as inputs """ b, attr = cos.cos(a) jacs = list(akg.differentiate(b, [a], head)) return jacs[0], attr
def cos_ad(head, a, target="cce"): """ Computes cosine derivative value of a tensor. Args: head (tvm,tensor.Tensor): Tensor of type float16, float32 a (tvm,tensor.Tensor): Tensor of type float16, float32 Returns: akg.tvm.Tensor of same type and shape as inputs """ b, attr = cos.cos(a) jacs = list(akg.differentiate(b, [a], head)) return jacs[0], attr
Python
def onehot_tiling_strategy(tensor, axis): """Custom tiling strategy for onehot op.""" tot_axis = ct_util.create_constraint_on_tensor(tensor=tensor, values=0, constraints=ct_util.TileConstraint.SET_PRIORITY, tensor_pos=axis) return tot_axis
def onehot_tiling_strategy(tensor, axis): """Custom tiling strategy for onehot op.""" tot_axis = ct_util.create_constraint_on_tensor(tensor=tensor, values=0, constraints=ct_util.TileConstraint.SET_PRIORITY, tensor_pos=axis) return tot_axis
Python
def OneHot(indices, depth, dtype, on_value=None, off_value=None, axis=None, target=utils.CCE): """ generate the one-hot code for input indices Args: indices (tvm.tensor.Tensor): defining the input data. depth (int): defining the depth of the one hot dimension. dtype (String): "float16" or "float32" or "int" or "int32". on_value (Scalar): optional. defining the value to fill in the output if indices[i] == j. default 1. off_value (Scalar): optional. defining the value to fill in the output if indices[i] != j. default 0. axis (int): optional. The axis to fill. default -1, that means a new inner-most axis. attrs (dict): optional. Dictionary provide tiling information for poly. kernel_name (String): optional. the name of the kernel that will be generated. Returns: akg.tvm.module. A module that combines both host and device code. Supported Platforms: 'Ascend' """ utils.ops_dtype_check([indices.dtype, dtype], utils.DtypeForDavinci.INT32.value + utils.DtypeForDavinci.ALL_FLOAT.value) shape = [x.value for x in indices.shape] utils.check_shape(shape) # Tensor of tensor do not support tensor with more than 3 dimensions for now if len(shape) > 3: raise RuntimeError("one_hot do not support input shape %d dimensions which is more than 3" % len(shape)) on_value_const = akg.tvm.const(1, dtype) if on_value is None else akg.tvm.const(on_value, dtype) off_value_const = akg.tvm.const(0, dtype) if off_value is None else akg.tvm.const(off_value, dtype) if axis is None: axis = -1 if axis == -1: axis = len(shape) if axis <= -2 or axis > len(shape): raise RuntimeError("axis(%s) is not an valid index" % axis) in_shape = [x for x in indices.shape] in_shape.insert(axis, depth) out_shape = tuple(in_shape) @script def one_hot_hybrid_1(indices_in, on_value_const_in, off_value_const_in): out = output_tensor(out_shape, on_value_const_in.dtype) m, n = out_shape for i in range(m): for j in range(n): out[i, j] = off_value_const_in if axis == 0: for i in range(n): if indices_in[i] >= 0: out[indices_in[i], i] = on_value_const_in else: for i in range(m): if indices_in[i] >= 0: out[i, indices_in[i]] = on_value_const_in return out @script def one_hot_hybrid_2(indices_in, on_value_const_in, off_value_const_in): out = output_tensor(out_shape, on_value_const_in.dtype) m, n, k = out.shape for x in range(m): for y in range(n): for z in range(k): out[x, y, z] = off_value_const_in if axis == 0: for i in range(n): for j in range(k): if indices_in[i, j] >= 0: out[indices_in[i, j], i, j] = on_value_const_in elif axis == 1: for i in range(m): for j in range(k): if indices_in[i, j] >= 0: out[i, indices_in[i, j], j] = on_value_const_in else: for i in range(m): for j in range(n): if indices_in[i, j] >= 0: out[i, j, indices_in[i, j]] = on_value_const_in return out @script def one_hot_hybrid_3(indices_in, on_value_const_in, off_value_const_in): out = output_tensor(out_shape, on_value_const_in.dtype) m, n, k, t = out.shape for x in range(m): for y in range(n): for z in range(k): for u in range(t): out[x, y, z, u] = off_value_const_in if axis == 0: for i in range(n): for j in range(k): for c in range(t): if indices_in[i, j, c] >= 0: out[indices_in[i, j, c], i, j, c] = on_value_const_in elif axis == 1: for i in range(m): for j in range(k): for c in range(t): if indices_in[i, j, c] >= 0: out[i, indices_in[i, j, c], j, c] = on_value_const_in elif axis == 2: for i in range(m): for j in range(n): for c in range(t): if indices_in[i, j, c] >= 0: out[i, j, indices_in[i, j, c], c] = on_value_const_in else: for i in range(m): for j in range(n): for c in range(k): if indices_in[i, j, c] >= 0: out[i, j, c, indices_in[i, j, c]] = on_value_const_in return out if len(shape) == 1: out = one_hot_hybrid_1(indices, on_value_const, off_value_const) elif len(shape) == 2: out = one_hot_hybrid_2(indices, on_value_const, off_value_const) elif len(shape) == 3: out = one_hot_hybrid_3(indices, on_value_const, off_value_const) strategy = onehot_tiling_strategy(out, axis) attr_map = {"RewriteVarTensorIdx": True} if strategy: attr_map["custom_tiling"] = strategy return out, attr_map
def OneHot(indices, depth, dtype, on_value=None, off_value=None, axis=None, target=utils.CCE): """ generate the one-hot code for input indices Args: indices (tvm.tensor.Tensor): defining the input data. depth (int): defining the depth of the one hot dimension. dtype (String): "float16" or "float32" or "int" or "int32". on_value (Scalar): optional. defining the value to fill in the output if indices[i] == j. default 1. off_value (Scalar): optional. defining the value to fill in the output if indices[i] != j. default 0. axis (int): optional. The axis to fill. default -1, that means a new inner-most axis. attrs (dict): optional. Dictionary provide tiling information for poly. kernel_name (String): optional. the name of the kernel that will be generated. Returns: akg.tvm.module. A module that combines both host and device code. Supported Platforms: 'Ascend' """ utils.ops_dtype_check([indices.dtype, dtype], utils.DtypeForDavinci.INT32.value + utils.DtypeForDavinci.ALL_FLOAT.value) shape = [x.value for x in indices.shape] utils.check_shape(shape) # Tensor of tensor do not support tensor with more than 3 dimensions for now if len(shape) > 3: raise RuntimeError("one_hot do not support input shape %d dimensions which is more than 3" % len(shape)) on_value_const = akg.tvm.const(1, dtype) if on_value is None else akg.tvm.const(on_value, dtype) off_value_const = akg.tvm.const(0, dtype) if off_value is None else akg.tvm.const(off_value, dtype) if axis is None: axis = -1 if axis == -1: axis = len(shape) if axis <= -2 or axis > len(shape): raise RuntimeError("axis(%s) is not an valid index" % axis) in_shape = [x for x in indices.shape] in_shape.insert(axis, depth) out_shape = tuple(in_shape) @script def one_hot_hybrid_1(indices_in, on_value_const_in, off_value_const_in): out = output_tensor(out_shape, on_value_const_in.dtype) m, n = out_shape for i in range(m): for j in range(n): out[i, j] = off_value_const_in if axis == 0: for i in range(n): if indices_in[i] >= 0: out[indices_in[i], i] = on_value_const_in else: for i in range(m): if indices_in[i] >= 0: out[i, indices_in[i]] = on_value_const_in return out @script def one_hot_hybrid_2(indices_in, on_value_const_in, off_value_const_in): out = output_tensor(out_shape, on_value_const_in.dtype) m, n, k = out.shape for x in range(m): for y in range(n): for z in range(k): out[x, y, z] = off_value_const_in if axis == 0: for i in range(n): for j in range(k): if indices_in[i, j] >= 0: out[indices_in[i, j], i, j] = on_value_const_in elif axis == 1: for i in range(m): for j in range(k): if indices_in[i, j] >= 0: out[i, indices_in[i, j], j] = on_value_const_in else: for i in range(m): for j in range(n): if indices_in[i, j] >= 0: out[i, j, indices_in[i, j]] = on_value_const_in return out @script def one_hot_hybrid_3(indices_in, on_value_const_in, off_value_const_in): out = output_tensor(out_shape, on_value_const_in.dtype) m, n, k, t = out.shape for x in range(m): for y in range(n): for z in range(k): for u in range(t): out[x, y, z, u] = off_value_const_in if axis == 0: for i in range(n): for j in range(k): for c in range(t): if indices_in[i, j, c] >= 0: out[indices_in[i, j, c], i, j, c] = on_value_const_in elif axis == 1: for i in range(m): for j in range(k): for c in range(t): if indices_in[i, j, c] >= 0: out[i, indices_in[i, j, c], j, c] = on_value_const_in elif axis == 2: for i in range(m): for j in range(n): for c in range(t): if indices_in[i, j, c] >= 0: out[i, j, indices_in[i, j, c], c] = on_value_const_in else: for i in range(m): for j in range(n): for c in range(k): if indices_in[i, j, c] >= 0: out[i, j, c, indices_in[i, j, c]] = on_value_const_in return out if len(shape) == 1: out = one_hot_hybrid_1(indices, on_value_const, off_value_const) elif len(shape) == 2: out = one_hot_hybrid_2(indices, on_value_const, off_value_const) elif len(shape) == 3: out = one_hot_hybrid_3(indices, on_value_const, off_value_const) strategy = onehot_tiling_strategy(out, axis) attr_map = {"RewriteVarTensorIdx": True} if strategy: attr_map["custom_tiling"] = strategy return out, attr_map
Python
def OneHotV2(indices, on_value, off_value, depth, axis=None, target=utils.CCE): """ generate the one-hot code for input indices Args: indices (akg.tvm.tensor.Tensor): defining the input data. on_value (akg.tvm.tensor.Tensor): defining the value to fill in the output if indices[i] == j. off_value (akg.tvm.tensor.Tensor): defining the value to fill in the output if indices[i] != j. depth (int): defining the depth of the one hot dimension. axis (int): optional. The axis to fill. default -1, that means a new inner-most axis. attrs (dict): optional. Dictionary provide tiling information for poly. kernel_name (String): optional. the name of the kernel that will be generated. Returns: akg.tvm.module. A module that combines both host and device code. Supported Platforms: 'Ascend' """ utils.ops_dtype_check(indices.dtype, utils.DtypeForDavinci.INT32) utils.ops_dtype_check([on_value.dtype, off_value.dtype], [utils.DtypeForDavinci.INT32, utils.DtypeForDavinci.ALL_FLOAT]) shape = [x.value for x in indices.shape] utils.check_shape(shape) # OneHot do not support tensor with more than 3 dimensions for now if len(shape) > 3: raise RuntimeError("one_hot do not support input shape %d dimensions which is more than 3" % len(shape)) if axis is None: axis = -1 if axis == -1: axis = len(shape) if axis <= -2 or axis > len(shape): raise RuntimeError("axis(%s) is not an valid index" % axis) in_shape = [x for x in indices.shape] in_shape.insert(axis, depth) out_shape = tuple(in_shape) @script def one_hot_hybrid_1(indices_in, on_value_const_in, off_value_const_in): out = output_tensor(out_shape, on_value_const_in.dtype) m, n = out_shape for i in range(m): for j in range(n): out[i, j] = off_value_const_in[0] if axis == 0: for i in range(n): if indices_in[i] >= 0: out[indices_in[i], i] = on_value_const_in[0] else: for i in range(m): if indices_in[i] >= 0: out[i, indices_in[i]] = on_value_const_in[0] return out @script def one_hot_hybrid_2(indices_in, on_value_const_in, off_value_const_in): out = output_tensor(out_shape, on_value_const_in.dtype) m, n, k = out.shape for x in range(m): for y in range(n): for z in range(k): out[x, y, z] = off_value_const_in[0] if axis == 0: for i in range(n): for j in range(k): if indices_in[i, j] >= 0: out[indices_in[i, j], i, j] = on_value_const_in[0] elif axis == 1: for i in range(m): for j in range(k): if indices_in[i, j] >= 0: out[i, indices_in[i, j], j] = on_value_const_in[0] else: for i in range(m): for j in range(n): if indices_in[i, j] >= 0: out[i, j, indices_in[i, j]] = on_value_const_in[0] return out @script def one_hot_hybrid_3(indices_in, on_value_const_in, off_value_const_in): out = output_tensor(out_shape, on_value_const_in.dtype) m, n, k, t = out.shape for x in range(m): for y in range(n): for z in range(k): for u in range(t): out[x, y, z, u] = off_value_const_in[0] if axis == 0: for i in range(n): for j in range(k): for c in range(t): if indices_in[i, j, c] >= 0: out[indices_in[i, j, c], i, j, c] = on_value_const_in[0] elif axis == 1: for i in range(m): for j in range(k): for c in range(t): if indices_in[i, j, c] >= 0: out[i, indices_in[i, j, c], j, c] = on_value_const_in[0] elif axis == 2: for i in range(m): for j in range(n): for c in range(t): if indices_in[i, j, c] >= 0: out[i, j, indices_in[i, j, c], c] = on_value_const_in[0] else: for i in range(m): for j in range(n): for c in range(k): if indices_in[i, j, c] >= 0: out[i, j, c, indices_in[i, j, c]] = on_value_const_in[0] return out if len(shape) == 1: out = one_hot_hybrid_1(indices, on_value, off_value) elif len(shape) == 2: out = one_hot_hybrid_2(indices, on_value, off_value) elif len(shape) == 3: out = one_hot_hybrid_3(indices, on_value, off_value) strategy = onehot_tiling_strategy(out, axis) attr_map = {"RewriteVarTensorIdx": True} if strategy: attr_map["custom_tiling"] = strategy return out, attr_map
def OneHotV2(indices, on_value, off_value, depth, axis=None, target=utils.CCE): """ generate the one-hot code for input indices Args: indices (akg.tvm.tensor.Tensor): defining the input data. on_value (akg.tvm.tensor.Tensor): defining the value to fill in the output if indices[i] == j. off_value (akg.tvm.tensor.Tensor): defining the value to fill in the output if indices[i] != j. depth (int): defining the depth of the one hot dimension. axis (int): optional. The axis to fill. default -1, that means a new inner-most axis. attrs (dict): optional. Dictionary provide tiling information for poly. kernel_name (String): optional. the name of the kernel that will be generated. Returns: akg.tvm.module. A module that combines both host and device code. Supported Platforms: 'Ascend' """ utils.ops_dtype_check(indices.dtype, utils.DtypeForDavinci.INT32) utils.ops_dtype_check([on_value.dtype, off_value.dtype], [utils.DtypeForDavinci.INT32, utils.DtypeForDavinci.ALL_FLOAT]) shape = [x.value for x in indices.shape] utils.check_shape(shape) # OneHot do not support tensor with more than 3 dimensions for now if len(shape) > 3: raise RuntimeError("one_hot do not support input shape %d dimensions which is more than 3" % len(shape)) if axis is None: axis = -1 if axis == -1: axis = len(shape) if axis <= -2 or axis > len(shape): raise RuntimeError("axis(%s) is not an valid index" % axis) in_shape = [x for x in indices.shape] in_shape.insert(axis, depth) out_shape = tuple(in_shape) @script def one_hot_hybrid_1(indices_in, on_value_const_in, off_value_const_in): out = output_tensor(out_shape, on_value_const_in.dtype) m, n = out_shape for i in range(m): for j in range(n): out[i, j] = off_value_const_in[0] if axis == 0: for i in range(n): if indices_in[i] >= 0: out[indices_in[i], i] = on_value_const_in[0] else: for i in range(m): if indices_in[i] >= 0: out[i, indices_in[i]] = on_value_const_in[0] return out @script def one_hot_hybrid_2(indices_in, on_value_const_in, off_value_const_in): out = output_tensor(out_shape, on_value_const_in.dtype) m, n, k = out.shape for x in range(m): for y in range(n): for z in range(k): out[x, y, z] = off_value_const_in[0] if axis == 0: for i in range(n): for j in range(k): if indices_in[i, j] >= 0: out[indices_in[i, j], i, j] = on_value_const_in[0] elif axis == 1: for i in range(m): for j in range(k): if indices_in[i, j] >= 0: out[i, indices_in[i, j], j] = on_value_const_in[0] else: for i in range(m): for j in range(n): if indices_in[i, j] >= 0: out[i, j, indices_in[i, j]] = on_value_const_in[0] return out @script def one_hot_hybrid_3(indices_in, on_value_const_in, off_value_const_in): out = output_tensor(out_shape, on_value_const_in.dtype) m, n, k, t = out.shape for x in range(m): for y in range(n): for z in range(k): for u in range(t): out[x, y, z, u] = off_value_const_in[0] if axis == 0: for i in range(n): for j in range(k): for c in range(t): if indices_in[i, j, c] >= 0: out[indices_in[i, j, c], i, j, c] = on_value_const_in[0] elif axis == 1: for i in range(m): for j in range(k): for c in range(t): if indices_in[i, j, c] >= 0: out[i, indices_in[i, j, c], j, c] = on_value_const_in[0] elif axis == 2: for i in range(m): for j in range(n): for c in range(t): if indices_in[i, j, c] >= 0: out[i, j, indices_in[i, j, c], c] = on_value_const_in[0] else: for i in range(m): for j in range(n): for c in range(k): if indices_in[i, j, c] >= 0: out[i, j, c, indices_in[i, j, c]] = on_value_const_in[0] return out if len(shape) == 1: out = one_hot_hybrid_1(indices, on_value, off_value) elif len(shape) == 2: out = one_hot_hybrid_2(indices, on_value, off_value) elif len(shape) == 3: out = one_hot_hybrid_3(indices, on_value, off_value) strategy = onehot_tiling_strategy(out, axis) attr_map = {"RewriteVarTensorIdx": True} if strategy: attr_map["custom_tiling"] = strategy return out, attr_map
Python
def squeeze(data, axis, target="cce"): """ Remove the dimensions which have shape size 1. Args: data: Tensor, input whose shape is to be squeeze. axis: Interger, specify which size 1 dimension to be removed. Return: Tensor, has the same type and element as data, but some size 1 dimensions are removed. """ shape = get_shape(data) if len(shape) == 1: raise RuntimeError("invalid input shape") utils.check_shape(shape) utils.ops_dtype_check(data.dtype, [utils.DtypeForDavinci.ALL_FLOAT, utils.DtypeForDavinci.INT32]) new_shape = [] shape_to_squeeze = [] if axis is None: axis = [i for i, sh in enumerate(shape) if sh == 1] if not isinstance(axis, (list, tuple)): axis = [axis] for i, sh in enumerate(shape): if not isinstance(sh, int) or i not in axis: new_shape.append(sh) shape_to_squeeze.append(True) else: shape_to_squeeze.append(False) def get_old_indices(indices): old_indices = [] new_index = 0 for i, sh in enumerate(shape_to_squeeze): if sh: old_indices.append(indices[new_index]) new_index += 1 else: old_indices.append(0) return old_indices B = akg.tvm.compute(new_shape, lambda *indices: data(*get_old_indices(indices))) return B
def squeeze(data, axis, target="cce"): """ Remove the dimensions which have shape size 1. Args: data: Tensor, input whose shape is to be squeeze. axis: Interger, specify which size 1 dimension to be removed. Return: Tensor, has the same type and element as data, but some size 1 dimensions are removed. """ shape = get_shape(data) if len(shape) == 1: raise RuntimeError("invalid input shape") utils.check_shape(shape) utils.ops_dtype_check(data.dtype, [utils.DtypeForDavinci.ALL_FLOAT, utils.DtypeForDavinci.INT32]) new_shape = [] shape_to_squeeze = [] if axis is None: axis = [i for i, sh in enumerate(shape) if sh == 1] if not isinstance(axis, (list, tuple)): axis = [axis] for i, sh in enumerate(shape): if not isinstance(sh, int) or i not in axis: new_shape.append(sh) shape_to_squeeze.append(True) else: shape_to_squeeze.append(False) def get_old_indices(indices): old_indices = [] new_index = 0 for i, sh in enumerate(shape_to_squeeze): if sh: old_indices.append(indices[new_index]) new_index += 1 else: old_indices.append(0) return old_indices B = akg.tvm.compute(new_shape, lambda *indices: data(*get_old_indices(indices))) return B
Python
def _register_intrin(token, intrin): """Add an intrin into calls dynamically.""" _internal_assert(not hasattr(calls, token), '{} already defined!'.format(token)) _REGISTER_INTRIN.add(token) if isinstance(intrin, _TensorIntrin): setattr(calls, token, intrin) else: setattr(calls, token, lambda func_id, args: intrin(*args))
def _register_intrin(token, intrin): """Add an intrin into calls dynamically.""" _internal_assert(not hasattr(calls, token), '{} already defined!'.format(token)) _REGISTER_INTRIN.add(token) if isinstance(intrin, _TensorIntrin): setattr(calls, token, intrin) else: setattr(calls, token, lambda func_id, args: intrin(*args))
Python
def _unregister_intrin(token): """Remove the intrin added by _register_intrin.""" _internal_assert(token in _REGISTER_INTRIN, '{} not defined!'.format(token)) _REGISTER_INTRIN.remove(token) delattr(calls, token)
def _unregister_intrin(token): """Remove the intrin added by _register_intrin.""" _internal_assert(token in _REGISTER_INTRIN, '{} not defined!'.format(token)) _REGISTER_INTRIN.remove(token) delattr(calls, token)
Python
def _register_intrin_emulate(token, emulate): """Register the emulation of an intrinsic into the hybrid runtime.""" _internal_assert(token not in HYBRID_GLOBALS, '{} already defined!'.format(token)) HYBRID_GLOBALS_INTRINS.add(token) HYBRID_GLOBALS[token] = emulate
def _register_intrin_emulate(token, emulate): """Register the emulation of an intrinsic into the hybrid runtime.""" _internal_assert(token not in HYBRID_GLOBALS, '{} already defined!'.format(token)) HYBRID_GLOBALS_INTRINS.add(token) HYBRID_GLOBALS[token] = emulate
Python
def _unregister_intrin_emulate(token): """Unregister the emulation of an intrinsic into the hybrid runtime.""" _internal_assert(token in HYBRID_GLOBALS_INTRINS, '{} not defined!'.format(token)) HYBRID_GLOBALS_INTRINS.remove(token) del HYBRID_GLOBALS[token]
def _unregister_intrin_emulate(token): """Unregister the emulation of an intrinsic into the hybrid runtime.""" _internal_assert(token in HYBRID_GLOBALS_INTRINS, '{} not defined!'.format(token)) HYBRID_GLOBALS_INTRINS.remove(token) del HYBRID_GLOBALS[token]
Python
def dense_run(batch, in_dim, out_dim, dtype, bias, attrs): """run function for dsl function dense.""" op_attrs = [bias] if 'tuning' in attrs.keys(): t = attrs.get("tuning", False) kernel_name = attrs.get("kernel_name", False) d1 = random_gaussian((batch, in_dim), miu=1, sigma=0.1).astype(dtype) w1 = random_gaussian((out_dim, in_dim), miu=1, sigma=0.1).astype(dtype) w2 = w1.transpose().copy() if bias: b1 = random_gaussian((out_dim), miu=1, sigma=0.1).astype(dtype) mod = utils.op_build_test(dense.dense, [d1.shape, w1.shape, b1.shape], [dtype, dtype, dtype], op_attrs, kernel_name=kernel_name, attrs=attrs, tuning=t) if t: exp_output = np.dot(d1, w2) # inputs and output to hold the data output = np.full(exp_output.shape, np.nan, dtype) for o in range(out_dim): exp_output[:, o] += b1[o] args = [d1, w1, b1, output] return mod, exp_output, args return mod else: mod = utils.op_build_test(dense.dense, [d1.shape, w1.shape], [dtype, dtype], op_attrs, kernel_name=kernel_name, attrs=attrs, tuning=t) if t: exp_output = np.dot(d1, w2) # inputs and output to hold the data output = np.full(exp_output.shape, np.nan, dtype) args = [d1, w1, output] return mod, exp_output, args else: return mod d1 = random_gaussian((batch, in_dim), miu=1, sigma=0.1).astype(dtype) w1 = random_gaussian((out_dim, in_dim), miu=1, sigma=0.1).astype(dtype) w2 = w1.transpose().copy() exp_output = np.dot(d1, w2) # inputs and output to hold the data output = np.full(exp_output.shape, np.nan, dtype) if bias: b1 = random_gaussian((out_dim), miu=1, sigma=0.1).astype(dtype) for o in range(out_dim): exp_output[:, o] += b1[o] inputs = [d1, w1, b1] args = [d1, w1, b1, output] mod = utils.op_build_test(dense.dense, [d1.shape, w1.shape, b1.shape], [dtype, dtype, dtype], op_attrs, kernel_name='dense', attrs=attrs) else: inputs = [d1, w1] args = [d1, w1, output] mod = utils.op_build_test(dense.dense, [d1.shape, w1.shape], [dtype, dtype], op_attrs, kernel_name='dense', attrs=attrs) acu_output = utils.mod_launch(mod, args, expect=exp_output) # compare result compare_result = compare_tensor(acu_output, exp_output, rtol=5e-03, equal_nan=True) return inputs, acu_output, exp_output, compare_result
def dense_run(batch, in_dim, out_dim, dtype, bias, attrs): """run function for dsl function dense.""" op_attrs = [bias] if 'tuning' in attrs.keys(): t = attrs.get("tuning", False) kernel_name = attrs.get("kernel_name", False) d1 = random_gaussian((batch, in_dim), miu=1, sigma=0.1).astype(dtype) w1 = random_gaussian((out_dim, in_dim), miu=1, sigma=0.1).astype(dtype) w2 = w1.transpose().copy() if bias: b1 = random_gaussian((out_dim), miu=1, sigma=0.1).astype(dtype) mod = utils.op_build_test(dense.dense, [d1.shape, w1.shape, b1.shape], [dtype, dtype, dtype], op_attrs, kernel_name=kernel_name, attrs=attrs, tuning=t) if t: exp_output = np.dot(d1, w2) # inputs and output to hold the data output = np.full(exp_output.shape, np.nan, dtype) for o in range(out_dim): exp_output[:, o] += b1[o] args = [d1, w1, b1, output] return mod, exp_output, args return mod else: mod = utils.op_build_test(dense.dense, [d1.shape, w1.shape], [dtype, dtype], op_attrs, kernel_name=kernel_name, attrs=attrs, tuning=t) if t: exp_output = np.dot(d1, w2) # inputs and output to hold the data output = np.full(exp_output.shape, np.nan, dtype) args = [d1, w1, output] return mod, exp_output, args else: return mod d1 = random_gaussian((batch, in_dim), miu=1, sigma=0.1).astype(dtype) w1 = random_gaussian((out_dim, in_dim), miu=1, sigma=0.1).astype(dtype) w2 = w1.transpose().copy() exp_output = np.dot(d1, w2) # inputs and output to hold the data output = np.full(exp_output.shape, np.nan, dtype) if bias: b1 = random_gaussian((out_dim), miu=1, sigma=0.1).astype(dtype) for o in range(out_dim): exp_output[:, o] += b1[o] inputs = [d1, w1, b1] args = [d1, w1, b1, output] mod = utils.op_build_test(dense.dense, [d1.shape, w1.shape, b1.shape], [dtype, dtype, dtype], op_attrs, kernel_name='dense', attrs=attrs) else: inputs = [d1, w1] args = [d1, w1, output] mod = utils.op_build_test(dense.dense, [d1.shape, w1.shape], [dtype, dtype], op_attrs, kernel_name='dense', attrs=attrs) acu_output = utils.mod_launch(mod, args, expect=exp_output) # compare result compare_result = compare_tensor(acu_output, exp_output, rtol=5e-03, equal_nan=True) return inputs, acu_output, exp_output, compare_result
Python
def _compute_mini(data_input, shape): """Use log and taylor to compute""" data_abs = topi.abs(data_input) result_ln = _compute_log(data_abs) result_taylor = _compute_taylor(data_abs) data_abs = topi.cast(data_abs, "float16") data_input = topi.cast(data_input, "float16") result_taylor = topi.cast(result_taylor, "float16") result_ln = topi.cast(result_ln, "float16") # when |x| < 0.5 using taylor computing, and when 0.5<|x|<1 using log() data_res = tvm.compute(shape, lambda *i : akg.tvm.expr.Select(data_abs(*i) < dc.half_const("float16"), result_taylor(*i), result_ln(*i)), name="le") # arctanh(-abs(x)) = -arctanh(abs(x)) data_res_neg = topi.multiply(data_res, dc.neg_one_const("float16")) data_res = tvm.compute(shape, lambda *i : akg.tvm.expr.Select(data_input(*i) < dc.zero_const("float16"), data_res_neg(*i), data_res(*i)), name="neg") return data_res
def _compute_mini(data_input, shape): """Use log and taylor to compute""" data_abs = topi.abs(data_input) result_ln = _compute_log(data_abs) result_taylor = _compute_taylor(data_abs) data_abs = topi.cast(data_abs, "float16") data_input = topi.cast(data_input, "float16") result_taylor = topi.cast(result_taylor, "float16") result_ln = topi.cast(result_ln, "float16") # when |x| < 0.5 using taylor computing, and when 0.5<|x|<1 using log() data_res = tvm.compute(shape, lambda *i : akg.tvm.expr.Select(data_abs(*i) < dc.half_const("float16"), result_taylor(*i), result_ln(*i)), name="le") # arctanh(-abs(x)) = -arctanh(abs(x)) data_res_neg = topi.multiply(data_res, dc.neg_one_const("float16")) data_res = tvm.compute(shape, lambda *i : akg.tvm.expr.Select(data_input(*i) < dc.zero_const("float16"), data_res_neg(*i), data_res(*i)), name="neg") return data_res
Python
def double_fivethou_compare(actual, bench_mark, r_tol=5e-3, equal_nan=True): """ Function for compare result according to double fivethou accuracy. Args: actual: actual. bench_mark: bench_mark. r_tol: Default: 5e-3. equal_nan: Default: True. Returns: res. """ cmp_array = np.isclose(actual, bench_mark, rtol=r_tol, equal_nan=equal_nan) pass_num = cmp_array.astype("int").sum() total_num = np.size(cmp_array) fail_num = total_num - pass_num fail_rate = 1.0 * fail_num / (1.0 * total_num) res = False if fail_rate < 5e-3: print("Failed rate: {0} / {1} = {2}".format(fail_num, total_num, fail_rate)) res = result_compare(actual, bench_mark, r_tol=r_tol) return res
def double_fivethou_compare(actual, bench_mark, r_tol=5e-3, equal_nan=True): """ Function for compare result according to double fivethou accuracy. Args: actual: actual. bench_mark: bench_mark. r_tol: Default: 5e-3. equal_nan: Default: True. Returns: res. """ cmp_array = np.isclose(actual, bench_mark, rtol=r_tol, equal_nan=equal_nan) pass_num = cmp_array.astype("int").sum() total_num = np.size(cmp_array) fail_num = total_num - pass_num fail_rate = 1.0 * fail_num / (1.0 * total_num) res = False if fail_rate < 5e-3: print("Failed rate: {0} / {1} = {2}".format(fail_num, total_num, fail_rate)) res = result_compare(actual, bench_mark, r_tol=r_tol) return res
Python
def TanhGrad(data_y, data_dy, target=utils.CCE): """ Compute the backpropogation gradient of tanh. Args: data_y: Tensor, which equals the output of tanh. data_dy: Tensor, the initial gradients. Return: Tensor, overall gradients. Supported Platforms: 'Ascend' """ dtype=data_y.dtype utils.ops_dtype_check(data_y.dtype, utils.DtypeForDavinci.ALL_FLOAT) shape = [x.value for x in data_y.shape] utils.check_shape(shape) # dx = dy * (1 - y*y) tmp1 = akg.tvm.const(-1, dtype=dtype) tmp2 = akg.tvm.const(1, dtype=dtype) data1_square = akg.lang.ascend.vmul(data_y, data_y) data_tmp = akg.lang.ascend.vmuls(data1_square, tmp1) anuminate = akg.lang.ascend.vadds(data_tmp, tmp2) res = akg.lang.ascend.vmul(anuminate, data_dy) return res
def TanhGrad(data_y, data_dy, target=utils.CCE): """ Compute the backpropogation gradient of tanh. Args: data_y: Tensor, which equals the output of tanh. data_dy: Tensor, the initial gradients. Return: Tensor, overall gradients. Supported Platforms: 'Ascend' """ dtype=data_y.dtype utils.ops_dtype_check(data_y.dtype, utils.DtypeForDavinci.ALL_FLOAT) shape = [x.value for x in data_y.shape] utils.check_shape(shape) # dx = dy * (1 - y*y) tmp1 = akg.tvm.const(-1, dtype=dtype) tmp2 = akg.tvm.const(1, dtype=dtype) data1_square = akg.lang.ascend.vmul(data_y, data_y) data_tmp = akg.lang.ascend.vmuls(data1_square, tmp1) anuminate = akg.lang.ascend.vadds(data_tmp, tmp2) res = akg.lang.ascend.vmul(anuminate, data_dy) return res
Python
def Round(data, target=utils.CCE): """ Round elements of x to nearest integer. Args: data (tvm.tensor.Tensor): Tensor of type float16, float32, int8, unit8, int32. Returns: tvm.tensor.Tensor of same type and shape as data. Supported Platforms: 'Ascend', 'GPU', 'CPU' """ utils.check_supported_target(target) utils.check_shape(data.shape) in_type = data.dtype if target == utils.CCE: if in_type != 'float16': data = akg.tvm.compute(data.shape, lambda *i: data(*i).astype("float16"), name="data_f16") return akg.lang.ascend.round(data) if in_type == 'float16': data = akg.topi.cast(data, 'float32') output = akg.topi.round(data) if in_type == 'float16': output = akg.topi.cast(output, 'float16') return output
def Round(data, target=utils.CCE): """ Round elements of x to nearest integer. Args: data (tvm.tensor.Tensor): Tensor of type float16, float32, int8, unit8, int32. Returns: tvm.tensor.Tensor of same type and shape as data. Supported Platforms: 'Ascend', 'GPU', 'CPU' """ utils.check_supported_target(target) utils.check_shape(data.shape) in_type = data.dtype if target == utils.CCE: if in_type != 'float16': data = akg.tvm.compute(data.shape, lambda *i: data(*i).astype("float16"), name="data_f16") return akg.lang.ascend.round(data) if in_type == 'float16': data = akg.topi.cast(data, 'float32') output = akg.topi.round(data) if in_type == 'float16': output = akg.topi.cast(output, 'float16') return output
Python
def schedule_reduce(outs, grid_dims = 0, block_dims = 0): """Schedule for inject->reduce->bcast ops. Parameters ---------- outs: Array of Tensor The computation graph description of reduce in the format of an array of tensors. Returns ------- sch: Schedule The computation schedule for the op. """ outs = [outs] if isinstance(outs, tvm.tensor.Tensor) else outs sch = tvm.create_schedule([x.op for x in outs]) scheduled_ops = [] for out in outs: scheduled_ops = traverse_after_reduce(out.op, sch, grid_dims, block_dims, scheduled_ops) return sch
def schedule_reduce(outs, grid_dims = 0, block_dims = 0): """Schedule for inject->reduce->bcast ops. Parameters ---------- outs: Array of Tensor The computation graph description of reduce in the format of an array of tensors. Returns ------- sch: Schedule The computation schedule for the op. """ outs = [outs] if isinstance(outs, tvm.tensor.Tensor) else outs sch = tvm.create_schedule([x.op for x in outs]) scheduled_ops = [] for out in outs: scheduled_ops = traverse_after_reduce(out.op, sch, grid_dims, block_dims, scheduled_ops) return sch
Python
def schedule_reduce_autotune(outs): """Autotune Schedule for inject->reduce->bcast ops. Parameters ---------- outs: Array of Tensor The computation graph description of reduce in the format of an array of tensors. Returns ------- sch: Schedule The computation schedule for the op. """ outs = [outs] if isinstance(outs, tvm.tensor.Tensor) else outs sch = tvm.create_schedule([x.op for x in outs]) scheduled_ops = [] for out in outs: scheduled_ops = traverse_after_reduce(out.op, sch, scheduled_ops=scheduled_ops, autotune=True) return sch
def schedule_reduce_autotune(outs): """Autotune Schedule for inject->reduce->bcast ops. Parameters ---------- outs: Array of Tensor The computation graph description of reduce in the format of an array of tensors. Returns ------- sch: Schedule The computation schedule for the op. """ outs = [outs] if isinstance(outs, tvm.tensor.Tensor) else outs sch = tvm.create_schedule([x.op for x in outs]) scheduled_ops = [] for out in outs: scheduled_ops = traverse_after_reduce(out.op, sch, scheduled_ops=scheduled_ops, autotune=True) return sch
Python
def normal_diag_KLdiv_ad(head, mean, scale): """ An example of differentiating normal_diag.KLdiv in all inputs and paramters Args: head: The adjoint of the output, in other words, some tensors, by which the Jacobians will be multiplied x: input mean: vector of means of MVN scale: vector of sigma of MVN with diagonal covariance """ mod = normal_diag.normal_diag(mean, scale).KL_divergence() auto_diff_outs = list(akg.differentiate(mod, [mean, scale], head)) return auto_diff_outs
def normal_diag_KLdiv_ad(head, mean, scale): """ An example of differentiating normal_diag.KLdiv in all inputs and paramters Args: head: The adjoint of the output, in other words, some tensors, by which the Jacobians will be multiplied x: input mean: vector of means of MVN scale: vector of sigma of MVN with diagonal covariance """ mod = normal_diag.normal_diag(mean, scale).KL_divergence() auto_diff_outs = list(akg.differentiate(mod, [mean, scale], head)) return auto_diff_outs
Python
def _reduce_min_max_ascend(data, axis=None, keepdims=False, method="min"): """ Computes the maximum or minimum of elements over a given axis or a list of axes of a tensor. Args: data (tvm.tensor.Tensor): The input tensor to reduce. Should be of type float16, float32, int8, uint8, int32. axis (Union[list, tuple, int, None]): The dimensions to reduce. If None, all dimensions will be reduced. If int or list, must be in the range [-len(data.shape), len(data.shape) - 1]. keepdims (bool): If True, retains reduced dimensions with length 1, default value is False. method (str): Specifies to compute maximum or minimum of input tensor, default value is min. Returns: tvm.tensor.Tensor of same type as input tensor data. """ # check shape utils.check_shape(data.shape) # check type dtype = data.dtype utils.ops_dtype_check(dtype, utils.DtypeForDavinci.ALL_TYPES) # check axis shape_len = len(data.shape) if axis is None: axis = range(shape_len) if hasattr(axis, 'index'): axis = list(axis) if isinstance(axis, int): axis = [axis] utils.is_valid_reduce_axis(data, axis) refined_axis = refine_reduce_axis(data, axis) if len(set(refined_axis)) == len(data.shape) and not keepdims: raise ValueError("When reducing on all axes of input, keepdim should be set to True.") # check method method_list = ["min", "max"] if method not in method_list: raise ValueError("supported method %s while given method is %s" % (",".join(method_list), method)) # In the emit_insn pass, for vmin and vmax, reduce_last_axis only support float16. if dtype != "float16": data = Cast(data, "float16", target="cce") if method == "min": res = akg.topi.min(data, axis=axis, keepdims=keepdims) else: res = akg.topi.max(data, axis=axis, keepdims=keepdims) if res.dtype != dtype: res = Cast(res, dtype, target="cce") return res
def _reduce_min_max_ascend(data, axis=None, keepdims=False, method="min"): """ Computes the maximum or minimum of elements over a given axis or a list of axes of a tensor. Args: data (tvm.tensor.Tensor): The input tensor to reduce. Should be of type float16, float32, int8, uint8, int32. axis (Union[list, tuple, int, None]): The dimensions to reduce. If None, all dimensions will be reduced. If int or list, must be in the range [-len(data.shape), len(data.shape) - 1]. keepdims (bool): If True, retains reduced dimensions with length 1, default value is False. method (str): Specifies to compute maximum or minimum of input tensor, default value is min. Returns: tvm.tensor.Tensor of same type as input tensor data. """ # check shape utils.check_shape(data.shape) # check type dtype = data.dtype utils.ops_dtype_check(dtype, utils.DtypeForDavinci.ALL_TYPES) # check axis shape_len = len(data.shape) if axis is None: axis = range(shape_len) if hasattr(axis, 'index'): axis = list(axis) if isinstance(axis, int): axis = [axis] utils.is_valid_reduce_axis(data, axis) refined_axis = refine_reduce_axis(data, axis) if len(set(refined_axis)) == len(data.shape) and not keepdims: raise ValueError("When reducing on all axes of input, keepdim should be set to True.") # check method method_list = ["min", "max"] if method not in method_list: raise ValueError("supported method %s while given method is %s" % (",".join(method_list), method)) # In the emit_insn pass, for vmin and vmax, reduce_last_axis only support float16. if dtype != "float16": data = Cast(data, "float16", target="cce") if method == "min": res = akg.topi.min(data, axis=axis, keepdims=keepdims) else: res = akg.topi.max(data, axis=axis, keepdims=keepdims) if res.dtype != dtype: res = Cast(res, dtype, target="cce") return res
Python
def ReduceMin(inputs, axis=None, keepdims=False, target=utils.CCE): """ Compute the min of elements across dimensions of a tensor. Args: inputs (tvm.tensor.Tensor): Tensor. axis (Union[list, tuple, int, None]): If the list or tuple is empty, the axis equal to None. keepdims (bool): If keepdims equal to True, the result shape length is same to input shape length. Returns: tvm.tensor.Tensor, has same type as input. If keepdims is True, all reduced dimensions are retained with length 1, else these reduced axis will be eliminate. Supported Platforms: 'Ascend', 'GPU', 'CPU' """ utils.check_supported_target(target) if target == utils.CCE: return _reduce_min_max_ascend(inputs, axis, keepdims, "min") else: return _reduce_min(inputs, axis, keepdims)
def ReduceMin(inputs, axis=None, keepdims=False, target=utils.CCE): """ Compute the min of elements across dimensions of a tensor. Args: inputs (tvm.tensor.Tensor): Tensor. axis (Union[list, tuple, int, None]): If the list or tuple is empty, the axis equal to None. keepdims (bool): If keepdims equal to True, the result shape length is same to input shape length. Returns: tvm.tensor.Tensor, has same type as input. If keepdims is True, all reduced dimensions are retained with length 1, else these reduced axis will be eliminate. Supported Platforms: 'Ascend', 'GPU', 'CPU' """ utils.check_supported_target(target) if target == utils.CCE: return _reduce_min_max_ascend(inputs, axis, keepdims, "min") else: return _reduce_min(inputs, axis, keepdims)
Python
def less_compare_float32(data_x, data_y): """if x is less than y, then return 1, else return 0""" shape_inputs = get_shape(data_x) # minimun num of float32 2**(-126) data_min = akg.lang.ascend.broadcast(tvm.const(2**(-126), dtype="float32"), shape_inputs, "float32") data_zero = akg.lang.ascend.broadcast(dc.zero_const("float32"), shape_inputs, "float32") res_sub = topi.subtract(data_y, data_x) res_min = topi.minimum(res_sub, data_min) res_max = topi.maximum(res_min, data_zero) # max num of float32 is 2**126 # but cce can only support 2**62, so use 62 * 62 * 2 to adaptor 126 res_mul_fierst = topi.multiply(res_max, tvm.const(2**62, dtype="float32")) res_mul_second = topi.multiply(res_mul_fierst, tvm.const(2**62, dtype="float32")) res = topi.multiply(res_mul_second, tvm.const(2**2, dtype="float32")) return res
def less_compare_float32(data_x, data_y): """if x is less than y, then return 1, else return 0""" shape_inputs = get_shape(data_x) # minimun num of float32 2**(-126) data_min = akg.lang.ascend.broadcast(tvm.const(2**(-126), dtype="float32"), shape_inputs, "float32") data_zero = akg.lang.ascend.broadcast(dc.zero_const("float32"), shape_inputs, "float32") res_sub = topi.subtract(data_y, data_x) res_min = topi.minimum(res_sub, data_min) res_max = topi.maximum(res_min, data_zero) # max num of float32 is 2**126 # but cce can only support 2**62, so use 62 * 62 * 2 to adaptor 126 res_mul_fierst = topi.multiply(res_max, tvm.const(2**62, dtype="float32")) res_mul_second = topi.multiply(res_mul_fierst, tvm.const(2**62, dtype="float32")) res = topi.multiply(res_mul_second, tvm.const(2**2, dtype="float32")) return res
Python
def nudged_min_max_compute(min_broadcast, max_broadcast, num_bits, narrow_range): """ Calculate the maximum and minimum values of the quantization. Notes: Each channel scale[i] euqal to (max_broadcast[i] - min_broadcast[i]) / (quant_max - quant_min). Then compute nudged_zero_point: nudged_zero_point = floor(between_min_max_float + 0.5) + less_quant_min_float + more_quant_max_float, between_min_max_float is first calculated by: zero_point_from_min = (quant_min_float - min_broadcast) / scale, then between_min_max_float = zero_point_from_min, which min_broadcast <= zero_point_from_min <= max_broadcast. Besides, the value of less_quant_min_float is equal to quant_min or zero, zero_point_from_min < quant_min_float, the value is quant_min, else is 0. The same as more_quant_max_float. Finally according to scale and nudged_zero_point to compute nudged_min and nudged_max: nudged_min = (quant_min - nudged_zero_point) * scale nudged_max = (quant_max - nudged_zero_point) * scale Args: min_broadcast (tvm.tensor.Tensor): minimum value to be quantified for each channel. max_broadcast (tvm.tensor.Tensor): maximum value to be quantified for each channel. num_bits (int): num_bits is the bitwidth of the quantization, range [2,16]. narrow_range (bool): if True, for each channel, quantized into the quantization range [0, 2^num_bits - 1] else quantized into the quantization range [1, 2^num_bits - 1]. Returns: nudged_min (tvm.tensor.Tensor): The same type and shape as min_broadcast. nudged_max (tvm.tensor.Tensor): The same type and shape as max_broadcast. scale (tvm.tensor.Tensor): The same type and shape as max_broadcast. """ dtype = min_broadcast.dtype quant_min = 1 if narrow_range else 0 quant_max = (2 ** num_bits) - 1 # because of need compute each channel, so quant_min and quant_max need to broadcast. quant_min_float = topi.full(min_broadcast.shape, dtype, tvm.const(quant_min, dtype)) quant_max_float = topi.full(min_broadcast.shape, dtype, tvm.const(quant_max, dtype)) # caculate each channel max and min difference. max_sub_min = topi.subtract(max_broadcast, min_broadcast) quant_max_sub_quant_min = topi.subtract(quant_max_float, quant_min_float) # compute scale = (max_broadcast - min_broadcast) / (quant_max - quant_min) # and min_div_scale = min_broadcast / scale if product_is_mini(): scale = Mul(max_sub_min, Reciprocal(quant_max_sub_quant_min), target=utils.CCE) min_div_scale = Mul(min_broadcast, Reciprocal(scale), target=utils.CCE) else: scale = Divide(max_sub_min, quant_max_sub_quant_min, target=utils.CCE) min_div_scale = Divide(min_broadcast, scale, target=utils.CCE) # zero_point_from_min = quant_min_float - min_broadcast / scale zero_point_from_min = topi.subtract(quant_min_float, min_div_scale) # if zero_point_from_min < quant_min_float, bool_less_quant_min_float = 1 else 0 bool_less_quant_min_float = less_compare_float32(zero_point_from_min, quant_min_float) # if quant_max_float < zero_point_from_min, bool_more_quant_max_float = 1 else 0 bool_more_quant_max_float = less_compare_float32(quant_max_float, zero_point_from_min) # according to above bool param to select effective value less_quant_min_float = topi.multiply(quant_min_float, bool_less_quant_min_float) more_quant_max_float = topi.multiply(quant_max_float, bool_more_quant_max_float) # compute which num is not less than quant_min_float and not large than quant_max_float tensor_one = topi.full(min_broadcast.shape, dtype, dc.one_const(dtype)) bool_not_less_quant_min_float = topi.subtract(tensor_one, bool_less_quant_min_float) bool_not_more_quant_max_float = topi.subtract(tensor_one, bool_more_quant_max_float) bool_between_min_max = topi.multiply(bool_not_less_quant_min_float, bool_not_more_quant_max_float) between_min_max_float = topi.multiply(zero_point_from_min, bool_between_min_max) # add 0.5 to num which min <= num <= max and then floor them. between_min_max_add_half_one = topi.add(between_min_max_float, dc.half_const(dtype)) between_min_max_round = akg.lang.ascend.floor(between_min_max_add_half_one) if product_is_mini(): between_min_max_round = topi.cast(between_min_max_round, "float16") between_min_max_round = topi.cast(between_min_max_round, "float32") # calculate the maximum and minimum values of the quantization nudged_zero_point_tmp = topi.add(less_quant_min_float, more_quant_max_float) nudged_zero_point = topi.add(nudged_zero_point_tmp, between_min_max_round) nudged_min_tmp = topi.subtract(quant_min_float, nudged_zero_point) nudged_max_tmp = topi.subtract(quant_max_float, nudged_zero_point) nudged_min = topi.multiply(nudged_min_tmp, scale) nudged_max = topi.multiply(nudged_max_tmp, scale) res = [nudged_min, nudged_max, scale] return res
def nudged_min_max_compute(min_broadcast, max_broadcast, num_bits, narrow_range): """ Calculate the maximum and minimum values of the quantization. Notes: Each channel scale[i] euqal to (max_broadcast[i] - min_broadcast[i]) / (quant_max - quant_min). Then compute nudged_zero_point: nudged_zero_point = floor(between_min_max_float + 0.5) + less_quant_min_float + more_quant_max_float, between_min_max_float is first calculated by: zero_point_from_min = (quant_min_float - min_broadcast) / scale, then between_min_max_float = zero_point_from_min, which min_broadcast <= zero_point_from_min <= max_broadcast. Besides, the value of less_quant_min_float is equal to quant_min or zero, zero_point_from_min < quant_min_float, the value is quant_min, else is 0. The same as more_quant_max_float. Finally according to scale and nudged_zero_point to compute nudged_min and nudged_max: nudged_min = (quant_min - nudged_zero_point) * scale nudged_max = (quant_max - nudged_zero_point) * scale Args: min_broadcast (tvm.tensor.Tensor): minimum value to be quantified for each channel. max_broadcast (tvm.tensor.Tensor): maximum value to be quantified for each channel. num_bits (int): num_bits is the bitwidth of the quantization, range [2,16]. narrow_range (bool): if True, for each channel, quantized into the quantization range [0, 2^num_bits - 1] else quantized into the quantization range [1, 2^num_bits - 1]. Returns: nudged_min (tvm.tensor.Tensor): The same type and shape as min_broadcast. nudged_max (tvm.tensor.Tensor): The same type and shape as max_broadcast. scale (tvm.tensor.Tensor): The same type and shape as max_broadcast. """ dtype = min_broadcast.dtype quant_min = 1 if narrow_range else 0 quant_max = (2 ** num_bits) - 1 # because of need compute each channel, so quant_min and quant_max need to broadcast. quant_min_float = topi.full(min_broadcast.shape, dtype, tvm.const(quant_min, dtype)) quant_max_float = topi.full(min_broadcast.shape, dtype, tvm.const(quant_max, dtype)) # caculate each channel max and min difference. max_sub_min = topi.subtract(max_broadcast, min_broadcast) quant_max_sub_quant_min = topi.subtract(quant_max_float, quant_min_float) # compute scale = (max_broadcast - min_broadcast) / (quant_max - quant_min) # and min_div_scale = min_broadcast / scale if product_is_mini(): scale = Mul(max_sub_min, Reciprocal(quant_max_sub_quant_min), target=utils.CCE) min_div_scale = Mul(min_broadcast, Reciprocal(scale), target=utils.CCE) else: scale = Divide(max_sub_min, quant_max_sub_quant_min, target=utils.CCE) min_div_scale = Divide(min_broadcast, scale, target=utils.CCE) # zero_point_from_min = quant_min_float - min_broadcast / scale zero_point_from_min = topi.subtract(quant_min_float, min_div_scale) # if zero_point_from_min < quant_min_float, bool_less_quant_min_float = 1 else 0 bool_less_quant_min_float = less_compare_float32(zero_point_from_min, quant_min_float) # if quant_max_float < zero_point_from_min, bool_more_quant_max_float = 1 else 0 bool_more_quant_max_float = less_compare_float32(quant_max_float, zero_point_from_min) # according to above bool param to select effective value less_quant_min_float = topi.multiply(quant_min_float, bool_less_quant_min_float) more_quant_max_float = topi.multiply(quant_max_float, bool_more_quant_max_float) # compute which num is not less than quant_min_float and not large than quant_max_float tensor_one = topi.full(min_broadcast.shape, dtype, dc.one_const(dtype)) bool_not_less_quant_min_float = topi.subtract(tensor_one, bool_less_quant_min_float) bool_not_more_quant_max_float = topi.subtract(tensor_one, bool_more_quant_max_float) bool_between_min_max = topi.multiply(bool_not_less_quant_min_float, bool_not_more_quant_max_float) between_min_max_float = topi.multiply(zero_point_from_min, bool_between_min_max) # add 0.5 to num which min <= num <= max and then floor them. between_min_max_add_half_one = topi.add(between_min_max_float, dc.half_const(dtype)) between_min_max_round = akg.lang.ascend.floor(between_min_max_add_half_one) if product_is_mini(): between_min_max_round = topi.cast(between_min_max_round, "float16") between_min_max_round = topi.cast(between_min_max_round, "float32") # calculate the maximum and minimum values of the quantization nudged_zero_point_tmp = topi.add(less_quant_min_float, more_quant_max_float) nudged_zero_point = topi.add(nudged_zero_point_tmp, between_min_max_round) nudged_min_tmp = topi.subtract(quant_min_float, nudged_zero_point) nudged_max_tmp = topi.subtract(quant_max_float, nudged_zero_point) nudged_min = topi.multiply(nudged_min_tmp, scale) nudged_max = topi.multiply(nudged_max_tmp, scale) res = [nudged_min, nudged_max, scale] return res
Python
def bool_both_zero_compute(juduged_min, juduged_max): """if input min and max are both zero then output_data will be all zero,so need a juduge compute tensor""" dtype = juduged_min.dtype tensor_zero = topi.full(juduged_min.shape, dtype, dc.zero_const(dtype)) min_abs = topi.abs(juduged_min) max_abs = topi.abs(juduged_max) min_max_replace = topi.add(min_abs, max_abs) # just check wether min and max are all zero, if true return 0 bool_min_max_product_less_zero = less_compare_float32(min_max_replace, tensor_zero) bool_min_max_product_more_zero = less_compare_float32(tensor_zero, min_max_replace) bool_both_zero = topi.add(bool_min_max_product_less_zero, bool_min_max_product_more_zero) return bool_both_zero
def bool_both_zero_compute(juduged_min, juduged_max): """if input min and max are both zero then output_data will be all zero,so need a juduge compute tensor""" dtype = juduged_min.dtype tensor_zero = topi.full(juduged_min.shape, dtype, dc.zero_const(dtype)) min_abs = topi.abs(juduged_min) max_abs = topi.abs(juduged_max) min_max_replace = topi.add(min_abs, max_abs) # just check wether min and max are all zero, if true return 0 bool_min_max_product_less_zero = less_compare_float32(min_max_replace, tensor_zero) bool_min_max_product_more_zero = less_compare_float32(tensor_zero, min_max_replace) bool_both_zero = topi.add(bool_min_max_product_less_zero, bool_min_max_product_more_zero) return bool_both_zero
Python
def softmax_ad_optimized(head, data, axis=-1): """ Computes the autodiff of softmax. Args: head (tvm.tensor.Tensor): Original differentiation values. data (tvm.tensor.Tensor): Input of softmax. axis (int): Along which axis softmax is performed. Returns: tvm.tensor.Tensor, the overall differentiation values. """ def get_shape(pld): return [d.value for d in pld.shape] def temp_compute(shape, grad, sftmx_fwd, *indices): shp_len = len(shape) grad_index = indices[:(shp_len - 2)] + indices[-1:] sftmx_fwd_index = indices[:-1] temp = grad(*grad_index) * akg.tvm.expr.Select(indices[-1] == indices[-2], sftmx_fwd(*sftmx_fwd_index) * (1 - sftmx_fwd(*sftmx_fwd_index)), -sftmx_fwd(*sftmx_fwd_index) * sftmx_fwd(*grad_index)) return temp def temp_sum_compute(shape, temp, *indices): kk = akg.tvm.reduce_axis((0, shape[-1]), name='kk') index = indices[:] + (kk,) temp_sum = akg.tvm.sum(temp(*index), axis=kk) return temp_sum def custom_softmax_fdiff(out, inputs, grad, ad_attrs, new_pld_array): data = inputs[0] shape = get_shape(data) sftmx_fwd = Softmax(data, -1)[0] shape.append(shape[-1]) temp = akg.tvm.compute(shape, lambda *indices: temp_compute(shape, grad, sftmx_fwd, *indices), name="softmax_select2") temp_sum = akg.tvm.compute(shape[:-1], lambda *indices: temp_sum_compute(shape, temp, *indices), name="softmax_ad2") return [temp_sum] l_up = Softmax(data, axis)[0] # For the large expression tree's dl w.r.t. data (where softmax is embedded inside), use the default fdiff. # For softmax's dl w.r.t. data (note: l_up is not a direct dependency of data), use the custom_softmax_fdiff. # In this case, l_up is the same as l_up, and data same as data, but this needs not be the case. [dl_ddata] = akg.differentiate(l_up, [data], head, None, None, override={l_up: ([data], custom_softmax_fdiff)}) attrs = {} return dl_ddata, attrs
def softmax_ad_optimized(head, data, axis=-1): """ Computes the autodiff of softmax. Args: head (tvm.tensor.Tensor): Original differentiation values. data (tvm.tensor.Tensor): Input of softmax. axis (int): Along which axis softmax is performed. Returns: tvm.tensor.Tensor, the overall differentiation values. """ def get_shape(pld): return [d.value for d in pld.shape] def temp_compute(shape, grad, sftmx_fwd, *indices): shp_len = len(shape) grad_index = indices[:(shp_len - 2)] + indices[-1:] sftmx_fwd_index = indices[:-1] temp = grad(*grad_index) * akg.tvm.expr.Select(indices[-1] == indices[-2], sftmx_fwd(*sftmx_fwd_index) * (1 - sftmx_fwd(*sftmx_fwd_index)), -sftmx_fwd(*sftmx_fwd_index) * sftmx_fwd(*grad_index)) return temp def temp_sum_compute(shape, temp, *indices): kk = akg.tvm.reduce_axis((0, shape[-1]), name='kk') index = indices[:] + (kk,) temp_sum = akg.tvm.sum(temp(*index), axis=kk) return temp_sum def custom_softmax_fdiff(out, inputs, grad, ad_attrs, new_pld_array): data = inputs[0] shape = get_shape(data) sftmx_fwd = Softmax(data, -1)[0] shape.append(shape[-1]) temp = akg.tvm.compute(shape, lambda *indices: temp_compute(shape, grad, sftmx_fwd, *indices), name="softmax_select2") temp_sum = akg.tvm.compute(shape[:-1], lambda *indices: temp_sum_compute(shape, temp, *indices), name="softmax_ad2") return [temp_sum] l_up = Softmax(data, axis)[0] # For the large expression tree's dl w.r.t. data (where softmax is embedded inside), use the default fdiff. # For softmax's dl w.r.t. data (note: l_up is not a direct dependency of data), use the custom_softmax_fdiff. # In this case, l_up is the same as l_up, and data same as data, but this needs not be the case. [dl_ddata] = akg.differentiate(l_up, [data], head, None, None, override={l_up: ([data], custom_softmax_fdiff)}) attrs = {} return dl_ddata, attrs
Python
def gather_tiling_strategy(data, axis): """Custom tiling strategy for gather op""" strategy = list() base = 0 for priority_value, pos in enumerate(range(len(data.shape) - 1, axis, -1)): priority_value = priority_value + base strategy.append(ct_util.create_constraint_on_tensor(tensor=data, values=priority_value, constraints=ct_util.TileConstraint.SET_PRIORITY, tensor_pos=pos)[0]) return strategy
def gather_tiling_strategy(data, axis): """Custom tiling strategy for gather op""" strategy = list() base = 0 for priority_value, pos in enumerate(range(len(data.shape) - 1, axis, -1)): priority_value = priority_value + base strategy.append(ct_util.create_constraint_on_tensor(tensor=data, values=priority_value, constraints=ct_util.TileConstraint.SET_PRIORITY, tensor_pos=pos)[0]) return strategy
Python
def sum_square(inputs, axis=None, keepdims=False, target=utils.CCE): """ Computes the sum of square value of input tensor along axis. Args: input: The input akg.tvm.tensor. axis: An integer, specifies the dimensions to reduce when performing the sum operation. keepdims: A boolean, if True, retains reduced dimensions with length 1, default value is False. Returns: A akg.tvm.Tensor of same type as input. """ inputs_square = square(inputs) return Sum(inputs_square, axis, keepdims, target=target)
def sum_square(inputs, axis=None, keepdims=False, target=utils.CCE): """ Computes the sum of square value of input tensor along axis. Args: input: The input akg.tvm.tensor. axis: An integer, specifies the dimensions to reduce when performing the sum operation. keepdims: A boolean, if True, retains reduced dimensions with length 1, default value is False. Returns: A akg.tvm.Tensor of same type as input. """ inputs_square = square(inputs) return Sum(inputs_square, axis, keepdims, target=target)
Python
def apply_momentum_run(shape, dtype, use_nesterov=False, grad_scale=1.0, lr_mat=0.1, momt_mat=0.9, attrs=None): """ run function for dsl function apply_momentum. """ lr = np.full((1,), lr_mat).astype(dtype) momt = np.full((1,), momt_mat).astype(dtype) if 'tuning' in attrs.keys(): t = attrs.get("tuning", False) kernel_name = attrs.get("kernel_name", False) mod = utils.op_build_test(ApplyMomentum, [shape, shape, shape, lr.shape, momt.shape], [dtype, dtype, dtype, dtype, dtype], [use_nesterov, grad_scale], kernel_name=kernel_name, attrs=attrs, tuning=t) if t: accum_exp, accum, expect, grad, var = gen_data(dtype, lr, momt, shape, use_nesterov, grad_scale) fake_output = np.full(shape, np.nan, dtype) return mod, (expect, accum_exp), {"args": (var, grad, accum, lr, momt, fake_output), 'outputs': (0, 2, -1), 'tuning': False} else: return mod else: mod = utils.op_build_test(ApplyMomentum, [shape, shape, shape, lr.shape, momt.shape], [dtype, dtype, dtype, dtype, dtype], [use_nesterov, grad_scale], kernel_name='apply_momentum', attrs=attrs) accum_exp, accum, expect, grad, var = gen_data(dtype, lr, momt, shape, use_nesterov, grad_scale) fake_output = np.full(shape, np.nan, dtype) var_update, accum_update, _ = utils.mod_launch(mod, (var, grad, accum, lr, momt, fake_output), outputs=(0, 2, -1), expect=expect) rtol, atol = get_rtol_atol("apply_momentum", dtype) expects = (expect, accum_exp) outputs = (var_update, accum_update) return var, outputs, expects, compare_tensor(outputs, expects, rtol=rtol, atol=atol, equal_nan=True)
def apply_momentum_run(shape, dtype, use_nesterov=False, grad_scale=1.0, lr_mat=0.1, momt_mat=0.9, attrs=None): """ run function for dsl function apply_momentum. """ lr = np.full((1,), lr_mat).astype(dtype) momt = np.full((1,), momt_mat).astype(dtype) if 'tuning' in attrs.keys(): t = attrs.get("tuning", False) kernel_name = attrs.get("kernel_name", False) mod = utils.op_build_test(ApplyMomentum, [shape, shape, shape, lr.shape, momt.shape], [dtype, dtype, dtype, dtype, dtype], [use_nesterov, grad_scale], kernel_name=kernel_name, attrs=attrs, tuning=t) if t: accum_exp, accum, expect, grad, var = gen_data(dtype, lr, momt, shape, use_nesterov, grad_scale) fake_output = np.full(shape, np.nan, dtype) return mod, (expect, accum_exp), {"args": (var, grad, accum, lr, momt, fake_output), 'outputs': (0, 2, -1), 'tuning': False} else: return mod else: mod = utils.op_build_test(ApplyMomentum, [shape, shape, shape, lr.shape, momt.shape], [dtype, dtype, dtype, dtype, dtype], [use_nesterov, grad_scale], kernel_name='apply_momentum', attrs=attrs) accum_exp, accum, expect, grad, var = gen_data(dtype, lr, momt, shape, use_nesterov, grad_scale) fake_output = np.full(shape, np.nan, dtype) var_update, accum_update, _ = utils.mod_launch(mod, (var, grad, accum, lr, momt, fake_output), outputs=(0, 2, -1), expect=expect) rtol, atol = get_rtol_atol("apply_momentum", dtype) expects = (expect, accum_exp) outputs = (var_update, accum_update) return var, outputs, expects, compare_tensor(outputs, expects, rtol=rtol, atol=atol, equal_nan=True)
Python
def gen_data(dtype, lr, momt, shape, use_nesterov, grad_scale): """ Generate data for testing the op """ var = random_gaussian(shape, miu=10, sigma=0.3).astype(dtype) grad = random_gaussian(shape, miu=3, sigma=0.3).astype(dtype) accum = random_gaussian(shape, miu=4, sigma=0.3).astype(dtype) grad_compute_value = grad * grad_scale momt_update = momt[0] * accum + grad_compute_value if use_nesterov == False: var_update = var - lr[0] * momt_update else: var_update = var - lr[0] * grad_compute_value - momt_update * lr[0] * momt[0] expect = var_update return momt_update, accum, expect, grad, var
def gen_data(dtype, lr, momt, shape, use_nesterov, grad_scale): """ Generate data for testing the op """ var = random_gaussian(shape, miu=10, sigma=0.3).astype(dtype) grad = random_gaussian(shape, miu=3, sigma=0.3).astype(dtype) accum = random_gaussian(shape, miu=4, sigma=0.3).astype(dtype) grad_compute_value = grad * grad_scale momt_update = momt[0] * accum + grad_compute_value if use_nesterov == False: var_update = var - lr[0] * momt_update else: var_update = var - lr[0] * grad_compute_value - momt_update * lr[0] * momt[0] expect = var_update return momt_update, accum, expect, grad, var
Python
def sqrt_mini_newton_iter_impl(x): """sqrt compute on mini with the Newton's Iteration""" # mini supports the rsqrt instruction, but not the sqrt instruction x_rsqrt = topi.rsqrt(x) x_sqrt = topi.divide(1, x_rsqrt) # newton_iter: x(n+1) = 1/2 *(x(n) + a/x(n)) steps = 3 half = tvm.const(0.5, x.dtype) shape = x.shape for i in range(steps): x_sqrt = tvm.compute(shape, lambda *indice: half * (x_sqrt(*indice) + x(*indice)/x_sqrt(*indice)), name="x_sqrt_%s" % i) return x_sqrt
def sqrt_mini_newton_iter_impl(x): """sqrt compute on mini with the Newton's Iteration""" # mini supports the rsqrt instruction, but not the sqrt instruction x_rsqrt = topi.rsqrt(x) x_sqrt = topi.divide(1, x_rsqrt) # newton_iter: x(n+1) = 1/2 *(x(n) + a/x(n)) steps = 3 half = tvm.const(0.5, x.dtype) shape = x.shape for i in range(steps): x_sqrt = tvm.compute(shape, lambda *indice: half * (x_sqrt(*indice) + x(*indice)/x_sqrt(*indice)), name="x_sqrt_%s" % i) return x_sqrt
Python
def log_compute_mini_impl(x, target=utils.CCE): """log compute on mini for x >= 1""" # compute method: # As vlog instruction has some precision problems when x in interval [1,2), the taylor method be used to # calculate log value of x. # For x in interval [1, 4/3), calculate log value of x by the Taylor formula: # log(1+x) = ((((0.2x - 0.25)x + 0.33333)x - 0.5)x + 1)x. # For x in interval [4/3, 5/3) and [5/3, 2), x are mapped to in interval [1, 4/3), by the following formulas: # [4/3, 5/3) -> log(x * 3/4) + log(4/3), # [5/3, 2) -> log(x * 3/5) + log(5/3). # For x in interval [2, 32768), calculate log value of x by vlog instruction directly: # [2, 32768) -> log(x). # As vlog instruction has overflow problems when x greater or equal to 32768, calculate log value of x # by the following formulas: # [32768, ) -> log(x/2.5) + log(2.5). thresholds = [4/3, 5/3, 2, 32768] thresholds_rec = [3/4, 3/5] log_thresholds = [0.28768207245178085, 0.5108256237659907] overflow_div_coffient = 2.5 log_overflow_div_coffient = 0.916290731874155 def _log_taylor(data): """algrithm: log(1+x) = ((((0.2x - 0.25)x + 0.33333)x - 0.5)x + 1)x""" data = topi.subtract(data, 1) taylor_params = [0.2, -0.25, 1/3, -0.5, 1] taylor_five = topi.multiply(data, taylor_params[0]) taylor_four_1 = topi.add(taylor_five, taylor_params[1]) taylor_four_2 = topi.multiply(taylor_four_1, data) taylor_three_1 = topi.add(taylor_four_2, taylor_params[2]) taylor_three_2 = topi.multiply(taylor_three_1, data) taylor_two_1 = topi.add(taylor_three_2, taylor_params[3]) taylor_two_2 = topi.multiply(taylor_two_1, data) taylor_one = topi.add(taylor_two_2, taylor_params[4]) taylor = topi.multiply(taylor_one, data) return taylor # taylor shape = x.shape threshold_2 = tvm.const(thresholds[1], "float16") threshold_1 = tvm.const(thresholds[0], "float16") threshold_2_rec = tvm.const(thresholds_rec[1], "float16") threshold_1_rec = tvm.const(thresholds_rec[0], "float16") x_fp16 = topi.cast(x, "float16") x_1 = tvm.compute(shape, lambda *indice: tvm.expr.Select(x_fp16(*indice) >= threshold_2, x_fp16(*indice)*threshold_2_rec, x_fp16(*indice)), name="x_1") x_2 = tvm.compute(shape, lambda *indice: tvm.expr.Select(x_1(*indice) >= threshold_1, x_1(*indice)*threshold_1_rec, x_1(*indice)), name="x_2") taylor = _log_taylor(topi.cast(x_2, "float32")) log_threshold_1 = log_thresholds[0] log_threshold_2 = log_thresholds[1] taylor_add_log_threshold_1_fp16 = topi.cast(topi.add(taylor, log_threshold_1), "float16") taylor_add_log_threshold_2_fp16 = topi.cast(topi.add(taylor, log_threshold_2), "float16") res = tvm.compute(shape, lambda *indice: tvm.expr.Select(x_1(*indice) >= threshold_1, taylor_add_log_threshold_1_fp16(*indice), taylor(*indice).astype("float16")), name="res_1") res = tvm.compute(shape, lambda *indice: tvm.expr.Select(x_fp16(*indice) >= threshold_2, taylor_add_log_threshold_2_fp16(*indice), res(*indice)), name="res_2") # vlog x_log = Log(x_fp16, target) res = tvm.compute(shape, lambda *indice: tvm.expr.Select(x_fp16(*indice) >= thresholds[2], x_log(*indice), res(*indice)), name="res_3") # overflow overflow_threshold = tvm.const(thresholds[3], "float16") res_overflow = topi.cast(topi.add(Log(topi.multiply(x, 1/overflow_div_coffient), target), log_overflow_div_coffient), "float16") res = tvm.compute(shape, lambda *indice: tvm.expr.Select(x_fp16(*indice) >= overflow_threshold, res_overflow(*indice), res(*indice)), name="res_4") if res.dtype != x.dtype: res = topi.cast(res, x.dtype) return res
def log_compute_mini_impl(x, target=utils.CCE): """log compute on mini for x >= 1""" # compute method: # As vlog instruction has some precision problems when x in interval [1,2), the taylor method be used to # calculate log value of x. # For x in interval [1, 4/3), calculate log value of x by the Taylor formula: # log(1+x) = ((((0.2x - 0.25)x + 0.33333)x - 0.5)x + 1)x. # For x in interval [4/3, 5/3) and [5/3, 2), x are mapped to in interval [1, 4/3), by the following formulas: # [4/3, 5/3) -> log(x * 3/4) + log(4/3), # [5/3, 2) -> log(x * 3/5) + log(5/3). # For x in interval [2, 32768), calculate log value of x by vlog instruction directly: # [2, 32768) -> log(x). # As vlog instruction has overflow problems when x greater or equal to 32768, calculate log value of x # by the following formulas: # [32768, ) -> log(x/2.5) + log(2.5). thresholds = [4/3, 5/3, 2, 32768] thresholds_rec = [3/4, 3/5] log_thresholds = [0.28768207245178085, 0.5108256237659907] overflow_div_coffient = 2.5 log_overflow_div_coffient = 0.916290731874155 def _log_taylor(data): """algrithm: log(1+x) = ((((0.2x - 0.25)x + 0.33333)x - 0.5)x + 1)x""" data = topi.subtract(data, 1) taylor_params = [0.2, -0.25, 1/3, -0.5, 1] taylor_five = topi.multiply(data, taylor_params[0]) taylor_four_1 = topi.add(taylor_five, taylor_params[1]) taylor_four_2 = topi.multiply(taylor_four_1, data) taylor_three_1 = topi.add(taylor_four_2, taylor_params[2]) taylor_three_2 = topi.multiply(taylor_three_1, data) taylor_two_1 = topi.add(taylor_three_2, taylor_params[3]) taylor_two_2 = topi.multiply(taylor_two_1, data) taylor_one = topi.add(taylor_two_2, taylor_params[4]) taylor = topi.multiply(taylor_one, data) return taylor # taylor shape = x.shape threshold_2 = tvm.const(thresholds[1], "float16") threshold_1 = tvm.const(thresholds[0], "float16") threshold_2_rec = tvm.const(thresholds_rec[1], "float16") threshold_1_rec = tvm.const(thresholds_rec[0], "float16") x_fp16 = topi.cast(x, "float16") x_1 = tvm.compute(shape, lambda *indice: tvm.expr.Select(x_fp16(*indice) >= threshold_2, x_fp16(*indice)*threshold_2_rec, x_fp16(*indice)), name="x_1") x_2 = tvm.compute(shape, lambda *indice: tvm.expr.Select(x_1(*indice) >= threshold_1, x_1(*indice)*threshold_1_rec, x_1(*indice)), name="x_2") taylor = _log_taylor(topi.cast(x_2, "float32")) log_threshold_1 = log_thresholds[0] log_threshold_2 = log_thresholds[1] taylor_add_log_threshold_1_fp16 = topi.cast(topi.add(taylor, log_threshold_1), "float16") taylor_add_log_threshold_2_fp16 = topi.cast(topi.add(taylor, log_threshold_2), "float16") res = tvm.compute(shape, lambda *indice: tvm.expr.Select(x_1(*indice) >= threshold_1, taylor_add_log_threshold_1_fp16(*indice), taylor(*indice).astype("float16")), name="res_1") res = tvm.compute(shape, lambda *indice: tvm.expr.Select(x_fp16(*indice) >= threshold_2, taylor_add_log_threshold_2_fp16(*indice), res(*indice)), name="res_2") # vlog x_log = Log(x_fp16, target) res = tvm.compute(shape, lambda *indice: tvm.expr.Select(x_fp16(*indice) >= thresholds[2], x_log(*indice), res(*indice)), name="res_3") # overflow overflow_threshold = tvm.const(thresholds[3], "float16") res_overflow = topi.cast(topi.add(Log(topi.multiply(x, 1/overflow_div_coffient), target), log_overflow_div_coffient), "float16") res = tvm.compute(shape, lambda *indice: tvm.expr.Select(x_fp16(*indice) >= overflow_threshold, res_overflow(*indice), res(*indice)), name="res_4") if res.dtype != x.dtype: res = topi.cast(res, x.dtype) return res
Python
def LessEqual(data1, data2, target=utils.CCE): """ Check whether input1 lessequals to input2. Args: input1 (tvm.tensor.Tensor): Tensor. input2 (tvm.tensor.Tensor): Tensor. Returns: tvm.tensor.Tensor. If input1 lessequal to input2 return True, else return False. Supported Platforms: 'Ascend', 'GPU', 'CPU' """ utils.check_supported_target(target) if target == utils.CCE: return _less_equal_ascend(data1, data2) else: return _less_equal(data1, data2)
def LessEqual(data1, data2, target=utils.CCE): """ Check whether input1 lessequals to input2. Args: input1 (tvm.tensor.Tensor): Tensor. input2 (tvm.tensor.Tensor): Tensor. Returns: tvm.tensor.Tensor. If input1 lessequal to input2 return True, else return False. Supported Platforms: 'Ascend', 'GPU', 'CPU' """ utils.check_supported_target(target) if target == utils.CCE: return _less_equal_ascend(data1, data2) else: return _less_equal(data1, data2)
Python
def relu_grad(inputs, head, target="cce"): """ Computes gradient of inputs for the relu op Args: inputs: It is the same with the relu op. head: Tensor, has the same type and shape as inputs. Back propagation value. Returns: Tensor, has the same type and shape as inputs. """ check_list = ["float16", "float32"] dtype = inputs.dtype if not dtype.lower() in check_list: raise RuntimeError("relu_grad only support %s while dtype is %s" % (",".join(check_list), dtype)) shape = [x.value for x in inputs.shape] utils.check_shape(shape) res = akg.tvm.compute(shape, lambda *i: akg.tvm.if_then_else( inputs(*i) > akg.tvm.const(0, dtype), head(*i), akg.tvm.const(0, dtype) )) return res
def relu_grad(inputs, head, target="cce"): """ Computes gradient of inputs for the relu op Args: inputs: It is the same with the relu op. head: Tensor, has the same type and shape as inputs. Back propagation value. Returns: Tensor, has the same type and shape as inputs. """ check_list = ["float16", "float32"] dtype = inputs.dtype if not dtype.lower() in check_list: raise RuntimeError("relu_grad only support %s while dtype is %s" % (",".join(check_list), dtype)) shape = [x.value for x in inputs.shape] utils.check_shape(shape) res = akg.tvm.compute(shape, lambda *i: akg.tvm.if_then_else( inputs(*i) > akg.tvm.const(0, dtype), head(*i), akg.tvm.const(0, dtype) )) return res
Python
def ApplyMomentum(weight, grad, accum, lr_mat, momt_mat, use_nesterov=False, grad_scale=1.0, target=utils.CCE): """ Apply momentum operator. Note: apply mometum is an op with inplace computing and binds is used. Args: weight (tvm.tensor.Tensor): weight tensor to be updated. grad (tvm.tensor.Tensor): gradient tensor. accum (tvm.tensor.Tensor): accum tensor to be updated. lr_mat (tvm.tensor.Tensor): tensor with shape (1,). momt_mat (tvm.tensor.Tensor): momt_mat tensor with shape (1,). use_nesterov (bool): Default value is False. grad_scale (float): Default value is 1.0 Returns: fake_output: Invalid value, just suit for framework. accum_inplace: tvm.tensor.Tensor, updated accum. weight_inplace: tvm.tensor.Tensor, updated weight. atts: dict. """ shape = [x.value for x in weight.shape] # shape check utils.elemwise_shape_check(weight.shape, grad.shape) utils.elemwise_shape_check(weight.shape, accum.shape) # dtype check utils.ops_dtype_check([weight.dtype, grad.dtype, accum.dtype], utils.DtypeForDavinci.ALL_FLOAT) grad = akg.tvm.compute(shape, lambda * indice: grad(*indice) * akg.tvm.const(grad_scale, grad.dtype), name="grad") momt_accum = akg.tvm.compute(shape, lambda *indice: accum(*indice) * momt_mat[0], name="momt_accum") accum_inplace = akg.tvm.compute(shape, lambda *indice: momt_accum(*indice) + grad(*indice), name="accum_inplace") if not use_nesterov: sum_grad = akg.tvm.compute(shape, lambda *indice: accum_inplace(*indice) * lr_mat[0], name="nesterov_lr") weight_inplace = akg.tvm.compute(shape, lambda *indice: weight(*indice) - sum_grad(*indice), name="weight_inplace") else: weight_inplace = akg.tvm.compute(shape, lambda *indice: weight(*indice) - grad(*indice) * lr_mat[0] - accum_inplace(*indice) * momt_mat[0] * lr_mat[0], name="weight_inplace") weight_inplace, weight_binds_info = TensorUtils.inplace_set(weight, weight_inplace, "data_buf") accum_inplace, accum_binds_info = TensorUtils.inplace_set(accum, accum_inplace, "accum_buf") binds_info_all = weight_binds_info binds_info_all.update(accum_binds_info) attrs = {utils.BINDS: binds_info_all} fake_output = akg.tvm.compute(shape, lambda *indice: momt_accum(*indice), name="fake_output") # The variable fake_ouput is a invalid value, just to suit for framework of ME ! # The variable weight_inplace is the updated value of weight . # The variable accum_inplace is the updated value of accum . return fake_output, accum_inplace, weight_inplace, attrs
def ApplyMomentum(weight, grad, accum, lr_mat, momt_mat, use_nesterov=False, grad_scale=1.0, target=utils.CCE): """ Apply momentum operator. Note: apply mometum is an op with inplace computing and binds is used. Args: weight (tvm.tensor.Tensor): weight tensor to be updated. grad (tvm.tensor.Tensor): gradient tensor. accum (tvm.tensor.Tensor): accum tensor to be updated. lr_mat (tvm.tensor.Tensor): tensor with shape (1,). momt_mat (tvm.tensor.Tensor): momt_mat tensor with shape (1,). use_nesterov (bool): Default value is False. grad_scale (float): Default value is 1.0 Returns: fake_output: Invalid value, just suit for framework. accum_inplace: tvm.tensor.Tensor, updated accum. weight_inplace: tvm.tensor.Tensor, updated weight. atts: dict. """ shape = [x.value for x in weight.shape] # shape check utils.elemwise_shape_check(weight.shape, grad.shape) utils.elemwise_shape_check(weight.shape, accum.shape) # dtype check utils.ops_dtype_check([weight.dtype, grad.dtype, accum.dtype], utils.DtypeForDavinci.ALL_FLOAT) grad = akg.tvm.compute(shape, lambda * indice: grad(*indice) * akg.tvm.const(grad_scale, grad.dtype), name="grad") momt_accum = akg.tvm.compute(shape, lambda *indice: accum(*indice) * momt_mat[0], name="momt_accum") accum_inplace = akg.tvm.compute(shape, lambda *indice: momt_accum(*indice) + grad(*indice), name="accum_inplace") if not use_nesterov: sum_grad = akg.tvm.compute(shape, lambda *indice: accum_inplace(*indice) * lr_mat[0], name="nesterov_lr") weight_inplace = akg.tvm.compute(shape, lambda *indice: weight(*indice) - sum_grad(*indice), name="weight_inplace") else: weight_inplace = akg.tvm.compute(shape, lambda *indice: weight(*indice) - grad(*indice) * lr_mat[0] - accum_inplace(*indice) * momt_mat[0] * lr_mat[0], name="weight_inplace") weight_inplace, weight_binds_info = TensorUtils.inplace_set(weight, weight_inplace, "data_buf") accum_inplace, accum_binds_info = TensorUtils.inplace_set(accum, accum_inplace, "accum_buf") binds_info_all = weight_binds_info binds_info_all.update(accum_binds_info) attrs = {utils.BINDS: binds_info_all} fake_output = akg.tvm.compute(shape, lambda *indice: momt_accum(*indice), name="fake_output") # The variable fake_ouput is a invalid value, just to suit for framework of ME ! # The variable weight_inplace is the updated value of weight . # The variable accum_inplace is the updated value of accum . return fake_output, accum_inplace, weight_inplace, attrs
Python
def StridedSlice(inputs, begin, end, strides, begin_mask, end_mask, ellipsis_mask, new_axis_mask, shrink_axis_mask, target=utils.CCE): """ Generate an array by slicing input tensor Args: inputs (tvm.tensor.Tensor): Tensor of type float16, float32. begin (Union[list, tuple, int]): The start indexes for slicing. end (Union[list, tuple, int]): The end indexes for slicing. strides (Union[list, tuple, int]): The strides for slicing. begin_mask (int): int32 mask for begin indexes. end_mask (int): int32 mask for end indexes. ellipsis_mask (int): int32 mask for inserting unspecified dimensions. new_axis_mask (int): int32 mask for new dim with length 1. shrink_axis_mask (int): int32 mask for shrinking the dims. Returns: tvm.tensor.Tensor, with the same dtype as inputs. Supported Platforms: 'Ascend' """ shape = [x.value for x in inputs.shape] # step0~4: complete begin, end, strides begin, end, strides, new_axis_index, shrink_list = complete_args(shape, begin, end, strides, begin_mask, end_mask, ellipsis_mask, new_axis_mask, shrink_axis_mask) # step5: use topi to do strided_slice using begin, end, strides if (shape == [1] and begin == end): return akg.tvm.compute(shape, lambda *i: inputs(*i), name="out") if inputs.dtype == "uint8": inputs_cast = akg.topi.cast(inputs, "int8") else: inputs_cast = inputs out1 = akg.topi.strided_slice(inputs_cast, begin, end, strides) # step6: increase out_tensor's dim using new_axis_index new_shape = list(out1.shape) for idx in new_axis_index[::-1]: new_shape.insert(idx, 1) # step7: decrease out_tensor's dim using shrink_list for idx in new_axis_index[::-1]: shrink_list.insert(idx, 0) shrink_axis_index = [idx for idx, x in enumerate(shrink_list) if x] for idx in shrink_axis_index[::-1]: new_shape.pop(idx) # step8: reshape out_tensor out2 = akg.topi.reshape(out1, tuple(new_shape)) if inputs.dtype == "uint8": out2 = akg.topi.cast(out2, "uint8") return out2
def StridedSlice(inputs, begin, end, strides, begin_mask, end_mask, ellipsis_mask, new_axis_mask, shrink_axis_mask, target=utils.CCE): """ Generate an array by slicing input tensor Args: inputs (tvm.tensor.Tensor): Tensor of type float16, float32. begin (Union[list, tuple, int]): The start indexes for slicing. end (Union[list, tuple, int]): The end indexes for slicing. strides (Union[list, tuple, int]): The strides for slicing. begin_mask (int): int32 mask for begin indexes. end_mask (int): int32 mask for end indexes. ellipsis_mask (int): int32 mask for inserting unspecified dimensions. new_axis_mask (int): int32 mask for new dim with length 1. shrink_axis_mask (int): int32 mask for shrinking the dims. Returns: tvm.tensor.Tensor, with the same dtype as inputs. Supported Platforms: 'Ascend' """ shape = [x.value for x in inputs.shape] # step0~4: complete begin, end, strides begin, end, strides, new_axis_index, shrink_list = complete_args(shape, begin, end, strides, begin_mask, end_mask, ellipsis_mask, new_axis_mask, shrink_axis_mask) # step5: use topi to do strided_slice using begin, end, strides if (shape == [1] and begin == end): return akg.tvm.compute(shape, lambda *i: inputs(*i), name="out") if inputs.dtype == "uint8": inputs_cast = akg.topi.cast(inputs, "int8") else: inputs_cast = inputs out1 = akg.topi.strided_slice(inputs_cast, begin, end, strides) # step6: increase out_tensor's dim using new_axis_index new_shape = list(out1.shape) for idx in new_axis_index[::-1]: new_shape.insert(idx, 1) # step7: decrease out_tensor's dim using shrink_list for idx in new_axis_index[::-1]: shrink_list.insert(idx, 0) shrink_axis_index = [idx for idx, x in enumerate(shrink_list) if x] for idx in shrink_axis_index[::-1]: new_shape.pop(idx) # step8: reshape out_tensor out2 = akg.topi.reshape(out1, tuple(new_shape)) if inputs.dtype == "uint8": out2 = akg.topi.cast(out2, "uint8") return out2
Python
def apply_adam(var, m, v, beta1_power, beta2_power, lr, beta1, beta2, epsilon, grad, use_nesterov=False, target=utils.CCE): """ Adam and Nadam optimization algorithm. Note: lr_t = lr*sqrt(1-beta2_power)/(1-beta1_power) m_new = m + (1-beta1)*(grad-m) v_new = v + (1-beta2)*(grad*grad-v) if user_nesterov == True: var_new = var - lr_t*(m_new*beta1 + (1-beta1)*grad) / (epsilon + sqrt(v_new)) else: var_new = var - lr_t*m_new / (epsilon + sqrt(v_new)) Args: var (tvm.tensor.Tensor): The tensor to be updated. Should be float16 or float32. m (tvm.tensor.Tensor): The first moment estimate. A tensor of same shape and type as var. v (tvm.tensor.Tensor): The second moment estimate. A tensor of same shape and type as var. beta1_power (tvm.tensor.Tensor): A scalar tensor of the same type as `var`. beta2_power (tvm.tensor.Tensor): A scalar tensor of the same type as `var`. lr (tvm.tensor.Tensor): The learning rate. A scalar tensor of the same type as `var`. beta1(tvm.tensor.Tensor): A tensor with shape (1,) and type is same as var. beta2(tvm.tensor.Tensor): A scalar tensor of the same type as `var`. epsilon(tvm.tensor.Tensor): A scalar tensor of the same type as `var`. grad (tvm.tensor.Tensor): A tensor of same shape and type as var. use_nesterov(bool): Default value is False. If use_nesterov is True, the Nadam algorithm be implemented, otherwise the adam algorithm be implemented. Returns: tvm.tensor.Tensor, updated var. tvm.tensor.Tensor, updated m. tvm.tensor.Tensor, updated v. """ # check shape utils.check_shape(var) shape = get_shape(var) for tensor in (m, v, grad): utils.elemwise_shape_check(shape, tensor.shape) sclar_shape = (1,) for sclar in (beta1_power, beta2_power, lr, beta1, beta2, epsilon): utils.elemwise_shape_check(sclar.shape, sclar_shape) # check dtype dtype = var.dtype utils.ops_dtype_check(dtype, [utils.DtypeForDavinci.FLOAT16, utils.DtypeForDavinci.FLOAT32]) for tensor in (var, m, v, beta1_power, beta2_power, lr, beta1, beta2, epsilon, grad): utils.elemwise_dtype_check(tensor.dtype, dtype) var_new, m_new, v_new = _apply_adam_compute(var, m, v, beta1_power, beta2_power, lr, beta1, beta2, epsilon, grad, use_nesterov) # update by inplace (var_new, m_new, v_new), binds_info = TensorUtils.inplace_set_tensors([var, m, v], [var_new, m_new, v_new]) attrs = {utils.BINDS: binds_info} return var_new, m_new, v_new, attrs
def apply_adam(var, m, v, beta1_power, beta2_power, lr, beta1, beta2, epsilon, grad, use_nesterov=False, target=utils.CCE): """ Adam and Nadam optimization algorithm. Note: lr_t = lr*sqrt(1-beta2_power)/(1-beta1_power) m_new = m + (1-beta1)*(grad-m) v_new = v + (1-beta2)*(grad*grad-v) if user_nesterov == True: var_new = var - lr_t*(m_new*beta1 + (1-beta1)*grad) / (epsilon + sqrt(v_new)) else: var_new = var - lr_t*m_new / (epsilon + sqrt(v_new)) Args: var (tvm.tensor.Tensor): The tensor to be updated. Should be float16 or float32. m (tvm.tensor.Tensor): The first moment estimate. A tensor of same shape and type as var. v (tvm.tensor.Tensor): The second moment estimate. A tensor of same shape and type as var. beta1_power (tvm.tensor.Tensor): A scalar tensor of the same type as `var`. beta2_power (tvm.tensor.Tensor): A scalar tensor of the same type as `var`. lr (tvm.tensor.Tensor): The learning rate. A scalar tensor of the same type as `var`. beta1(tvm.tensor.Tensor): A tensor with shape (1,) and type is same as var. beta2(tvm.tensor.Tensor): A scalar tensor of the same type as `var`. epsilon(tvm.tensor.Tensor): A scalar tensor of the same type as `var`. grad (tvm.tensor.Tensor): A tensor of same shape and type as var. use_nesterov(bool): Default value is False. If use_nesterov is True, the Nadam algorithm be implemented, otherwise the adam algorithm be implemented. Returns: tvm.tensor.Tensor, updated var. tvm.tensor.Tensor, updated m. tvm.tensor.Tensor, updated v. """ # check shape utils.check_shape(var) shape = get_shape(var) for tensor in (m, v, grad): utils.elemwise_shape_check(shape, tensor.shape) sclar_shape = (1,) for sclar in (beta1_power, beta2_power, lr, beta1, beta2, epsilon): utils.elemwise_shape_check(sclar.shape, sclar_shape) # check dtype dtype = var.dtype utils.ops_dtype_check(dtype, [utils.DtypeForDavinci.FLOAT16, utils.DtypeForDavinci.FLOAT32]) for tensor in (var, m, v, beta1_power, beta2_power, lr, beta1, beta2, epsilon, grad): utils.elemwise_dtype_check(tensor.dtype, dtype) var_new, m_new, v_new = _apply_adam_compute(var, m, v, beta1_power, beta2_power, lr, beta1, beta2, epsilon, grad, use_nesterov) # update by inplace (var_new, m_new, v_new), binds_info = TensorUtils.inplace_set_tensors([var, m, v], [var_new, m_new, v_new]) attrs = {utils.BINDS: binds_info} return var_new, m_new, v_new, attrs
Python
def buffer_align(self, *args): """Set alignment requirements for realize bound of each axis Parameters ---------- args : List of alignment requirement for each axis of stage Each list alignment element is a tuple (min_align, extent_align) """ _api_internal._StageBufferAlign(self, args)
def buffer_align(self, *args): """Set alignment requirements for realize bound of each axis Parameters ---------- args : List of alignment requirement for each axis of stage Each list alignment element is a tuple (min_align, extent_align) """ _api_internal._StageBufferAlign(self, args)
Python
def emit_insn(self, var, value): """Annotate the iteration to emit insn Parameters ---------- var : IterVar The iteration to be unrolled. value : insn name """ value = convert(value) _api_internal._StagePragma(self, var, "emit_insn", value)
def emit_insn(self, var, value): """Annotate the iteration to emit insn Parameters ---------- var : IterVar The iteration to be unrolled. value : insn name """ value = convert(value) _api_internal._StagePragma(self, var, "emit_insn", value)
Python
def sparse_sf_ce_with_logits_tiling_strategy(tensor, out_shape): """Custom tiling strategy for sparse softmax cross entropy op.""" strategy = list() for i in range(len(out_shape)): if i != len(out_shape) - 1: strategy.append(ct_util.create_constraint_on_tensor(tensor=tensor, values=1, constraints=ct_util.TileConstraint.FACTOR, tensor_pos=i)[0]) else: tot_axis = ct_util.create_constraint_on_tensor(tensor=tensor, values="FULL", constraints=ct_util.TileConstraint.MAX, tensor_pos=i)[0] strategy.append(tot_axis) return strategy
def sparse_sf_ce_with_logits_tiling_strategy(tensor, out_shape): """Custom tiling strategy for sparse softmax cross entropy op.""" strategy = list() for i in range(len(out_shape)): if i != len(out_shape) - 1: strategy.append(ct_util.create_constraint_on_tensor(tensor=tensor, values=1, constraints=ct_util.TileConstraint.FACTOR, tensor_pos=i)[0]) else: tot_axis = ct_util.create_constraint_on_tensor(tensor=tensor, values="FULL", constraints=ct_util.TileConstraint.MAX, tensor_pos=i)[0] strategy.append(tot_axis) return strategy
Python
def SparseSoftmaxCrossEntropyWithLogits(labels, logits, reduction='mean', target=utils.CCE): """ Computes sparse softmax cross entropy between `logits` and `labels`. Note: Softmax calculation of Logits is done inside the op. Args: labels (tvm.tensor.Tensor): int32 tensor of shape [batch_size]. Each entry in it must be an index in `[0, num_classes)`. logits (tvm.tensor.Tensor): float32 or float16 tensor of shape [batch_size, num_class]. reduction (str): Specifies the reduction to apply to the output: 'none' or 'mean' or 'sum'. Default: 'mean'. 'none': no reduction for the output 'sum': the sum for the output 'mean': the mean for the output. Returns: tvm.tensor.Tensor, has the same dtype as logits. If reduction is 'none', shape of the tensor is the same as logits, otherwise shape of the tensor is the same as labels. Supported Platforms: 'Ascend' """ utils.ops_dtype_check(logits.dtype, utils.DtypeForDavinci.ALL_FLOAT) strategy, cost, _ = sparse_softmax_cross_entropy_with_logits_impl(labels, logits, reduction) attr_map = {"custom_tiling": strategy} return cost, attr_map
def SparseSoftmaxCrossEntropyWithLogits(labels, logits, reduction='mean', target=utils.CCE): """ Computes sparse softmax cross entropy between `logits` and `labels`. Note: Softmax calculation of Logits is done inside the op. Args: labels (tvm.tensor.Tensor): int32 tensor of shape [batch_size]. Each entry in it must be an index in `[0, num_classes)`. logits (tvm.tensor.Tensor): float32 or float16 tensor of shape [batch_size, num_class]. reduction (str): Specifies the reduction to apply to the output: 'none' or 'mean' or 'sum'. Default: 'mean'. 'none': no reduction for the output 'sum': the sum for the output 'mean': the mean for the output. Returns: tvm.tensor.Tensor, has the same dtype as logits. If reduction is 'none', shape of the tensor is the same as logits, otherwise shape of the tensor is the same as labels. Supported Platforms: 'Ascend' """ utils.ops_dtype_check(logits.dtype, utils.DtypeForDavinci.ALL_FLOAT) strategy, cost, _ = sparse_softmax_cross_entropy_with_logits_impl(labels, logits, reduction) attr_map = {"custom_tiling": strategy} return cost, attr_map
Python
def lamb_apply_optimizer_assign_set_dim_func(data): """set dim info for attr.""" shape = get_shape(data) hash_key = str((tuple(shape), data.dtype)) return ct_util.set_dims_by_key(hash_key, lamb_apply_optimizer_assign_set_dim_map), hash_key
def lamb_apply_optimizer_assign_set_dim_func(data): """set dim info for attr.""" shape = get_shape(data) hash_key = str((tuple(shape), data.dtype)) return ct_util.set_dims_by_key(hash_key, lamb_apply_optimizer_assign_set_dim_map), hash_key
Python
def bng1_tiling_strategy(tensor): """Custom tiling strategy for first part of splited fused_batch_norm_grad op""" # bn1 input [N, C1, C0, H, W] batch, _, in_h, in_w, _ = get_shape(tensor) batch_pos = 0 c0_pos = 4 c1_pos = 1 strategy = list() if batch > 1: strategy += ct_util.create_constraint_on_tensor( tensor=tensor, values=1, constraints=ct_util.TileConstraint.CANDIDATE, tensor_pos=batch_pos) if in_h != 1 or in_w != 1: strategy += ct_util.create_constraint_on_tensor( tensor=tensor, values="FULL", constraints=ct_util.TileConstraint.MAX, tensor_pos=c0_pos) strategy += ct_util.create_constraint_on_tensor( tensor=tensor, values=1, constraints=ct_util.TileConstraint.CANDIDATE, tensor_pos=c1_pos) strategy += ct_util.create_constraint_on_tensor( tensor=tensor, values=NUM_CORE, constraints=ct_util.TileConstraint.CANDIDATE, tensor_pos=c1_pos) return strategy
def bng1_tiling_strategy(tensor): """Custom tiling strategy for first part of splited fused_batch_norm_grad op""" # bn1 input [N, C1, C0, H, W] batch, _, in_h, in_w, _ = get_shape(tensor) batch_pos = 0 c0_pos = 4 c1_pos = 1 strategy = list() if batch > 1: strategy += ct_util.create_constraint_on_tensor( tensor=tensor, values=1, constraints=ct_util.TileConstraint.CANDIDATE, tensor_pos=batch_pos) if in_h != 1 or in_w != 1: strategy += ct_util.create_constraint_on_tensor( tensor=tensor, values="FULL", constraints=ct_util.TileConstraint.MAX, tensor_pos=c0_pos) strategy += ct_util.create_constraint_on_tensor( tensor=tensor, values=1, constraints=ct_util.TileConstraint.CANDIDATE, tensor_pos=c1_pos) strategy += ct_util.create_constraint_on_tensor( tensor=tensor, values=NUM_CORE, constraints=ct_util.TileConstraint.CANDIDATE, tensor_pos=c1_pos) return strategy
Python
def bng3_tiling_strategy(tensor): """Custom tiling strategy for 3rd part of splited fused_batch_norm_grad op""" # bn3 input [C1, C0, N, H, W] strategy_nc0 = list() n_pos = 0 c0_pos = 4 c1_pos = 1 strategy_nc0 += ct_util.create_constraint_on_tensor( tensor=tensor, values=1, constraints=ct_util.TileConstraint.CANDIDATE, tensor_pos=n_pos) strategy_nc0 += ct_util.create_constraint_on_tensor( tensor=tensor, values="FULL", constraints=ct_util.TileConstraint.MAX, tensor_pos=c0_pos) strategy_c1 = list() strategy_c1 += ct_util.create_constraint_on_tensor( tensor=tensor, values=1, constraints=ct_util.TileConstraint.CANDIDATE, tensor_pos=c1_pos) strategy_c1 += ct_util.create_constraint_on_tensor( tensor=tensor, values=NUM_CORE, constraints=ct_util.TileConstraint.CANDIDATE, tensor_pos=c1_pos) strategy = strategy_nc0 + strategy_c1 return strategy
def bng3_tiling_strategy(tensor): """Custom tiling strategy for 3rd part of splited fused_batch_norm_grad op""" # bn3 input [C1, C0, N, H, W] strategy_nc0 = list() n_pos = 0 c0_pos = 4 c1_pos = 1 strategy_nc0 += ct_util.create_constraint_on_tensor( tensor=tensor, values=1, constraints=ct_util.TileConstraint.CANDIDATE, tensor_pos=n_pos) strategy_nc0 += ct_util.create_constraint_on_tensor( tensor=tensor, values="FULL", constraints=ct_util.TileConstraint.MAX, tensor_pos=c0_pos) strategy_c1 = list() strategy_c1 += ct_util.create_constraint_on_tensor( tensor=tensor, values=1, constraints=ct_util.TileConstraint.CANDIDATE, tensor_pos=c1_pos) strategy_c1 += ct_util.create_constraint_on_tensor( tensor=tensor, values=NUM_CORE, constraints=ct_util.TileConstraint.CANDIDATE, tensor_pos=c1_pos) strategy = strategy_nc0 + strategy_c1 return strategy