file_path
stringlengths
7
180
content
stringlengths
0
811k
repo
stringclasses
11 values
python/tvm/topi/gpu/conv2d_nhwc.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=invalid-name, too-many-locals, too-many-statements, unused-argument """Direct conv2d in NHWC layout""" import tvm from tvm import te from tvm import autotvm from ..utils import get_const_tuple def schedule_conv2d_nhwc_direct(cfg, s, Conv): """schedule optimized for NHWC direct conv2d""" pad_data, kernel = s[Conv].op.input_tensors s[pad_data].compute_inline() if isinstance(kernel.op, tvm.te.ComputeOp) and "dilate" in kernel.op.tag: s[kernel].compute_inline() if Conv.op in s.outputs: output = Conv OL = s.cache_write(Conv, "local") else: output = s.outputs[0].output(0) s[Conv].set_scope("local") OL = Conv # create cache stage AA = s.cache_read(pad_data, "shared", [OL]) WW = s.cache_read(kernel, "shared", [OL]) AL = s.cache_read(AA, "local", [OL]) WL = s.cache_read(WW, "local", [OL]) # Currently Conv2d NHWC only support dynamic shpe in batch dynamic_batch = isinstance(s[output].op.axis[0].dom.extent, tvm.tir.expr.Var) # Schedule for autotvm cfg.define_knob("tile_n", [1] if dynamic_batch else [2, 4, 8]) cfg.define_knob("tile_c", [2, 4, 8]) cfg.define_knob("num_thread_n", [1] if dynamic_batch else [4, 8, 16]) cfg.define_knob("num_thread_c", [4, 8, 16]) cfg.define_knob("vthread_n", [1] if dynamic_batch else [1, 2]) cfg.define_knob("vthread_c", [1, 2]) cfg.define_knob("step", [16, 3, 32, 64]) cfg.define_knob("vectorize", [1, 2, 4, 8]) # fallback support target = tvm.target.Target.current() if cfg.is_fallback: ref_log = autotvm.tophub.load_reference_log( target.kind.name, target.model, "conv2d_nhwc.gpu" ) cfg.fallback_with_reference_log(ref_log) tile_n = cfg["tile_n"].val tile_c = cfg["tile_c"].val num_thread_n = cfg["num_thread_n"].val num_thread_c = cfg["num_thread_c"].val vthread_n = cfg["vthread_n"].val vthread_c = cfg["vthread_c"].val step = cfg["step"].val vec_factor = cfg["vectorize"].val block_factor_c = tile_c * num_thread_c * vthread_c offset = 8 A_align = step + offset W_align = block_factor_c + offset block_x = te.thread_axis("blockIdx.x") block_y = te.thread_axis("blockIdx.y") block_z = te.thread_axis("blockIdx.z") thread_x = te.thread_axis((0, num_thread_c), "threadIdx.x") thread_y = te.thread_axis((0, num_thread_n), "threadIdx.y") thread_xz = te.thread_axis((0, vthread_c), "vthread", name="vx") thread_yz = te.thread_axis((0, vthread_n), "vthread", name="vy") # Schedule for output ni, _, wi, fi = s[output].op.axis bx = wi fi, vec = s[output].split(fi, factor=vec_factor) s[output].vectorize(vec) tx, fi = s[output].split(fi, factor=tile_c) txz, tx = s[output].split(tx, factor=num_thread_c) bz, txz = s[output].split(txz, factor=vthread_c) ty, ni = s[output].split(ni, factor=tile_n) tyz, ty = s[output].split(ty, factor=num_thread_n) by, tyz = s[output].split(tyz, factor=vthread_n) s[output].reorder(bx, by, bz, tyz, txz, ty, tx, ni, fi, vec) s[output].bind(bz, block_z) s[output].bind(by, block_y) s[output].bind(bx, block_x) s[output].bind(tyz, thread_yz) s[output].bind(txz, thread_xz) s[output].bind(ty, thread_y) s[output].bind(tx, thread_x) # Schedule local computation s[OL].compute_at(s[output], tx) ni, yi, xi, fi = s[OL].op.axis ry, rx, rc = s[OL].op.reduce_axis rco, rci = s[OL].split(rc, factor=step) s[OL].vectorize(fi) s[OL].reorder(rco, ry, rx, rci, ni, fi) s[AA].compute_at(s[OL], rx) s[WW].compute_at(s[OL], rx) s[AL].compute_at(s[OL], rci) s[WL].compute_at(s[OL], rci) # Schedule for data's share memory ni, yi, xi, ci = s[AA].op.axis s[AA].reorder(yi, xi, ni, ci) s[AA].storage_align(xi, A_align - 1, A_align) t = s[AA].fuse(ni, ci) ty, tx = s[AA].split(t, factor=num_thread_c) _, ty = s[AA].split(ty, factor=num_thread_n) s[AA].bind(tx, thread_x) s[AA].bind(ty, thread_y) # Schedule for kernel's share memory _, _, ic, o = s[WW].op.axis t = s[WW].fuse(ic, o) s[WW].storage_align(ic, W_align - 1, W_align) t, vec = s[WW].split(t, factor=vec_factor) s[WW].vectorize(vec) ty, tx = s[WW].split(t, factor=num_thread_c) _, ty = s[WW].split(ty, factor=num_thread_n) s[WW].bind(tx, thread_x) s[WW].bind(ty, thread_y) N, OH, OW, CO = get_const_tuple(output.shape) KH, KW, CI, _ = get_const_tuple(kernel.shape) if isinstance(N, int): cfg.add_flop(2 * N * OH * OW * CO * CI * KH * KW)
https://github.com/zk-ml/tachikoma
python/tvm/topi/gpu/dense.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=invalid-name, unused-argument """Schedule for dense operator""" import logging from tvm import autotvm, te from tvm.autotvm.task.space import SplitEntity from .. import nn from ..utils import traverse_inline, get_const_tuple logger = logging.getLogger("topi") @autotvm.register_topi_compute("dense_small_batch.gpu") def dense_small_batch(cfg, data, weight, bias=None, out_dtype=None): """Dense operator on GPU""" return nn.dense(data, weight, bias, out_dtype) @autotvm.register_topi_schedule("dense_small_batch.gpu") def schedule_dense_small_batch(cfg, outs): """Schedule float32/64 dense with small batch size""" outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs s = te.create_schedule([x.op for x in outs]) def _callback(op): if op.tag == "dense": _schedule_dense_small_batch(cfg, s, op.output(0)) traverse_inline(s, outs[0].op, _callback) return s @autotvm.register_topi_compute("matmul_default.gpu") def matmul_default( cfg, tensor_a, tensor_b, bias=None, out_dtype=None, transpose_a=False, transpose_b=False, ): """Matmul operator on GPU""" return nn.matmul(tensor_a, tensor_b, bias, out_dtype, transpose_a, transpose_b) @autotvm.register_topi_schedule("matmul_default.gpu") def schedule_matmul_default(cfg, outs): """Schedule matmul on GPU""" outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs s = te.create_schedule([x.op for x in outs]) def _callback(op): if op.tag == "matmul": # Temporary use this as a basic schedule for matmul # TODO(jcf94): Add a more general schedule for matmul _schedule_dense_small_batch(cfg, s, op.output(0)) traverse_inline(s, outs[0].op, _callback) return s def _schedule_dense_small_batch(cfg, s, C): A, weights = C.op.input_tensors if len(weights.op.input_tensors) == 1 and weights.op.input_tensors[0] == A: s[weights].compute_inline() _, in_dim_weights = get_const_tuple(weights.shape) _, in_dim_A = get_const_tuple(A.shape) if isinstance(in_dim_A, int): in_dim = in_dim_A elif isinstance(in_dim_weights, int): in_dim = in_dim_weights else: in_dim = None if in_dim is not None: cfg.define_split("tile_k", in_dim, num_outputs=2) if cfg.is_fallback: cfg["tile_k"] = SplitEntity([-1, 64] if in_dim > 64 else [1, 64]) _, kf = cfg["tile_k"].apply(s, C, C.op.reduce_axis[0]) else: tile_k = 64 _, kf = s[C].split(C.op.reduce_axis[0], tile_k) CF = s.rfactor(C, kf) if C.op in s.outputs: Out = C else: Out = s.outputs[0].output(0) s[C].compute_at(s[Out], s[Out].op.axis[1]) s[Out].bind(s[Out].op.axis[0], te.thread_axis("blockIdx.y")) s[Out].bind(s[Out].op.axis[1], te.thread_axis("blockIdx.x")) tx = s[C].op.reduce_axis[0] thread_x = te.thread_axis("threadIdx.x") s[C].bind(tx, thread_x) s[CF].compute_at(s[C], tx) s[C].set_store_predicate(thread_x.var.equal(0)) s[Out].set_store_predicate(thread_x.var.equal(0)) @autotvm.register_topi_compute("dense_large_batch.gpu") def dense_large_batch(cfg, data, weight, bias=None, out_dtype=None): """Dense operator on GPU""" return nn.dense(data, weight, bias, out_dtype) @autotvm.register_topi_schedule("dense_large_batch.gpu") def schedule_dense_large_batch(cfg, outs): """Schedule float32/64 dense with large batch size""" outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs s = te.create_schedule([x.op for x in outs]) def _callback(op): if op.tag == "dense": _schedule_dense_large_batch(cfg, s, op.output(0)) traverse_inline(s, outs[0].op, _callback) return s def _schedule_dense_large_batch(cfg, s, C): """Schedule float32/64 dense with large batch size""" A, B = C.op.input_tensors if len(B.op.input_tensors) == 1 and B.op.input_tensors[0] == A: s[B].compute_inline() batch, in_dim = get_const_tuple(A.shape) out_dim, _ = get_const_tuple(B.shape) k = C.op.reduce_axis[0] # create tuning space try: block_cand = [64, 128] vthread_cand = [2**x for x in range(1, 7)] n_thread_cand = [2**x for x in range(3, 7)] cfg.define_split( "tile_x", batch, num_outputs=4, filter=lambda x: ( x.size[1] in vthread_cand and x.size[2] in n_thread_cand and (x.size[1] * x.size[2] * x.size[3]) in block_cand ), ) cfg.define_split( "tile_y", out_dim, num_outputs=4, filter=lambda x: ( x.size[1] in vthread_cand and x.size[2] in n_thread_cand and (x.size[1] * x.size[2] * x.size[3]) in block_cand ), ) cfg.define_split("tile_k", in_dim, num_outputs=3, filter=lambda x: x.size[0] > 2) except IndexError: # Index error happens when no entities left after filtering, which was designed # to prune tuning space for better search efficiency. logger.debug("Tuning space was created without pruning due to unfit shapes") cfg.define_split("tile_x", batch, num_outputs=4) cfg.define_split("tile_y", out_dim, num_outputs=4) cfg.define_split("tile_k", in_dim, num_outputs=3) if cfg.is_fallback: if batch > 1: cfg["tile_x"] = SplitEntity([-1, 2, 16, 2]) else: cfg["tile_x"] = SplitEntity([1, 1, 1, 1]) if out_dim > 1: cfg["tile_y"] = SplitEntity([-1, 2, 16, 2]) else: cfg["tile_y"] = SplitEntity([1, 1, 1, 1]) if in_dim > 8: cfg["tile_k"] = SplitEntity([-1, 8, 1]) else: cfg["tile_k"] = SplitEntity([-1, 1, 1]) # Explicit memory access AA = s.cache_read(A, "shared", [C]) BB = s.cache_read(B, "shared", [C]) AL = s.cache_read(AA, "local", [C]) BL = s.cache_read(BB, "local", [C]) CC = s.cache_write(C, "local") # Deal with op fusion if C.op not in s.outputs: s[C].compute_inline() C = s.outputs[0].output(0) # Split and reorder computation bx, txz, tx, xi = cfg["tile_x"].apply(s, C, C.op.axis[0]) by, tyz, ty, yi = cfg["tile_y"].apply(s, C, C.op.axis[1]) s[C].reorder(by, bx, tyz, txz, ty, tx, yi, xi) s[CC].compute_at(s[C], tx) # Binding s[C].bind(by, te.thread_axis("blockIdx.y")) s[C].bind(bx, te.thread_axis("blockIdx.x")) s[C].bind(tyz, te.thread_axis("vthread")) s[C].bind(txz, te.thread_axis("vthread")) s[C].bind(ty, te.thread_axis("threadIdx.y")) s[C].bind(tx, te.thread_axis("threadIdx.x")) # Split reduction yo, xo = CC.op.axis ko, kt, ki = cfg["tile_k"].apply(s, CC, k) s[CC].reorder(ko, kt, ki, yo, xo) s[AA].compute_at(s[CC], ko) s[BB].compute_at(s[CC], ko) s[CC].unroll(kt) s[AL].compute_at(s[CC], kt) s[BL].compute_at(s[CC], kt) # Schedule for A's shared memory load num_thread_x = cfg["tile_x"].size[2] ty, _ = s[AA].split(s[AA].op.axis[0], nparts=num_thread_x) _, xi = s[AA].split(s[AA].op.axis[1], factor=num_thread_x * 4) tx, xi = s[AA].split(xi, nparts=num_thread_x) s[AA].bind(ty, te.thread_axis("threadIdx.y")) s[AA].bind(tx, te.thread_axis("threadIdx.x")) s[AA].double_buffer() # Schedule for B' shared memory load num_thread_y = cfg["tile_y"].size[2] ty, _ = s[BB].split(s[BB].op.axis[0], nparts=num_thread_y) _, xi = s[BB].split(s[BB].op.axis[1], factor=num_thread_y * 4) tx, xi = s[BB].split(xi, nparts=num_thread_y) s[BB].bind(ty, te.thread_axis("threadIdx.y")) s[BB].bind(tx, te.thread_axis("threadIdx.x")) s[BB].double_buffer()
https://github.com/zk-ml/tachikoma
python/tvm/topi/hexagon/__init__.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """ Schedules for Hexagon. """ # pylint: disable=wildcard-import from .batch_matmul import * from .conv2d import * from .dense import * from .injective import * from .pad import * from .pooling import * from .reduce import * from .resize2d import * from .tensor_intrin import * from .qnn import * from .dense_alter_op import * from .conv2d_alter_op import *
https://github.com/zk-ml/tachikoma
python/tvm/topi/hexagon/batch_matmul.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """Schedule for composition of batch_matmul operator""" import tvm def schedule_batch_matmul(outs): """Schedule for batch_matmul op. Parameters ---------- outs: Array of Tensor The computation graph description of batch_matmul in the format of an array of tensors. Returns ------- sch: Schedule The computation schedule for the op. """ outs = [outs] if isinstance(outs, tvm.te.tensor.Tensor) else outs s = tvm.te.create_schedule([x.op for x in outs]) tvm.te.schedule.AutoInlineInjective(s) return s
https://github.com/zk-ml/tachikoma
python/tvm/topi/hexagon/conv2d.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=invalid-name """Schedule for conv2d""" import tvm from tvm import te from .. import nn from ..utils import traverse_inline from .tensor_intrin import dot_vrmpy from ..generic import conv2d as conv2d_generic def schedule_conv2d_nhwc(outs): """Schedule for conv2d NHWC operator. Parameters ---------- outs: Array of Tensor The computation graph description of conv2d in the format of an array of tensors. Returns ------- sch: Schedule The computation schedule for the op. """ outs = [outs] if isinstance(outs, tvm.te.tensor.Tensor) else outs s = tvm.te.create_schedule([x.op for x in outs]) tvm.te.schedule.AutoInlineInjective(s) return s def schedule_conv2d_nchw(outs): return schedule_conv2d_nhwc(outs) def schedule_conv2d(outs, layout="NHWC"): layout_uncase = layout.casefold() if layout_uncase == "NHWC".casefold(): return schedule_conv2d_nhwc(outs) if layout_uncase == "NCHW".casefold(): return schedule_conv2d_nchw(outs) raise ValueError(f"Unexpected layout={layout}") def schedule_depthwise_conv2d_nchw(outs): return schedule_conv2d_nchw(outs) def schedule_depthwise_conv2d_nhwc(out): return schedule_conv2d_nhwc(out) def schedule_conv2d_transpose_nchw(outs): """Create schedule for tensors""" outs = [outs] if isinstance(outs, tvm.te.tensor.Tensor) else outs s = schedule_conv2d_nchw(outs) def _callback(op): if "unpack_nchwc" in op.tag: conv_out = op.input_tensors[0] # retrieve data data_vec = conv_out.op.input_tensors[0] if isinstance(data_vec, tvm.te.ComputeOp): data_pad = data_vec.op.input_tensors[0] data_dilate = data_pad.op.input_tensors[0] s[data_dilate].compute_inline() s[data_pad].compute_inline() # retrieve kernel kernel_vec = conv_out.op.input_tensors[1] if isinstance(kernel_vec, tvm.te.ComputeOp): kernel_transform = kernel_vec.op.input_tensors[0] s[kernel_transform].compute_inline() traverse_inline(s, outs[0].op, _callback) return s def conv2d_NCHWc_int8( data, kernel, stride, padding, dilation, layout, out_layout, out_dtype="int32" ): """Compute definition for int8 conv2d in NCHWc layout""" n_elems = int(kernel.shape[-1]) return nn.conv2d_NCHWc_int8( data, kernel, stride, padding, dilation, layout, out_layout, out_dtype, n_elems=n_elems ) def schedule_conv2d_NCHWc_int8(outs): """Schedule for int8 conv2d in NCHWc layout using vrmpy tensorization""" s = te.create_schedule([x.op for x in outs]) def _callback(op): if "conv2d_NCHWc_int8" in op.tag: conv_out = op.output(0) kernel_vec = conv_out.op.input_tensors[1] data_vec = conv_out.op.input_tensors[0] out_width = conv_out.shape[3] reg_n = 1 for n in range(31, 0, -1): if out_width % n == 0: reg_n = n break cfg = {"tile_ow": reg_n, "unroll_kw": False} args = [s, cfg, data_vec, kernel_vec, conv_out, outs[0]] intrin = dot_vrmpy(data_vec.dtype, kernel_vec.dtype) conv2d_generic.schedule_conv_NCHWc_cpu_common_int8( *args, int32_lanes=32, int8_elems=4, intrin=intrin, inline_fused=True, ) traverse_inline(s, outs[0].op, _callback) return s
https://github.com/zk-ml/tachikoma
python/tvm/topi/hexagon/conv2d_alter_op.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=invalid-name,unused-variable,unused-argument,no-member """Conv2d alter op functions for Hexagon""" from tvm import relay from ..utils import get_const_tuple from .. import nn from ..nn import conv2d_alter_layout from ..generic.conv2d import conv2d_alter_int8_common @conv2d_alter_layout.register("hexagon") def _alter_conv2d_layout(attrs, inputs, tinfos, out_type): """Convert nn.conv2d into nn.contrib_conv2d_nchwc if vrmpy is applicable.""" new_attrs = {k: attrs[k] for k in attrs.keys()} data_layout = attrs["data_layout"] kernel_layout = attrs["kernel_layout"] data_tensor, kernel_tensor = tinfos out_channel, in_channel, _, _ = get_const_tuple(kernel_tensor.shape) if ( "int8" in data_tensor.dtype and "int8" in kernel_tensor.dtype and out_channel % 32 == 0 and in_channel % 4 == 0 and data_layout == "NCHW" and kernel_layout == "OIHW" ): out_channel, in_channel, _, _ = get_const_tuple(kernel_tensor.shape) n_elems = 4 oc_bn = 32 ic_bn = min(in_channel, 32) new_attrs = {k: attrs[k] for k in attrs.keys()} new_attrs["channels"] = out_channel new_attrs["data_layout"] = "NCHW%dc" % ic_bn new_attrs["kernel_layout"] = "OIHW{:n}i{:n}o{:n}i".format(ic_bn // n_elems, oc_bn, n_elems) new_attrs["out_layout"] = "NCHW%dc" % oc_bn return relay.nn.contrib_conv2d_nchwc(*inputs, **new_attrs) return None @nn.conv2d_legalize.register("hexagon") def _conv2d_legalize(attrs, inputs, arg_types): """Legalize conv2d op for vrmpy tensorization. If the inputs are signed or unsigned int8, the input and output channels are padded to be a multiple of 4 and 32 respectively. If the input data types are (int8, int8), they are converted to (uint8, int8) and the vector-by-vector variant of vrmpy is applied. If the input data types are (uint8, uint8), the more efficient vector-by-scalar variant of vrmpy is applied. Unlike the nn.dense case (see dense_alter_op.py), we do not convert (uint8, int8) to (uint8, uint8). That would introduce another convolution by a constant (128 or 1) filter, to compensate for the dtype legalization. In the nn.dense case, such compensation factor is just a sum over the K axis. """ data_layout = attrs["data_layout"] kernel_layout = attrs["kernel_layout"] output_tensor = arg_types[2] data, kernel = inputs if data_layout != "NCHW" or kernel_layout != "OIHW": return None data_tensor, kernel_tensor = arg_types[0], arg_types[1] if "int8" in data_tensor.dtype and "int8" in data_tensor.dtype: output_tensor = arg_types[2] data, kernel = inputs desired_data_dtype = "uint8" in_channel_vector_length = 4 out_channel_vector_length = 32 return conv2d_alter_int8_common( data, data_tensor, kernel, kernel_tensor, output_tensor, attrs, desired_data_dtype, in_channel_vector_length, out_channel_vector_length, ) return None
https://github.com/zk-ml/tachikoma
python/tvm/topi/hexagon/dense.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=invalid-name """Schedule for dense operator""" import tvm from tvm.topi.utils import traverse_inline from tvm import te from .. import tag from .tensor_intrin import dot_vrmpy def schedule_dense(outs): """Schedule for dense op. Parameters ---------- outs: Array of Tensor The computation graph description of dense in the format of an array of tensors. Returns ------- sch: Schedule The computation schedule for the op. """ outs = [outs] if isinstance(outs, tvm.te.tensor.Tensor) else outs s = tvm.te.create_schedule([x.op for x in outs]) tvm.te.schedule.AutoInlineInjective(s) return s def dense_u8u8i32_vrmpy_compute(X, packed_w, bias, out_dtype): """Compute for uint8 x uint8 -> int32 dense using vrmpy""" assert X.dtype == "uint8" and packed_w.dtype == "uint8" and out_dtype == "int32" m, k = X.shape n_o, _, n_i, _ = packed_w.shape assert n_i == 32 ak = te.reduce_axis((0, k), name="k") C = te.compute( (m, n_o * n_i), lambda i, j: te.sum( X[i, ak].astype("int32") * packed_w[tvm.tir.indexdiv(j, 32), tvm.tir.indexdiv(ak, 4), j % 32, ak % 4].astype( "int32" ), axis=ak, ), tag="dense_u8u8i32_vrmpy", name="compute", ) if bias is not None: C = te.compute(C.shape, lambda i, j: C[i, j] + bias[j], tag=tag.BROADCAST) return C def dense_u8u8i32_vrmpy_schedule(outs): """Schedule for vrmpy dense""" s = te.create_schedule([x.op for x in outs]) # O: The output of the fused op O = outs[0] def _schedule_dense(s, C, O): (a_k,) = C.op.reduce_axis a_y = C.op.axis[-2] a_yo, a_yi = s[C].split(a_y, factor=32) a_xo, a_xi = s[C].split(C.op.axis[-1], factor=32) a_ko, a_ki = s[C].split(a_k, factor=4) s[C].reorder(a_yo, a_xo, a_yi, a_ko, a_xi, a_ki) pc = dot_vrmpy("uint8", "uint8") s[C].tensorize(a_xi, pc) s[C].parallel(s[C].fuse(a_yo, a_xo)) if C != O: a_y = O.op.axis[-2] a_yo, a_yi = s[O].split(a_y, factor=32) a_xo, a_xi = s[O].split(O.op.axis[-1], factor=32) s[O].reorder(a_yo, a_xo, a_yi, a_xi) s[O].vectorize(a_xi) s[C].compute_at(s[O], a_yi) s[O].parallel(s[O].fuse(a_yo, a_xo)) def _callback(op): if "u8u8i32_vrmpy" in op.tag: # C: The output of GEMM C = op.output(0) _schedule_dense(s, C, O) traverse_inline(s, outs[0].op, _callback) return s
https://github.com/zk-ml/tachikoma
python/tvm/topi/hexagon/dense_alter_op.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=invalid-name,unused-variable,unused-argument,no-member """Dense alter op functions for ARM""" import tvm from tvm import relay from .. import nn from ..nn import dense_alter_layout def check_vrmpy_applicable(x, y): return ( "int8" in x.dtype and "int8" in y.dtype and y.shape[-2] % 32 == 0 and y.shape[-1] % 4 == 0 ) @dense_alter_layout.register(["hexagon"]) def _alter_dense_layout(attrs, inputs, tinfos, out_type): data_tensor, weight_tensor = tinfos out_dtype = out_type.dtype if check_vrmpy_applicable(data_tensor, weight_tensor): weight_layout = "NC32n4c" return relay.nn.contrib_dense_pack(inputs[0], inputs[1], weight_layout, None, out_dtype) else: return None def vrmpy_legalize(x, w, arg_types, op, attrs): """ Legalizes int8 inputs to dense for vrmpy. X'_u8 = X_s8 + 128 X_s8 * W_s8 = (X'_u8 - 128) * (W'_u8 - 128) = X'_u8 * W'_u8 - X'_u8 * 128 - 128 * W'_u8 + 128 * 128 X_u8 * W_s8 = X_u8 * (W'_u8 - 128) = X'_u8 * W'_u8 - X_u8 * 128 """ if not check_vrmpy_applicable(arg_types[0], arg_types[1]): return None def cast_to_uint8(x): x = relay.cast(x, "int32") x = relay.add(x, relay.const(128, "int32")) return relay.cast(x, "uint8") if arg_types[0].dtype == "int8" and arg_types[1].dtype == "int8": x = cast_to_uint8(x) w = cast_to_uint8(w) W_u8x128 = relay.const(-128, "int32") * relay.sum(relay.cast(w, "int32"), axis=[-1]) X_u8x128 = relay.const(-128, "int32") * relay.sum(relay.cast(x, "int32"), axis=[-1]) X_u8x128 = relay.expand_dims(X_u8x128, axis=1) out = op(x, w, **attrs) out += W_u8x128 out += X_u8x128 k_dim = int(arg_types[0].shape[-1]) return out + relay.const(128 * 128 * k_dim, "int32") if arg_types[0].dtype == "uint8" and arg_types[1].dtype == "int8": w = cast_to_uint8(w) X_u8x128 = relay.expand_dims( relay.const(-128, "int32") * relay.sum(relay.cast(x, "int32"), axis=[-1]), axis=1 ) out = op(x, w, **attrs) return out + X_u8x128 return None @nn.dense_legalize.register("hexagon") def _dense_legalize(attrs, inputs, arg_types): """Legalize dense op for HVX vectorization and vrmpy tensorization. Given a workload with a matrix X of shape (M, K) and a matrix Y of (N, K), we first pad the N dimension to be a multiple of the output vector length. And if the inputs are signed or unsigned int8 and the Y matrix can be packed into the NK32n4k layout, we convert both inputs to uint8 to apply the most efficient variant of vrmpy. """ new_attrs = {k: attrs[k] for k in attrs.keys()} # Collect the input tensors. x_tensor, y_tensor = arg_types[0], arg_types[1] dtype = x_tensor.dtype # Collect the output tensor. output_tensor = arg_types[2] # Collect the input exprs. x, y = inputs N, _ = y_tensor.shape if dtype == "float16": vec_len = 64 elif "int8" in dtype: vec_len = 32 else: return None if N % vec_len != 0: N_padded = ((N + vec_len) // vec_len) * vec_len dn = N_padded - N y_ = relay.nn.pad(y, pad_width=((0, dn), (0, 0))) # If units is explicitly specified, it is used to compute the output shape. # We need to update units after padding to prevent a type error. if attrs["units"] is not None: new_attrs["units"] = N + dn arg_types = [ arg_types[0], tvm.ir.tensor_type.TensorType([N + dn, arg_types[1].shape[1]], arg_types[1].dtype), ] vrmpy_out = vrmpy_legalize(x, y_, arg_types, relay.nn.dense, new_attrs) if vrmpy_out is None: out_ = relay.nn.dense(x, y_, **new_attrs) else: out_ = vrmpy_out out = relay.strided_slice(out_, begin=[0, 0], end=[x.value for x in output_tensor.shape]) return out return vrmpy_legalize(inputs[0], inputs[1], arg_types, relay.nn.dense, attrs)
https://github.com/zk-ml/tachikoma
python/tvm/topi/hexagon/injective.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """Schedule for injective operators""" import tvm import numpy as np def schedule_injective(outs): """Schedule for injective op. Parameters ---------- outs: Array of Tensor The computation graph description of injective in the format of an array of tensors. Returns ------- sch: Schedule The computation schedule for the op. """ outs = [outs] if isinstance(outs, tvm.te.tensor.Tensor) else outs s = tvm.te.create_schedule([x.op for x in outs]) tvm.te.schedule.AutoInlineInjective(s) # Fuse axes and vectorize inner elements for x in outs: fused = s[x].fuse(*x.op.axis) outer, inner = s[x].split(fused, factor=128 // np.dtype(x.dtype).itemsize) s[x].vectorize(inner) s[x].parallel(outer) return s def schedule_softmax(outs): return schedule_injective(outs) def schedule_elemwise(outs): return schedule_injective(outs) def schedule_broadcast(outs): return schedule_injective(outs)
https://github.com/zk-ml/tachikoma
python/tvm/topi/hexagon/pad.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """Schedule for nn.pad operator""" import tvm import numpy as np def schedule_pad(outs): """Schedule for pad op. Parameters ---------- outs: Array of Tensor The computation graph description of injective in the format of an array of tensors. Returns ------- sch: Schedule The computation schedule for the op. """ outs = [outs] if isinstance(outs, tvm.te.tensor.Tensor) else outs s = tvm.te.create_schedule([x.op for x in outs]) tvm.te.schedule.AutoInlineInjective(s) # Fuse axes and vectorize only if last output tensor dimension is divisible by a factor: factor = 128 // np.dtype(outs[0].dtype).itemsize last_dim = outs[0].shape[-1] if last_dim % factor == 0 and last_dim // factor >= 0: fused = s[outs[0]].fuse(*outs[0].op.axis) _, inner = s[outs[0]].split(fused, factor=factor) s[outs[0]].vectorize(inner) return s
https://github.com/zk-ml/tachikoma
python/tvm/topi/hexagon/pooling.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """Schedule for pooling operators""" import tvm def schedule_pool(outs, layout="NHWC"): # pylint: disable=unused-argument """Schedule for pooling op. Parameters ---------- outs: Array of Tensor The computation graph description of injective in the format of an array of tensors. layout: str The tensor layout. Returns ------- sch: Schedule The computation schedule for the op. """ outs = [outs] if isinstance(outs, tvm.te.tensor.Tensor) else outs s = tvm.te.create_schedule([x.op for x in outs]) tvm.te.schedule.AutoInlineInjective(s) return s def schedule_adaptive_pool(outs): return schedule_pool(outs)
https://github.com/zk-ml/tachikoma
python/tvm/topi/hexagon/qnn/__init__.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """ Computes and schedules for Hexagon quantized ops """ from .avg_pool2d import qnn_avg_pool2d_compute, qnn_avg_pool2d_schedule from .qadd_qsub_qmul import * from .dequantize import ( dequantize_compute, dequantize_schedule, ) from .quantize import quantize_compute, tir_quantize_schedule from .nn import * from .qdepthwise_conv2d_slice import qdepthwise_conv2d_compute, qdepthwise_conv2d_schedule
https://github.com/zk-ml/tachikoma
python/tvm/topi/hexagon/qnn/avg_pool2d.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=invalid-name, unused-variable, unused-argument, too-many-locals """ Compute and schedule for quantized avg_pool2d op Please note the following assumptions made by the implementation: 1) The input must be padded in advance to account for 'padding'. In addition, both input and output must be padded as per the physical buffer layout. 2) The current implementation assumes 'count_include_pad' to be 'True'. It can be modified to support 'False' case but the element count for the pooling window must be pre-computed and provided as an input to reduce the run-time overhead. 3) 'padding' is ignored. It must be handled outside of the sliced op. 4) Please note that this implementation will not work if the output includes any physical layout related padding as it can result into out-of-bound access for the input. """ from tvm import te from tvm import tir from ..utils import get_layout_transform_fn, get_fixed_point_value def validate_out_shape(out_shape: list, in_shape: list, kernel: list, stride: list, dilation: list): """Validate output shape""" _, oh, ow, _ = out_shape _, ih, iw, _ = in_shape kh, kw = kernel sh, sw = stride dh, dw = dilation if ih < (oh - 1) * sh + dh * (kh - 1) + 1: raise RuntimeError("Output height is too large") if iw < (ow - 1) * sw + dw * (kw - 1) + 1: raise RuntimeError("Output width is too large") def saturate(x: te.Tensor, dtype: str): """Saturate value for the specified data type""" return te.max(te.min_value(dtype), te.min(x, te.max_value(dtype))) def qnn_avg_pool2d_compute( data: te.Tensor, kernel: list, stride: list, dilation: list, oshape: list, odtype: str, # quantization params: input_zero_point: int, input_scale: float, output_zero_point: int, output_scale: float, ): """Compute for quantized avg_pool2d""" kh, kw = kernel rh = te.reduce_axis((0, kh), name="rh") rw = te.reduce_axis((0, kw), name="rw") ob, oh, ow, oc = oshape if isinstance(ob, int): validate_out_shape(oshape, data.shape, kernel, stride, dilation) if odtype == "uint8": temp_dtype = "uint16" elif odtype == "int8": temp_dtype = "int16" else: raise RuntimeError(f"Unsupported output dtype, {odtype}'") sh, sw = stride dh, dw = dilation PoolArea = kh * kw scale = input_scale / output_scale scale_fixed_point, rsh = get_fixed_point_value(scale, "int16") scale_with_area = scale_fixed_point // PoolArea corr = (output_zero_point << rsh) - input_zero_point * scale_fixed_point Sum = te.compute( oshape, lambda b, h, w, c: te.sum( data[b, h * sh + dh * rh, w * sw + dw * rw, c].astype(temp_dtype), axis=[rh, rw] ), name="sum", ) Avg = te.compute( oshape, lambda b, h, w, c: saturate( ((Sum[b, h, w, c] * scale_with_area) + corr) >> rsh, odtype ).astype(odtype), name="avg", ) return Avg def schedule_nhwc_8h8w32c(outs: te.Tensor, ins: te.Tensor, output_layout: str, input_layout: str): """Schedule for input and output layout nhwc-8h8w32c""" func = te.create_prim_func([ins, outs]) s = tir.Schedule(func) Sum = s.get_block("sum") Avg = s.get_block("avg") input_transform_fn = get_layout_transform_fn(input_layout) output_transform_fn = get_layout_transform_fn(output_layout) s.transform_layout(Sum, ("read", 0), input_transform_fn) s.transform_layout(Avg, ("write", 0), output_transform_fn) # Schedule 'Avg' # Split and reorder the axes to iterate over the output tensor chunks. # Each chunk consists for 2048 bytes with 32 channels being the fastest # changing axis, followed by 8 width and then 8 height. # The width is split by a factor of 4 and then fused with 32 channels # to provide full vector length of data for the output tensor chunks. # NOTE: These schedules are a work in progress and may require # adjustments in future as some of the missing features for 2-d tensors # become available. n, h, w, c = s.get_loops(Avg) ho, hi = s.split(h, [None, 8]) wo, wi = s.split(w, [None, 8]) wio, wii = s.split(wi, [None, 4]) co, ci = s.split(c, [None, 32]) s.reorder(n, ho, wo, co, hi, wio, wii, ci) wii_ci = s.fuse(wii, ci) s.vectorize(wii_ci) # Schedule 'Sum' s.compute_at(Sum, wio) Sum_axis = s.get_loops(Sum) # Compute for 'Sum' includes reduction along height and width. The axes # are being reordered so that 4 width and 32 channels become the # inner-most loops which then can be fused and vectorized. However, # vectorization of the 2-d tensors doesn't work when reduction is # involved and requires codegen support that is yet to be added. s.reorder(Sum_axis[-2], Sum_axis[-1], Sum_axis[-4], Sum_axis[-3]) ci_wii = s.fuse(Sum_axis[-4], Sum_axis[-3]) # s.vectorize(ci_wii) # Doesn't work return s def schedule_n11c_2048c(outs: te.Tensor, ins: te.Tensor, output_layout: str, input_layout: str): """Schedule for output layout: n11c-2048c, input layout: nhwc-8h8w32c""" func = te.create_prim_func([ins, outs]) s = tir.Schedule(func) Sum = s.get_block("sum") Avg = s.get_block("avg") input_transform_fn = get_layout_transform_fn(input_layout) output_transform_fn = get_layout_transform_fn(output_layout) s.transform_layout(Sum, ("read", 0), input_transform_fn) s.transform_layout(Avg, ("write", 0), output_transform_fn) # Schedule 'Avg' # Split and reorder the axes to iterate over the output tensor chunks. # Each chunk consists for 2048 bytes. For n11c-2048c tensor layout, each chunk # only contains 2048 channels which get split by a factor of 128 to be vectorized. # NOTE: These schedules are a work in progress and may require # adjustments in future as some of the missing features for 2-d tensors # become available. n, h, w, c = s.get_loops(Avg) co, ci = s.split(c, [None, 2048]) cio, cii = s.split(ci, [None, 128]) s.vectorize(cii) # Schedule 'Sum' # Compute for 'Sum' includes reduction along height and width. The axes are being # reordered so that 128 channels become the inner-most loop and can be vectorized. # However, vectorization of the 2-d tensors doesn't work when reduction is # involved and requires codegen support that is yet to be added. s.compute_at(Sum, cio) Sum_axis = s.get_loops(Sum) s.reorder(Sum_axis[-2], Sum_axis[-1], Sum_axis[-3]) # s.vectorize(Sum_axis[-3]) # Doesn't work return s def qnn_avg_pool2d_schedule(outs: te.Tensor, ins: te.Tensor, output_layout: str, input_layout: str): """Quantized avg_pool2d schedule NOTE: This schedule assumes that both input and output tensors are in the form of 2d discontiguous buffer and data is already arranged as per the input and output layout respectively. """ if output_layout == "nhwc-8h8w32c-2d": return schedule_nhwc_8h8w32c(outs, ins, output_layout, input_layout) if output_layout == "n11c-2048c-2d": return schedule_n11c_2048c(outs, ins, output_layout, input_layout) raise RuntimeError(f"Unexpected layout '{output_layout}'")
https://github.com/zk-ml/tachikoma
python/tvm/topi/hexagon/qnn/dequantize.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=invalid-name """ Hexagon qnn.dequantize slice op compute and schedule""" from tvm import te from tvm import tir from ..utils import get_layout_transform_fn def dequantize_compute(tensor_A, scale_A, zero_point_A): return te.compute( tensor_A.shape, lambda *indices: (scale_A * (tensor_A[indices] - zero_point_A)).astype("float32"), name="dequantize", ) def dequantize_stir_schedule_nhwc_8h8w32c( _in, _out, in_layout, out_layout, ): """Schedule for nhwc int8/uint8 to f32 : nhwc layout""" func = te.create_prim_func([_in, _out]) sch = tir.Schedule(func, debug_mask="all") block_name = "dequantize" n, h, w, c = sch.get_loops(sch.get_block(block_name)) ho, hi = sch.split(h, [None, 4]) wo, wi = sch.split(w, [None, 8]) wio, wii = sch.split(wi, [None, 4]) co, ci = sch.split(c, [None, 32]) sch.transform_layout(block_name, "A", in_layout) sch.transform_layout(block_name, block_name, out_layout) sch.reorder(n, ho, wo, co, hi, wio, wii, ci) wii_ci = sch.fuse(wii, ci) sch.vectorize(wii_ci) return sch def dequantize_stir_schedule_nc( _in, _out, in_layout, out_layout, ): """Schedule for nc int8/uint8 to f32 : nc layout""" func = te.create_prim_func([_in, _out]) sch = tir.Schedule(func, debug_mask="all") block_name = "dequantize" _, c_orig = sch.get_loops(sch.get_block(block_name)) _, c_inner = sch.split(c_orig, [None, 512]) sch.transform_layout(block_name, "A", in_layout) sch.transform_layout(block_name, block_name, out_layout) sch.vectorize(c_inner) return sch def dequantize_schedule(_in, _output, in_layout_str, out_layout_str): """Schedule for int8/uint8 to f32 : top level function""" f32_layout_transform_func = get_layout_transform_fn(out_layout_str) in_layout_transform_func = get_layout_transform_fn(in_layout_str) if out_layout_str == "nhwc-4h2w32c2w-2d": return dequantize_stir_schedule_nhwc_8h8w32c( _in, _output, in_layout_transform_func, f32_layout_transform_func, ) if out_layout_str == "nc-512c-2d": return dequantize_stir_schedule_nc( _in, _output, in_layout_transform_func, f32_layout_transform_func, ) raise RuntimeError(f"Unexpected layout '{layout}'")
https://github.com/zk-ml/tachikoma
python/tvm/topi/hexagon/qnn/nn.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """Hexagon QNN operators""" # pylint: disable=invalid-name import tvm from tvm import te, topi from ...utils import get_const_tuple from ...nn.utils import get_pad_tuple from ...nn.pad import pad from ... import tag, nn from ...x86.concat import concatenate def clip_cast(val, dtype): # clip + cast: const_min = tvm.tir.min_value(dtype) const_max = tvm.tir.max_value(dtype) return te.max(tvm.te.min(val, const_max), const_min).astype(dtype) def get_qnn_param(param, indices, axis): # Account scalar and 1D quantization parameters: if len(param.shape) == 0: return param param_idx = tvm.tir.indexmod(indices[axis], topi.shape(param)[0]) return param[param_idx] def default_schedule(outs): """Simple default schedule for QNN ops. Parameters ---------- outs: Array of Tensor The computation graph description of dense in the format of an array of tensors. Returns ------- sch: Schedule The computation schedule for the op. """ outs = [outs] if isinstance(outs, tvm.te.tensor.Tensor) else outs s = tvm.te.create_schedule([x.op for x in outs]) tvm.te.schedule.AutoInlineInjective(s) return s def qnn_quantize(data, output_scale, output_zero_point, axis, out_dtype): """Compute for qnn.quantize Q_output = clamp((round(input_tensor/output_scale) + output_zero_point), out_dtype::min, out_dtype::max) """ assert len(output_scale.shape) == 0 or len(output_scale.shape) == 1 assert len(output_zero_point.shape) == 0 or len(output_zero_point.shape) == 1 def _compute(*indices): value = data(*indices) scale = get_qnn_param(output_scale, indices, axis) zp = get_qnn_param(output_zero_point, indices, axis) val = te.add(te.round(te.div(value, scale)), zp) return clip_cast(val, out_dtype) return te.compute(data.shape, _compute, tag=tag.ELEMWISE) def schedule_qnn_quantize(outs): """Schedule for qnn.quantize Parameters ---------- outs: Array of Tensor The computation graph description of qnn.quantize in the format of an array of tensors. Returns ------- sch: Schedule The computation schedule for the op. """ return default_schedule(outs) def qnn_dequantize(data, input_scale, input_zero_point, axis): """Compute for qnn.dequantize fp_output = input_scale * (Q_input - input_zero_point) """ def _compute(*indices): value = data(*indices) scale = get_qnn_param(input_scale, indices, axis) zp = get_qnn_param(input_zero_point, indices, axis) return te.multiply(scale, te.subtract(value, zp)) return te.compute(data.shape, _compute, tag=tag.ELEMWISE) def schedule_qnn_dequantize(outs): """Schedule for qnn.dequantize Parameters ---------- outs: Array of Tensor The computation graph description of qnn.dequantize in the format of an array of tensors. Returns ------- sch: Schedule The computation schedule for the op. """ return default_schedule(outs) def qnn_requantize(data, input_scale, input_zp, output_scale, output_zp, axis, out_dtype): """Compute for qnn.requantize Q_output = zp_output + round((scale_input)/(scale_output) * (Q_input - zp_input)) TODO: support 'rounding' and 'compute_dtype' arguments. """ def _compute(*indices): value = data(*indices) iscale = get_qnn_param(input_scale, indices, axis) oscale = get_qnn_param(output_scale, indices, axis) sub = te.subtract(value, input_zp) mul = te.div(iscale, oscale) val = te.add(te.round(te.multiply(mul, sub)), output_zp) # clip + cast: const_min = tvm.tir.min_value(out_dtype) const_max = tvm.tir.max_value(out_dtype) return te.max(tvm.te.min(val, const_max), const_min).astype(out_dtype) return te.compute(data.shape, _compute) def schedule_qnn_requantize(outs): """Schedule for qnn.requantize Parameters ---------- outs: Array of Tensor The computation graph description of qnn.requantize in the format of an array of tensors. Returns ------- sch: Schedule The computation schedule for the op. """ return default_schedule(outs) def qnn_add( lhs, rhs, lhs_scale, lhs_zero_point, rhs_scale, rhs_zero_point, output_scale, output_zero_point ): """Compute for qnn.add Q_output = zp_output + round((lhs_scale)/(scale_output) * (lhs_input - lhs_zp_input)) + round((rhs_scale)/(scale_output) * (rhs_input - rhs_zp_input)) TODO: support 'axis' argument. """ assert lhs.dtype == rhs.dtype dtype = lhs.dtype def _compute(*indices): lvalue = lhs(*indices) rvalue = rhs(*indices) q_lv = te.round( te.multiply(te.div(lhs_scale, output_scale), te.subtract(lvalue, lhs_zero_point)) ).astype("int32") q_rv = te.round( te.multiply(te.div(rhs_scale, output_scale), te.subtract(rvalue, rhs_zero_point)) ).astype("int32") val = te.add(te.add(q_lv, q_rv), output_zero_point) # clip + cast: const_min = tvm.tir.min_value(dtype) const_max = tvm.tir.max_value(dtype) return te.max(tvm.te.min(val, const_max), const_min).astype(dtype) return te.compute(lhs.shape, _compute) def schedule_qnn_add(outs): """Schedule for qnn.add Parameters ---------- outs: Array of Tensor The computation graph description of qnn.add in the format of an array of tensors. Returns ------- sch: Schedule The computation schedule for the op. """ return default_schedule(outs) def requantize_tensor(tensor, i_scale, i_zp, o_scale, o_zp, out_dtype): """Requantize tensor""" def _compute(*indices): value = tensor(*indices) mul_value = te.round( te.multiply(te.div(i_scale, o_scale), te.subtract(value, i_zp)) ).astype("int32") rq_value = te.add(mul_value, o_zp) return clip_cast(rq_value, out_dtype) return te.compute(tensor.shape, _compute) def qnn_concatenate(data, axis, out_dtype): """Compute for qnn.concatenate Parameters ---------- data: Array of Tensor The computation graph description of qnn.concatenate in the format of an array of tensors. axis: int The axis along which the tensors are concatenated. out_dtype: string Data type of output tensor Returns ------- out: Tensor The computation for the op. """ # Get output quantization parameters. o_scale = data[-2] o_zp = data[-1] # Initially qnn.concatenate had 3 tuples: (1) tuple with input tensors, (2) tuple with input # scales and (3) tuple with input zero points. # Last 2 elements in data represent output scale and zero point. num_of_tuples = 3 assert ((len(data) - 2) % num_of_tuples) == 0 args_num = (len(data) - 2) // num_of_tuples args = [] for i in range(args_num): # Get next tensor and its quantization parameters. tensor = data[i] i_scale = data[i + args_num] i_zp = data[i + args_num * 2] # Requantize tensors and add them to the list. args.append(requantize_tensor(tensor, i_scale, i_zp, o_scale, o_zp, out_dtype)) # Call x86 implementation of concatenate. return concatenate(args, axis) def schedule_qnn_concatenate(outs): """Schedule for qnn.concatenate Parameters ---------- outs: Array of Tensor The computation graph description of qnn.add in the format of an array of tensors. Returns ------- sch: Schedule The computation schedule for the op. """ return default_schedule(outs) def qnn_conv2d( # Conv2d inputs data, weight, # Conv2d quantization params: input_zero_point, kernel_zero_point, _input_scale, _kernel_scale, # bias bias, # Requantization params: rq_input_scale, rq_input_zero_point, rq_output_scale, rq_output_zero_point, # Conv2d attributes: strides, padding, dilation, oshape, odtype, ): """Compute for qnn.conv2d with NCHW layout. Output data type should be specified through the 'odtype' parameter. qnn.conv2d leverages int32 type to store intermediate results. If 'odtype' differs from int32, you need to specify requantization parameters. """ in_channel = data.shape[1] # NCHW layout kernel_height = weight.shape[2] # OIHW layout kernel_width = weight.shape[3] # OIHW layout height_stride, width_stride = strides dilation_h, dilation_w = dilation dilated_kernel_h = (kernel_height - 1) * dilation_h + 1 dilated_kernel_w = (kernel_width - 1) * dilation_w + 1 pad_top, pad_left, pad_down, pad_right = get_pad_tuple( get_const_tuple(padding), (dilated_kernel_h, dilated_kernel_w) ) # Subtract zero point from input and then do padding with 0 value data = te.compute(data.shape, lambda *indices: te.subtract(data(*indices), input_zero_point)) # DOPAD if pad_top != 0 or pad_down != 0 or pad_left != 0 or pad_right != 0: pad_before = (0, 0, pad_top, pad_left) pad_after = (0, 0, pad_down, pad_right) data_pad = pad(data, pad_before, pad_after, name="data_pad") else: data_pad = data ic = te.reduce_axis((0, in_channel), name="ic") kh = te.reduce_axis((0, kernel_height), name="kh") kw = te.reduce_axis((0, kernel_width), name="kw") # axis=0 in get_qnn_param means 'O' dimension in "OIHW" weights layout. out = te.compute( oshape, lambda n, oc, oh, ow: te.sum( data_pad[ n, ic, oh * height_stride + kh * dilation_h, ow * width_stride + kw * dilation_w, ].astype("int32") * te.subtract( weight[oc, ic, kh, kw], get_qnn_param(kernel_zero_point, (oc, ic, kh, kw), axis=0) ).astype("int32"), axis=[ic, kh, kw], ), ) # Add bias if bias is not None: assert len(out.shape) == len(bias.shape) assert bias.shape[2] == 1 and bias.shape[3] == 1 out = te.compute(out.shape, lambda n, c, h, w: out[n, c, h, w] + bias[n, c, 0, 0]) # Requantize output of convolution # Q_output = zp_output + round((scale_input)/(scale_output) * (Q_input - zp_input)) if rq_input_scale is not None and rq_output_scale is not None: # Now supported only scalar and 1D quantization parameters assert len(rq_input_scale.shape) == 0 or len(rq_input_scale.shape) == 1 assert len(rq_output_scale.shape) == 0 or len(rq_output_scale.shape) == 1 axis = -1 if len(rq_input_scale.shape) == 1 or len(rq_output_scale.shape) == 1: axis = 1 # Axis param should correspond to 'C' dimension. return qnn_requantize( out, rq_input_scale, rq_input_zero_point, rq_output_scale, rq_output_zero_point, axis, odtype, ) return out def schedule_qnn_conv2d(outs): """Schedule for qnn.conv2d Parameters ---------- outs: Array of Tensor The computation graph description of qnn.conv2d in the format of an array of tensors. Returns ------- sch: Schedule The computation schedule for the op. """ return default_schedule(outs) def qnn_depthwise_conv2d( # Conv2d inputs data, weight, # Conv2d quantization params: input_zero_point, kernel_zero_point, _input_scale, _kernel_scale, # bias bias, # Requantization params: rq_input_scale, rq_input_zero_point, rq_output_scale, rq_output_zero_point, # Conv2d attributes: strides, padding, dilation, oshape, odtype, ): """Compute for qnn.conv2d with NCHW layout Output data type should be specified through the 'odtype' parameter. qdepthwise nn.conv2d leverages int32 type to store intermediate results. If 'odtype' differs from int32, you need to specify requantization parameters. """ kernel_height = weight.shape[2] # OIHW layout kernel_width = weight.shape[3] # OIHW layout height_stride, width_stride = strides dilation_h, dilation_w = dilation dilated_kernel_h = (kernel_height - 1) * dilation_h + 1 dilated_kernel_w = (kernel_width - 1) * dilation_w + 1 pad_top, pad_left, pad_down, pad_right = get_pad_tuple( get_const_tuple(padding), (dilated_kernel_h, dilated_kernel_w) ) # Subtract zero point from input and then do padding with 0 value data = te.compute(data.shape, lambda *indices: te.subtract(data(*indices), input_zero_point)) # DOPAD if pad_top != 0 or pad_down != 0 or pad_left != 0 or pad_right != 0: pad_before = (0, 0, pad_top, pad_left) pad_after = (0, 0, pad_down, pad_right) data_pad = pad(data, pad_before, pad_after, name="data_pad") else: data_pad = data kh = te.reduce_axis((0, kernel_height), name="kh") kw = te.reduce_axis((0, kernel_width), name="kw") out = te.compute( oshape, lambda n, oc, oh, ow: te.sum( data_pad[ n, oc, oh * height_stride + kh * dilation_h, ow * width_stride + kw * dilation_w, ].astype("int32") * te.subtract(weight[oc, 0, kh, kw], kernel_zero_point).astype("int32"), axis=[kh, kw], ), ) # Add bias if bias is not None: assert len(out.shape) == len(bias.shape) assert bias.shape[2] == 1 and bias.shape[3] == 1 out = te.compute(out.shape, lambda n, c, h, w: out[n, c, h, w] + bias[n, c, 0, 0]) # Requantize output of convolution # Q_output = zp_output + round((scale_input)/(scale_output) * (Q_input - zp_input)) if rq_input_scale is not None and rq_output_scale is not None: # Now supported only scalar and 1D quantization parameters assert len(rq_input_scale.shape) == 0 or len(rq_input_scale.shape) == 1 assert len(rq_output_scale.shape) == 0 or len(rq_output_scale.shape) == 1 axis = -1 if len(rq_input_scale.shape) == 1 or len(rq_output_scale.shape) == 1: axis = 1 # Axis param should correspond to 'C' dimension. return qnn_requantize( out, rq_input_scale, rq_input_zero_point, rq_output_scale, rq_output_zero_point, axis, odtype, ) return out def schedule_qnn_depthwise_conv2d(outs): """Schedule for depthwise qnn.conv2d Parameters ---------- outs: Array of Tensor The computation graph description of qnn.conv2d in the format of an array of tensors. Returns ------- sch: Schedule The computation schedule for the op. """ return default_schedule(outs) def qnn_dense( data, weight, # Dense quantization params: input_zero_point, kernel_zero_point, _input_scale, _kernel_scale, # bias bias, # Requantization params: rq_input_scale, rq_input_zero_point, rq_output_scale, rq_output_zero_point, out_dtype, ): """Compute for qnn.dense Output data type should be specified through the 'odtype' parameter. qnn.dense leverages int32 type to store intermediate results. If 'odtype' differs from int32, you need to specify requantization parameters. """ M, K = get_const_tuple(data.shape) N, _ = get_const_tuple(weight.shape) k = te.reduce_axis((0, K), "k") # This implementation uses "int32" dense output data type. # axis=0 in get_qnn_param mean 'N' dimension in "NK" weights layout. out = te.compute( (M, N), lambda m, n: te.sum( te.subtract(data[m, k], input_zero_point).astype("int32") * te.subtract(weight[n, k], get_qnn_param(kernel_zero_point, (n, k), axis=0)).astype( "int32" ), axis=k, ), ) # Add bias if bias is not None: out = te.compute(out.shape, lambda n, c: out[n, c] + bias[c]) # Requantize output of dense # Q_output = zp_output + round((scale_input)/(scale_output) * (Q_input - zp_input)) if rq_input_scale is not None and rq_output_scale is not None: # Now supported only scalar and 1D quantization parameters assert len(rq_input_scale.shape) == 0 or len(rq_input_scale.shape) == 1 assert len(rq_output_scale.shape) == 0 or len(rq_output_scale.shape) == 1 axis = -1 if len(rq_input_scale.shape) == 1 or len(rq_output_scale.shape) == 1: axis = 1 # Axis param should correspond to 'N' dimension. return qnn_requantize( out, rq_input_scale, rq_input_zero_point, rq_output_scale, rq_output_zero_point, axis, out_dtype, ) return out def schedule_qnn_dense(outs): """Schedule for qnn.dense Parameters ---------- outs: Array of Tensor The computation graph description of qnn.dense in the format of an array of tensors. Returns ------- sch: Schedule The computation schedule for the op. """ return default_schedule(outs) def qnn_batch_matmul( tensor_a, tensor_b, # batch_matmul quantization params: a_zero_point, b_zero_point, _a_scale, _b_scale, # Attributes transpose_a, transpose_b, out_dtype, ): """Compute for qnn.batch_matmul""" # Preprocess tensor_a: subtract zp a_sub_zp = te.compute( tensor_a.shape, lambda *indices: te.subtract(tensor_a(*indices), a_zero_point) ) # Preprocess tensor_b: subtract zp b_sub_zp = te.compute( tensor_b.shape, lambda *indices: te.subtract(tensor_b(*indices), b_zero_point) ) return nn.batch_matmul(a_sub_zp, b_sub_zp, None, out_dtype, transpose_a, transpose_b) def schedule_qnn_batch_matmul(outs): """Schedule for qnn.batch_matmul Parameters ---------- outs: Array of Tensor The computation graph description of qnn.batch_matmul in the format of an array of tensors. Returns ------- sch: Schedule The computation schedule for the op. """ return default_schedule(outs)
https://github.com/zk-ml/tachikoma
python/tvm/topi/hexagon/qnn/qadd_qsub_qmul.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=invalid-name """Compute and schedule for quantized add, multiply, subtract op Please note the following assumptions made by the implementation: 1) The inputs will be multiple of crouton layout except for the axis that needs broadcasting.""" from tvm import te from tvm import tir from ..utils import get_layout_transform_fn, get_fixed_point_value def broadcast_axis(tensor_A, tensor_B): """Find out the indices that will have broadcasting""" A_broadcast = [] B_broadcast = [] for i in range(len(tensor_A.shape)): if tensor_A.shape[i] == tensor_B.shape[i]: A_broadcast.append(1) B_broadcast.append(1) elif tensor_A.shape[i] == 1: A_broadcast.append(0) B_broadcast.append(1) elif tensor_B.shape[i] == 1: A_broadcast.append(1) B_broadcast.append(0) return A_broadcast, B_broadcast def saturate(x: te.Tensor, dtype: str): """Saturate value for the specified data type""" return te.max(te.min_value(dtype), te.min(x, te.max_value(dtype))) def get_int_scale( scale_A: float, scale_B: float, scale_M: float, zero_point_A: int, zero_point_B: int, zero_point_M: int, op: str, ): """ Get fixed-point number and exp_scale_factor from topi.hexagon.utils.get_fixed_point_value. Also, depending on the op, this function uses exp_scale_factor(log2 of the scale factor) to adjust the output's zero_point. """ C_recip = 1 / scale_M if op == "qmul": scale = scale_A * scale_B * C_recip scale_fixed_point, rsh = get_fixed_point_value(scale, "int16") # We need to adjust output's zero point value since the compute for the op is multiplied # by a scaling factor. # The scaling factor is 2^x where x is the exp_scale_factor which is assigned to rsh here. # Since zero_point_M is multipled by 2^rsh while converting floating-point scale value # into fixed-point number, we left shift it by rsh in our compute to reflect that. corr = zero_point_M << rsh return scale_fixed_point, rsh, corr a_scale_f = scale_A * C_recip b_scale_f = scale_B * C_recip scale_fixed_point_a, rsh_a = get_fixed_point_value(a_scale_f, "int16") scale_fixed_point_b, rsh_b = get_fixed_point_value(b_scale_f, "int16") # Here we have two exp_scale_factors rsh_a and rsh_b. # To avoid complexity, we want to use a common exp_scale_factor and # we want to use the lowest of the two. # Since, either of scale_fixed_point_a or scale_fixed_point_b has already been multiplied # by 2^max(rsh_a, rsh_b) in topi.hexagon.utils.get_fixed_point_value, # we want to undo that by right shifting that scale_fixed_point value # by the difference of rsh_a and rsh_b. # This results into having a common exp_scale_factor for both scale_fixed_point_a # and scale_fixed_point_b. # We also set rsh here which is used to adjust the zero_point_M and compute the corr value, # computation of which comes from the original equation of the op's compute. if rsh_a > rsh_b: scale_fixed_point_a = scale_fixed_point_a >> (rsh_a - rsh_b) rsh = rsh_b else: scale_fixed_point_b = scale_fixed_point_b >> (rsh_b - rsh_a) rsh = rsh_a if op == "qadd": corr = (zero_point_M << rsh) - ( zero_point_A * scale_fixed_point_a + zero_point_B * scale_fixed_point_b ) else: corr = (zero_point_M << rsh) - ( zero_point_A * scale_fixed_point_a - zero_point_B * scale_fixed_point_b ) return scale_fixed_point_a, scale_fixed_point_b, rsh, corr def qadd_broadcast_compute( tensor_A: te.Tensor, tensor_B: te.Tensor, output_shape: list, zero_point_A: int, scale_A: float, zero_point_B: int, scale_B: float, zero_point_M: int, scale_M: float, dtype: str, ): """Compute quantized add with broadcasting""" A_broadcast, B_broadcast = broadcast_axis(tensor_A, tensor_B) n_a, h_a, w_a, c_a = A_broadcast n_b, h_b, w_b, c_b = B_broadcast scale_a, scale_b, rsh, corr = get_int_scale( scale_A, scale_B, scale_M, zero_point_A, zero_point_B, zero_point_M, "qadd" ) return te.compute( output_shape, lambda n, h, w, c: saturate( ( ( (tensor_A[n * n_a, h * h_a, w * w_a, c * c_a] * scale_a) + (tensor_B[n * n_b, h * h_b, w * w_b, c * c_b] * scale_b) + corr ) >> rsh ), dtype, ).astype(dtype), ) def qsubtract_broadcast_compute( tensor_A: te.Tensor, tensor_B: te.Tensor, output_shape: list, zero_point_A: int, scale_A: float, zero_point_B: int, scale_B: float, zero_point_M: int, scale_M: float, dtype: str, ): """Compute quantized subtract with broadcasting""" A_broadcast, B_broadcast = broadcast_axis(tensor_A, tensor_B) n_a, h_a, w_a, c_a = A_broadcast n_b, h_b, w_b, c_b = B_broadcast scale_a, scale_b, rsh, corr = get_int_scale( scale_A, scale_B, scale_M, zero_point_A, zero_point_B, zero_point_M, "qsub" ) return te.compute( output_shape, lambda n, h, w, c: saturate( ( ( (tensor_A[n * n_a, h * h_a, w * w_a, c * c_a] * scale_a) - (tensor_B[n * n_b, h * h_b, w * w_b, c * c_b] * scale_b) + corr ) >> rsh ), dtype, ).astype(dtype), ) def qmultiply_broadcast_compute( tensor_A: te.Tensor, tensor_B: te.Tensor, output_shape: list, zero_point_A: int, scale_A: float, zero_point_B: int, scale_B: float, zero_point_M: int, scale_M: float, dtype: str, ): """Compute quantized multiply with broadcasting""" A_broadcast, B_broadcast = broadcast_axis(tensor_A, tensor_B) n_a, h_a, w_a, c_a = A_broadcast n_b, h_b, w_b, c_b = B_broadcast scale_int, rsh, corr = get_int_scale( scale_A, scale_B, scale_M, zero_point_A, zero_point_B, zero_point_M, "qmul" ) return te.compute( output_shape, lambda n, h, w, c: saturate( ( ( scale_int * (tensor_A[n * n_a, h * h_a, w * w_a, c * c_a] - zero_point_A) * (tensor_B[n * n_b, h * h_b, w * w_b, c * c_b] - zero_point_B) + corr ) >> rsh ), dtype, ).astype(dtype), ) def tir_schedule_quant( out_M: te.Tensor, tensor_A: te.Tensor, tensor_B: te.Tensor, output_layout: str, tensor_A_layout: str, tensor_B_layout: str, ): """Schedule for output layout nhwc-8h8w32c-2d""" func = te.create_prim_func([tensor_A, tensor_B, out_M]) s = tir.Schedule(func) block = s.get_block("compute") if tensor_A_layout == "nhwc-8h8w32c-2d": tensor_A_transformed_layout = get_layout_transform_fn(tensor_A_layout) s.transform_layout(block, buffer=tensor_A.name, index_map=tensor_A_transformed_layout) if tensor_B_layout == "nhwc-8h8w32c-2d": tensor_B_transformed_layout = get_layout_transform_fn(tensor_B_layout) s.transform_layout(block, buffer=tensor_B.name, index_map=tensor_B_transformed_layout) output_transformed_layout = get_layout_transform_fn(output_layout) s.transform_layout(block, buffer=out_M.name, index_map=output_transformed_layout) n, h, w, c = s.get_loops(block) h_o, h_i = s.split(h, [None, 8]) w_o, w_i = s.split(w, [None, 8]) c_o, c_i = s.split(c, [None, 32]) wio, wii = s.split(w_i, [None, 4]) s.reorder(n, h_o, w_o, c_o, h_i, wio, wii, c_i) return s
https://github.com/zk-ml/tachikoma
python/tvm/topi/hexagon/qnn/qdepthwise_conv2d_slice.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=invalid-name, unused-variable, unused-argument, too-many-locals """ Please note the following assumptions made by the implementation: 1) The input must be padded in advance to account for 'padding'. In addition, both input and output must be padded as per the physical buffer layout. 2) 'padding' is ignored. It must be handled outside of the sliced op. 3) The weights are expected to be as per physical layout The initial compute for quantized depthwise conv2d is as follows where cm = channel_multiplier; assumed to be 1, zp_a = Activation_zero_point, zp_w = Weight_zero_point, Qa = Quantized Activation, Qw = Quantized Weights. a) Qc(n, oh, ow, oc) = (Sigma(r, s) (Qw(r, s, oc%cm, oc/cm) - zp_w) * (Qa(n, oh + r, ow + s, oc/cm) - zp_a)) * scale_value where scale_value = (activation_scale * weight_scale) / output_scale This can be written as b) Qc(n, oh, ow, oc) = (t1 - t2 - t3 + t4) * scale_value where t1 = Sigma(r, s) Qw(r, s, oc%cm, oc/cm) * Qa(n, oh + r, ow + s, oc/cm) t2 = Sigma(r, s) zp_w * Qa(n, oh + r, ow + s, oc/cm) t3 = Sigma(r, s) zp_a * Qw(r, s, oc%cm, oc/cm) t4 = Sigma(r, s) zp_a * zp_w c) Qc(n, oh, ow, oc) = saturate(((t1 - t2 - t3 + t4) * fixed_scale_value)) >> rsh) where fixed_scale_value, rsh are fixed point values for scale_value. Compute and schedule for quantized depthwise conv2d slice op""" import typing import tvm from tvm import te from ..utils import get_layout_transform_fn, get_fixed_point_value, saturate def qdepthwise_conv2d_compute( activations: te.Tensor, weights: te.Tensor, out_shape: typing.Tuple, stride: typing.Tuple, dilation: typing.Tuple, dtype: str, # quantization params: activation_zero_point, activation_scale, weight_zero_point, weight_scale, output_zero_point, output_scale, ): """Compute for quantized depthwise conv2d""" filt_shape = weights.shape ob, oh, ow, oc = out_shape if dtype == "uint8": temp_dtype = "int32" big_dtype = "int64" elif dtype == "int8": temp_dtype = "int32" big_dtype = "int64" else: raise RuntimeError(f"Unsupported output dtype, {odtype}'") reduce_height = tvm.te.reduce_axis((0, filt_shape[0]), name="reduce_height") reduce_width = tvm.te.reduce_axis((0, filt_shape[1]), name="reduce_width") stride_height, stride_width = stride dilation_height, dilation_width = dilation scale_value = (activation_scale * weight_scale) / output_scale fixed_scale_value, rsh = get_fixed_point_value(scale_value, "int16") t1 = tvm.te.compute( out_shape, lambda n, h, w, c: tvm.te.sum( ( ( activations[ n, h * stride_height + reduce_height * dilation_height, w * stride_width + reduce_width * dilation_width, c, ].astype(temp_dtype) ) * (weights[reduce_height, reduce_width, 0, c].astype(temp_dtype)) ).astype(temp_dtype), axis=[reduce_height, reduce_width], ), name="t1", ) t2 = tvm.te.compute( out_shape, lambda n, h, w, c: tvm.te.sum( ( ( activations[ n, h * stride_height + reduce_height * dilation_height, w * stride_width + reduce_width * dilation_width, c, ].astype(temp_dtype) ) * weight_zero_point ).astype(temp_dtype), axis=[reduce_height, reduce_width], ), name="t2", ) t3 = tvm.te.compute( (oc,), lambda c: tvm.te.sum( ( ((weights[reduce_height, reduce_width, 0, c].astype(temp_dtype))) * activation_zero_point ).astype(temp_dtype), axis=[reduce_height, reduce_width], ), name="t3", ) t4 = activation_zero_point * weight_zero_point * reduce_height * reduce_width output = tvm.te.compute( out_shape, lambda n, h, w, c: saturate( ( ( ( ((t1[n, h, w, c]).astype(big_dtype) - t2[n, h, w, c] - t3[c] + t4) * fixed_scale_value ) >> rsh ) + (output_zero_point).astype(big_dtype) ), dtype, ).astype(dtype), name="output", ) return output def qdepthwise_conv2d_schedule( outs: te.Tensor, ins: typing.List[te.Tensor], transform_activation_layout: str, transform_weights: str, ): """ Schedule for quantized depthwise conv2d for input layout nhwc-8h8w32c assert len(ins) == 2, "This schedule expects only 2 inputs - Activations and Weights """ source_expr = ins + [outs] prim_func = tvm.te.create_prim_func(source_expr) sch = tvm.tir.Schedule(prim_func) compute = sch.get_block("output") compute1 = sch.get_block("t1") transform_layout_fn = get_layout_transform_fn(transform_activation_layout) transform_layout_weights = get_layout_transform_fn(transform_weights) # Apply layout_transform for activation sch.transform_layout(compute1, ins[0].name, transform_layout_fn) # Apply layout_transform for weights sch.transform_layout(compute1, ins[1].name, transform_layout_weights) # Apply layout_transform for output sch.transform_layout(compute, outs.name, transform_layout_fn) # This returns the original 6d loop batch, height, width, channel, reduce_height, reduce_width = sch.get_loops(compute1) h_outer, h_inner = sch.split(height, [None, 8]) w_outer, w_inner = sch.split(width, [None, 8]) c_outer, c_inner = sch.split(channel, [None, 32]) sch.reorder( batch, h_outer, w_outer, c_outer, h_inner, reduce_height, reduce_width, w_inner, c_inner, ) sch.decompose_reduction(compute1, reduce_height) # wi_ci = sch.fuse(w_inner,c_inner) # sch.vectorize(wi_ci) return sch
https://github.com/zk-ml/tachikoma
python/tvm/topi/hexagon/qnn/quantize.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=invalid-name """Compute and schedule for hexagon quantize Please note the following assumptions made by the implementation: 1) The input and output data will be multiple of crouton layout 2) And the supported layout is NHWC 3) The input layout will be nhwc-4h2w32c2w-2d and output layout will be nhwc-8h8w32c-2d""" from tvm import te from tvm import tir from ..utils import get_layout_transform_fn, saturate def quantize_compute(tensor_A: te.Tensor, scale: float, zero_point: int, dtype: str): """Compute for quantize""" scale_recip = 1 / scale return te.compute( tensor_A.shape, lambda n, h, w, c: saturate( ((tensor_A[n, h, w, c] * scale_recip).astype("int32") + zero_point), dtype, ).astype(dtype), name="quantize", ) def tir_quantize_schedule( out_M: te.Tensor, tensor_A: te.Tensor, input_layout: str, output_layout: str, ): """Schedule for output layout nhwc-8h8w32c-2d""" func = te.create_prim_func([tensor_A, out_M]) s = tir.Schedule(func) block = s.get_block("quantize") input_transformed_layout = get_layout_transform_fn(input_layout) s.transform_layout(block, buffer=tensor_A.name, index_map=input_transformed_layout) output_transformed_layout = get_layout_transform_fn(output_layout) s.transform_layout(block, buffer=out_M.name, index_map=output_transformed_layout) # Fixed chunk size is 2048 byte # For uint8 the layout for fixed chunk is 8x8x32 # where each element is 1 bytes # Split and reorder is done to iterate over the fixed chunk # Channel is split by a factor of 32 # Width is split by a factor of 8 # Height is split by a factor of 8 n, h, w, c = s.get_loops(block) h_o, h_i = s.split(h, [None, 8]) w_o, w_i = s.split(w, [None, 8]) c_o, c_i = s.split(c, [None, 32]) wio, wii = s.split(w_i, [None, 4]) s.reorder(n, h_o, w_o, c_o, h_i, wio, wii, c_i) return s
https://github.com/zk-ml/tachikoma
python/tvm/topi/hexagon/reduce.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """Schedule for composition of reduction operator""" import tvm def schedule_reduce(outs): """Schedule for reduction op. Parameters ---------- outs: Array of Tensor The computation graph description of reduction in the format of an array of tensors. Returns ------- sch: Schedule The computation schedule for the op. """ outs = [outs] if isinstance(outs, tvm.te.tensor.Tensor) else outs s = tvm.te.create_schedule([x.op for x in outs]) tvm.te.schedule.AutoInlineInjective(s) return s
https://github.com/zk-ml/tachikoma
python/tvm/topi/hexagon/resize2d.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=invalid-name """Compute and schedule for resize2d Please note the following assumptions made by the implementation: 1) The input and output data will be multiple of crouton layout 2) And the supported layout is NHWC""" from tvm import te from tvm import tir from tvm import topi from .utils import get_layout_transform_fn def resize2d_compute( data, roi, size, layout, method="linear", coordinate_transformation_mode="half_pixel", rounding_method="", bicubic_alpha=-0.5, bicubic_exclude=0, extrapolation_value=0.0, out_dtype=None, output_shape=None, ): """Call resize2d op from topi.image""" return topi.image.resize2d( data, roi, size, layout, method, coordinate_transformation_mode, rounding_method, bicubic_alpha, bicubic_exclude, extrapolation_value, out_dtype, output_shape, ) def tir_resize2d_schedule( out_m, input_a, input_layout: str, output_layout: str, ): """Schedule for input and output layout nhwc-8h2w32c2w-2d and nhwc-8h8w32c-2d""" func = te.create_prim_func([input_a, out_m]) s = tir.Schedule(func) block = s.get_block("resize") if input_layout in ( "nhwc-8h2w32c2w-2d", "nhwc-8h8w32c-2d", ): input_transformed_layout = get_layout_transform_fn(input_layout) s.transform_layout(block, buffer=("read", 0), index_map=input_transformed_layout) output_transformed_layout = get_layout_transform_fn(output_layout) s.transform_layout(block, buffer=("write", 0), index_map=output_transformed_layout) if output_layout == "nhwc-8h2w32c2w-2d": # Fixed chunk size is 2048 byte # For fp16 the layout for fixed chunk is 8x4x32 # where each element is 2 bytes # Split and reorder is done to iterate over the fixed chunk # Channel is split by a factor of 32 # Width is split by a factor of 4 # Height is split by a factor of 8 n, h, w, c = s.get_loops(block) ho, hi = s.split(h, [None, 8]) wo, wi = s.split(w, [None, 4]) co, ci = s.split(c, [None, 32]) s.reorder(n, ho, wo, co, hi, wi, ci) elif output_layout == "nhwc-8h8w32c-2d": # Fixed chunk size is 2048 byte # For uint8 the layout for fixed chunk is 8x8x32 # where each element is 1 bytes # Split and reorder is done to iterate over the fixed chunk # Channel is split by a factor of 32 # Width is split by a factor of 8 # Height is split by a factor of 8 n, h, w, c = s.get_loops(block) ho, hi = s.split(h, [None, 8]) wo, wi = s.split(w, [None, 8]) co, ci = s.split(c, [None, 32]) s.reorder(n, ho, wo, co, hi, wi, ci) return s
https://github.com/zk-ml/tachikoma
python/tvm/topi/hexagon/slice_ops/__init__.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """ Computes and Schedules for Hexagon slice ops. """ from .avg_pool2d import avg_pool2d_compute, avg_pool2d_schedule from .max_pool2d import max_pool2d_compute, max_pool2d_STIR_schedule from .add_subtract_multiply import * from .argmax import argmax_compute, argmax_schedule from .batch_flatten import batch_flatten_compute, batch_flatten_stir_schedule from .softmax_slice import * from .clip import * from .cast import ( cast_f16_f32_compute, cast_f16_f32_schedule, cast_f32_f16_compute, cast_f32_f16_schedule, ) from .conv2d import * from .reshape import reshape_compute, reshape_stir_schedule from .relu import relu_compute, relu_stir_schedule from .tanh import tanh_te_compute, tanhf16_schedule from .dwconv2d import * from .depth_to_space import d2s_compute, d2s_schedule
https://github.com/zk-ml/tachikoma
python/tvm/topi/hexagon/slice_ops/add_subtract_multiply.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=invalid-name """Compute and schedule for add, multiply, subtract slice op Please note the following assumptions made by the implementation: 1) The inputs will be multiple of crouton layout except for the axis that needs broadcasting.""" from tvm import te from tvm import tir from tvm import topi from ..utils import get_layout_transform_fn def add_broadcast_compute(input_a, input_b): """Call the add op from topi""" return topi.add(input_a, input_b) def subtract_broadcast_compute(input_a, input_b): """Call the subtract op from topi""" return topi.subtract(input_a, input_b) def multiply_broadcast_compute(input_a, input_b): """Call the multiply op from topi""" return topi.multiply(input_a, input_b) def tir_broadcast_schedule( out_m, input_a, input_b, output_layout: str, input_a_layout: str, input_b_layout: str, op_name: str, ): """Schedule for input and output layout nhwc-8h2w32c2w-2d considering broadcast""" func = te.create_prim_func([input_a, input_b, out_m]) s = tir.Schedule(func) block_dict = {"add": "T_add", "subtract": "T_subtract", "multiply": "T_multiply"} block = s.get_block(block_dict[op_name]) if input_a_layout == "nhwc-8h2w32c2w-2d": input_a_transformed_layout = get_layout_transform_fn(input_a_layout) s.transform_layout(block, buffer=("read", 0), index_map=input_a_transformed_layout) if input_b_layout == "nhwc-8h2w32c2w-2d": input_b_transformed_layout = get_layout_transform_fn(input_b_layout) s.transform_layout(block, buffer=("read", 1), index_map=input_b_transformed_layout) output_transformed_layout = get_layout_transform_fn(output_layout) s.transform_layout(block, buffer=("write", 0), index_map=output_transformed_layout) n, h, w, c = s.get_loops(block) h_o, h_i = s.split(h, [None, 8]) w_o, w_i = s.split(w, [None, 4]) c_o, c_i = s.split(c, [None, 32]) wio, wii = s.split(w_i, [None, 2]) s.reorder(n, h_o, w_o, c_o, h_i, wio, c_i, wii) fused = s.fuse(c_i, wii) s.vectorize(fused) return s
https://github.com/zk-ml/tachikoma
python/tvm/topi/hexagon/slice_ops/argmax.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """ Hexagon slice argmax compute and schedule""" from tvm import tir from tvm import topi from ..utils import get_layout_transform_fn def argmax_compute(in_tensor, axis): out_tensor = topi.argmax(in_tensor, axis) return out_tensor def argmax_stir_schedule_nhwc(func, in_layout, out_layout): """Schedule for nhwc argmax""" sch = tir.Schedule(func, debug_mask="all") sch.transform_layout("A_red_temp", "A", in_layout) sch.transform_layout("A_red", "A_red", out_layout) return sch def argmax_schedule(argmax_func, in_layout_str, out_layout_str): """Schedule for argmax: top level function""" if (in_layout_str == "nhwc-8h2w32c2w-2d") and (out_layout_str == "nhw-32h16w-2d"): fp16_layout_transform = get_layout_transform_fn(in_layout_str) int32_layout_transform = get_layout_transform_fn(out_layout_str) tir_s = argmax_stir_schedule_nhwc( argmax_func, fp16_layout_transform, int32_layout_transform ) return tir_s if (in_layout_str == "nhwc-8h8w32c-2d") and (out_layout_str == "nhw-32h16w-2d"): int8_layout_transform = get_layout_transform_fn(in_layout_str) int32_layout_transform = get_layout_transform_fn(out_layout_str) tir_s = argmax_stir_schedule_nhwc( argmax_func, int8_layout_transform, int32_layout_transform ) return tir_s raise RuntimeError(f"Unexpected input_layout, output_layout '{in_layout_str, out_layout_str}'")
https://github.com/zk-ml/tachikoma
python/tvm/topi/hexagon/slice_ops/avg_pool2d.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=invalid-name, unused-variable, unused-argument, too-many-locals """ Compute and schedule for avg_pool2d slice op Please note the following assumptions made by the implementation: 1) The input must be padded in advance to account for 'padding'. In addition, both input and output must be padded as per the physical buffer layout. 2) The current implementation assumes 'count_include_pad' to be 'True'. It can be modified to support 'False' case but the element count for the pooling window must be pre-computed and provided as an input to reduce the run-time overhead. 3) 'padding' is ignored. It must be handled outside of the sliced op. 4) Please note that this implementation will not work if the output includes any physical layout related padding as it can result into out-of-bound access for the input. """ from tvm import te from tvm import tir from ..utils import get_layout_transform_fn def validate_out_shape(out_shape, in_shape, kernel, stride, dilation): """Validate output shape""" _, oh, ow, _ = out_shape _, ih, iw, _ = in_shape kh, kw = kernel sh, sw = stride dh, dw = dilation if ih < (oh - 1) * sh + dh * (kh - 1) + 1: raise RuntimeError("Output height is too large") if iw < (ow - 1) * sw + dw * (kw - 1) + 1: raise RuntimeError("Output width is too large") def avg_pool2d_compute(A, kernel, stride, dilation, oshape, odtype="float16"): """avg_pool2d compute""" if odtype != "float16": RuntimeError(f"Unsupported output dtype '{odtype}'") kh, kw = kernel rh = te.reduce_axis((0, kh), name="rh") rw = te.reduce_axis((0, kw), name="rw") ob, oh, ow, oc = oshape if isinstance(ob, int): validate_out_shape(oshape, A.shape, kernel, stride, dilation) sh, sw = stride dh, dw = dilation InvArea = float(1) / (kh * kw) Sum = te.compute( oshape, lambda b, h, w, c: te.sum( A[b, h * sh + dh * rh, w * sw + dw * rw, c].astype("float32"), axis=[rh, rw] ), name="sum", ) Avg = te.compute( oshape, lambda b, h, w, c: (Sum[b, h, w, c] * InvArea).astype(A.dtype), name="avg" ) return Avg def schedule_nhwc_8h2w32c2w(outs, ins, output_layout: str, input_layout: str): """Schedule for input and output layout nhwc-8h2w32c2w""" func = te.create_prim_func([ins, outs]) s = tir.Schedule(func) Sum = s.get_block("sum") Avg = s.get_block("avg") input_transform_fn = get_layout_transform_fn(input_layout) output_transform_fn = get_layout_transform_fn(output_layout) s.transform_layout(Sum, ("read", 0), input_transform_fn) s.transform_layout(Avg, ("write", 0), output_transform_fn) # Schedule 'Avg' n, h, w, c = s.get_loops(Avg) ho, hi = s.split(h, [None, 8]) wo, wi = s.split(w, [None, 4]) wio, wii = s.split(wi, [None, 2]) co, ci = s.split(c, [None, 32]) s.reorder(n, ho, wo, co, hi, wio, ci, wii) ci_wii = s.fuse(ci, wii) s.vectorize(ci_wii) # Schedule 'Sum' s.compute_at(Sum, wio) Sum_axis = s.get_loops(Sum) s.reorder(Sum_axis[-2], Sum_axis[-1], Sum_axis[-4], Sum_axis[-3]) ci_wii = s.fuse(Sum_axis[-4], Sum_axis[-3]) # s.vectorize(ci_wii) # Doesn't work return s def schedule_n11c_1024c(outs, ins, output_layout: str, input_layout: str): """Schedule for output layout: n11c-1024c, input layout: nhwc-8h2w32c2w""" func = te.create_prim_func([ins, outs]) s = tir.Schedule(func) Sum = s.get_block("sum") Avg = s.get_block("avg") input_transform_fn = get_layout_transform_fn(input_layout) output_transform_fn = get_layout_transform_fn(output_layout) s.transform_layout(Sum, ("read", 0), input_transform_fn) s.transform_layout(Avg, ("write", 0), output_transform_fn) # Schedule 'Avg' n, h, w, c = s.get_loops(Avg) co, ci = s.split(c, [None, 1024]) cio, cii = s.split(ci, [None, 64]) s.vectorize(cii) # Schedule 'Sum' s.compute_at(Sum, cio) Sum_axis = s.get_loops(Sum) s.reorder(Sum_axis[-2], Sum_axis[-1], Sum_axis[-3]) # s.vectorize(Sum_axis[-3]) # Doesn't work return s def avg_pool2d_schedule(outs, ins, output_layout: str, input_layout: str): """avg_pool2d schedule""" if output_layout == "nhwc-8h2w32c2w-2d": return schedule_nhwc_8h2w32c2w(outs, ins, output_layout, input_layout) if output_layout == "n11c-1024c-2d": return schedule_n11c_1024c(outs, ins, output_layout, input_layout) raise RuntimeError(f"Unexpected layout '{output_layout}'")
https://github.com/zk-ml/tachikoma
python/tvm/topi/hexagon/slice_ops/batch_flatten.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """Hexagon slice batch flatten compute and schedule""" from tvm import te, tir, topi from ..utils import get_layout_transform_fn def batch_flatten_compute(inp: te.Tensor) -> te.Tensor: """Compute for slice batch flatten op for hexagon. This op makes the following assumptions: 1. This op is written for a sliced batch flatten operation. 2. The input is assumed to be in NHWC layout. Parameters ---------- Input : te.Tensor Input activations padded for inner dimension size Returns ------- Output : te.Tensor Output of applying batch flatten operation on input """ return topi.nn.flatten(inp) def batch_flatten_stir_schedule( out: te.Tensor, inp: te.Tensor, out_layout: str, in_layout: str, ) -> tir.Schedule: """STIR schedule definition for the compute of batch flatten compute. Parameters ---------- outputs : te.Tensor The output tensor as returned by a call to batch_flatten_compute input : te.Tensor Input tensor to batch_flatten out_layout: typing.Callable The transformation function definition for the expected output layout in_layout: typing.Callable The transformation function definition for the input layout Returns ------- sch : tvm.tir.Schedule The STIR schedule for slice batch flatten compute """ batch_flatten_func = te.create_prim_func([inp, out]) sch = tir.Schedule(batch_flatten_func, debug_mask="all") compute = sch.get_block("compute") sch.transform_layout(compute, inp.name, get_layout_transform_fn(in_layout)) sch.transform_layout(compute, out.name, get_layout_transform_fn(out_layout)) i, j = sch.get_loops(compute) jout, channel = sch.split(j, [None, inp.shape[3]]) height, width = sch.split(jout, [inp.shape[1], inp.shape[2]]) channelo, channeli = sch.split(channel, [None, 1024]) channelio, channelii = sch.split(channeli, [None, 64]) sch.reorder(i, height, width, channelo, channelio, channelii) sch.vectorize(channelii) return sch
https://github.com/zk-ml/tachikoma
python/tvm/topi/hexagon/slice_ops/cast.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """ Hexagon slice cast op compute and schedule""" from tvm import te from tvm import tir from ..utils import get_layout_transform_fn def get_layout_transform_for_f32(f32_layout_string): """ Given f32 layout string, return transform_layout function and channel/height split factor to be used for scheduling """ layout_transform_fn = get_layout_transform_fn(f32_layout_string) if f32_layout_string == "nhwc-8h2w32c2w-2d": return [layout_transform_fn, 8] if f32_layout_string == "nhwc-4h2w32c2w-2d": return [layout_transform_fn, 4] if f32_layout_string == "nc-1024c-2d": return [layout_transform_fn, 1024] if f32_layout_string == "nc-512c-2d": return [layout_transform_fn, 512] raise RuntimeError(f"Unexpected f32_layout '{f32_layout_string}'") def cast_f16_f32_compute(in_tensor): out_tensor = te.compute( in_tensor.shape, lambda *indices: in_tensor[indices].astype("float32"), name="CastF16F32" ) return out_tensor def cast_f16_f32_stir_schedule_nhwc(func, in_layout, out_layout, h_split_factor): """Schedule for nhwc f16 to f32 cast: nhwc layout""" sch = tir.Schedule(func, debug_mask="all") block_name = "CastF16F32" n_orig, h_orig, w_orig, c_orig = sch.get_loops(sch.get_block(block_name)) h_outer, h_inner = sch.split(h_orig, [None, h_split_factor]) w_outer, w_inner = sch.split(w_orig, [None, 4]) c_outer, c_inner = sch.split(c_orig, [None, 32]) w_inner_o, w_inner_i = sch.split(w_inner, [None, 2]) sch.reorder(n_orig, h_outer, w_outer, c_outer, h_inner, w_inner_o, c_inner, w_inner_i) sch.transform_layout(block_name, "A", in_layout) sch.transform_layout(block_name, block_name, out_layout) fused = sch.fuse(c_inner, w_inner_i) sch.vectorize(fused) return sch def cast_f16_f32_stir_schedule_nc(func, in_layout, out_layout, c_split_factor): """Schedule for nc f16 to f32 cast: nc layout""" sch = tir.Schedule(func, debug_mask="all") block_name = "CastF16F32" _, c_orig = sch.get_loops(sch.get_block(block_name)) _, c_inner = sch.split(c_orig, [None, c_split_factor]) _, c_inner_inner = sch.split(c_inner, [None, 64]) sch.transform_layout(block_name, "A", in_layout) sch.transform_layout(block_name, block_name, out_layout) sch.vectorize(c_inner_inner) return sch def cast_f16_f32_schedule(cast_func, in_layout_str, out_layout_str): """Schedule for f16 to f32 cast: top level function""" f32_layout_transform_func, split_factor = get_layout_transform_for_f32(out_layout_str) f16_layout_transform_func = get_layout_transform_fn(in_layout_str) if in_layout_str == "nhwc-8h2w32c2w-2d": return cast_f16_f32_stir_schedule_nhwc( cast_func, f16_layout_transform_func, f32_layout_transform_func, split_factor, ) if in_layout_str == "nc-1024c-2d": return cast_f16_f32_stir_schedule_nc( cast_func, f16_layout_transform_func, f32_layout_transform_func, split_factor ) raise RuntimeError(f"Unexpected input_layout, output_layout '{input_layout, output_layout}'") def cast_f32_f16_compute(in_tensor): out_tensor = te.compute( in_tensor.shape, lambda *indices: in_tensor[indices].astype("float16"), name="CastF32F16" ) return out_tensor def cast_f32_f16_stir_schedule_nhwc(func, in_layout, out_layout, h_split_factor): """Schedule for nhwc f32 to f16 cast: nhwc layout""" sch = tir.Schedule(func, debug_mask="all") block_name = "CastF32F16" n_orig, h_orig, w_orig, c_orig = sch.get_loops(sch.get_block(block_name)) h_outer, h_inner = sch.split(h_orig, [None, h_split_factor]) w_outer, w_inner = sch.split(w_orig, [None, 4]) c_outer, c_inner = sch.split(c_orig, [None, 32]) w_inner_o, w_inner_i = sch.split(w_inner, [None, 2]) sch.reorder(n_orig, h_outer, w_outer, c_outer, h_inner, w_inner_o, c_inner, w_inner_i) sch.transform_layout(block_name, "A", in_layout) sch.transform_layout(block_name, block_name, out_layout) fused = sch.fuse(c_inner, w_inner_i) sch.vectorize(fused) return sch def cast_f32_f16_stir_schedule_nc(func, in_layout, out_layout, c_split_factor): """Schedule for nc f32 to f16 cast: nc layout""" sch = tir.Schedule(func, debug_mask="all") block_name = "CastF32F16" _, c_orig = sch.get_loops(sch.get_block(block_name)) _, c_inner = sch.split(c_orig, [None, c_split_factor]) _, c_inner_inner = sch.split(c_inner, [None, 64]) sch.transform_layout(block_name, "A", in_layout) sch.transform_layout(block_name, block_name, out_layout) sch.vectorize(c_inner_inner) return sch def cast_f32_f16_schedule(cast_func, in_layout_str, out_layout_str): """Schedule for f32 to f16 cast: top level function""" f32_layout_transform_func, split_factor = get_layout_transform_for_f32(in_layout_str) f16_layout_transform_func = get_layout_transform_fn(out_layout_str) if out_layout_str == "nhwc-8h2w32c2w-2d": return cast_f32_f16_stir_schedule_nhwc( cast_func, f32_layout_transform_func, f16_layout_transform_func, split_factor ) if out_layout_str == "nc-1024c-2d": return cast_f32_f16_stir_schedule_nc( cast_func, f32_layout_transform_func, f16_layout_transform_func, split_factor ) raise RuntimeError(f"Unexpected input_layout, output_layout '{in_layout_str, out_layout_str}'")
https://github.com/zk-ml/tachikoma
python/tvm/topi/hexagon/slice_ops/clip.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=invalid-name """ Clip the elements in `A` between `A_min` and `A_max`. """ from tvm import te, tir, topi from ..utils import get_layout_transform_fn def clip_compute(A, A_min, A_max): """ Use topi clip implementation """ return topi.clip(A, A_min, A_max) def clip_schedule(outs, ins, output_layout: str, input_layout: str): """ Hexagon clip schedule """ A = ins M = outs func = te.create_prim_func([A, M]) s = tir.Schedule(func) block = s.get_block("compute") input_transformed_layout = get_layout_transform_fn(input_layout) s.transform_layout(block, buffer=("read", 0), index_map=input_transformed_layout) output_transformed_layout = get_layout_transform_fn(output_layout) s.transform_layout(block, buffer=("write", 0), index_map=output_transformed_layout) n, h, w, c = s.get_loops(block) ho, hi = s.split(h, [None, 8]) wo, wi = s.split(w, [None, 4]) co, ci = s.split(c, [None, 32]) wio, wii = s.split(wi, [None, 2]) s.reorder(n, ho, wo, co, hi, wio, ci, wii) fused = s.fuse(ci, wii) s.vectorize(fused) return s
https://github.com/zk-ml/tachikoma
python/tvm/topi/hexagon/slice_ops/conv2d.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=line-too-long """Hexagon slice conv2d compute and schedule""" import typing import tvm from tvm import te from ..utils import get_layout_transform_fn def conv2d_compute( activations: te.Tensor, weights: te.Tensor, out_shape: typing.Tuple, stride: typing.Tuple, dilation: typing.Tuple, dtype: str, output_name: str, weights_width_reversed: bool = True, ) -> te.Tensor: """Compute for slice conv2d op for hexagon. This op makes the following assumptions: 1. This op is written for a sliced convolution with 2d physical buffers 2. The input activations is assumed to be in NHWC layout and filter is in HWIO layout 3. Grouped convolutions are not supported. and there will be a separate compute definition for depthwise convolution 4. In order to get grouped convolutions, it is assumed that the op will be sliced according to the groups and multiple calls to this compute would be placed. Parameters ---------- activations : te.Tensor Input activations padded for inner dimension size weights : te.Tensor Weights without dilation out_shape : typing.Tuple The logical output shape without considering input padding stride : typing.Tuple stride dilation : typing.Tuple dilation dtype : str dtype output_name : str The name to be given to output. This would become the block name for the corresponding STIR compute weights_width_reversed : bool The width axis of weights are expected in reverse order if weights_width_reversed is True Returns ------- output : te.Tensor Output of applying 2D convolution of Weights on Input """ filt_shape = weights.shape reduce_channel = tvm.te.reduce_axis((0, filt_shape[2]), name="reduce_channel") reduce_height = tvm.te.reduce_axis((0, filt_shape[0]), name="reduce_height") reduce_width = tvm.te.reduce_axis((0, filt_shape[1]), name="reduce_width") stride_height, stride_width = stride dilation_height, dilation_width = dilation if weights_width_reversed: weights_width_var = filt_shape[1] - reduce_width - 1 else: weights_width_var = reduce_width output = tvm.te.compute( out_shape, lambda n, h, w, c: tvm.te.sum( ( activations[ n, h * stride_height + reduce_height * dilation_height, w * stride_width + reduce_width * dilation_width, reduce_channel, ] * weights[reduce_height, weights_width_var, reduce_channel, c] ).astype(dtype), axis=[reduce_channel, reduce_height, reduce_width], ), name=output_name, ) return output def conv2d_te_schedule( out: te.Tensor, ins: typing.List[te.Tensor], transform_activation_layout: str, transform_weights_layout: str, transform_output_layout: str, ) -> te.Schedule: """TE Schedule for the sliced conv2d op This schedule makes the following assumptions: 1. There is only one output tensor 2. The activations and weights have specific layouts defined by the last 2 arguments 3. All transformation functions are expected to be a bijection for now Parameters ---------- out : te.Tensor The output tensor returned by a call to conv2d_compute ins : typing.List[te.Tensor] The list of 2 Tensors which would be the input activations and weights transform_activation_layout : str The expected activations layout transform_weights_layout : str String representing the weights layout as defined in get_layout_transform_fn transform_output_layout: str String representing the output layout as defined in get_layout_transform_fn Returns ------- sch : te.Schedule The TE schedule for slice conv2d """ activations, weights = ins output = out sch = tvm.te.create_schedule(output.op) reduce_channel, reduce_height, reduce_width = sch[output].op.reduce_axis sch[activations].transform_layout(get_layout_transform_fn(transform_activation_layout)) sch[weights].transform_layout(get_layout_transform_fn(transform_weights_layout)) transformed_axis = sch[output].transform_layout( get_layout_transform_fn(transform_output_layout) ) fused_out_axis = sch[output].fuse(transformed_axis[-1], transformed_axis[-2]) sch[output].reorder( *[*transformed_axis[:-2], reduce_height, reduce_width, reduce_channel, fused_out_axis] ) # The below code doesn't work yet as vectorization across 2D boundary is not yet supported # s[output].vectorize(fused_out_axis) return sch def conv2d_schedule( outs: te.Tensor, ins: typing.List[te.Tensor], transform_activation_layout: str, transform_weights_layout: str, transform_output_layout: str, output_name: str, ) -> tvm.tir.Schedule: """STIR schedule definition for the compute defined above by conv2d_compute. - Auto-generated prim_func before applying schedule primitives for reference - The below TVMScript code is for conv2d with padded input dimensions and a stride of 1x1 # from tvm.script import tir as T @T.prim_func def func(InputTensor: T.Buffer[(1, 24, 12, 32), "float16"], Weights: T.Buffer[(3, 3, 32, 32), "float16"], compute: T.Buffer[(1, 16, 8, 32), "float16"]) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) # body # with T.block("root") for i0, i1, i2, i3, i4, i5, i6 in T.grid(1, 16, 8, 32, 32, 3, 3): with T.block("compute"): n, h, w, c, rc, rh, rw = T.axis.remap("SSSSRRR", [i0, i1, i2, i3, i4, i5, i6]) T.reads(InputTensor[n, h + rh, w + rw, rc], Weights[rh, rw, rc, c]) T.writes(compute[n, h, w, c]) with T.init(): compute[n, h, w, c] = T.float16(0) compute[n, h, w, c] = compute[n, h, w, c] + InputTensor[n, h + rh, w + rw, rc] * Weights[rh, rw, rc, c] Parameters ---------- outs : te.Tensor The output Tensor as returned by a call to conv2d_compute ins : typing.List[te.Tensor] This is a list of 2 tensors - Input activations and Weights transform_activation_layout : str String representing the activations layout as defined in get_layout_transform_fn transform_weights_layout : str String representing the weights layout as defined in get_layout_transform_fn transform_output_layout: str String representing the output layout as defined in get_layout_transform_fn output_name : str The name that was given to the output compute and which can be used to get the block name Returns ------- sch : tvm.tir.Schedule The STIR schedule for slice conv2d compute """ assert len(ins) == 2, "This schedule expects only 2 inputs - Activations and Weights" source_expr = ins + [outs] prim_func = tvm.te.create_prim_func(source_expr) sch = tvm.tir.Schedule(prim_func) compute = sch.get_block(output_name) # Apply layout_transform for activation sch.transform_layout(compute, ins[0].name, get_layout_transform_fn(transform_activation_layout)) # Apply layout_transform for weights sch.transform_layout(compute, ins[1].name, get_layout_transform_fn(transform_weights_layout)) # Apply layout_transform for output sch.transform_layout(compute, outs.name, get_layout_transform_fn(transform_output_layout)) batch, height, width, channel, reduce_channel, reduce_height, reduce_width = sch.get_loops( compute ) # This still returns the original 7d loop h_outer, h_inner = sch.split(height, [None, 8]) w_outer, w_inner = sch.split(width, [None, 4]) w_inner_outer, w_inner_inner = sch.split(w_inner, [2, 2]) c_outer, c_inner = sch.split(channel, [None, 32]) sch.reorder( batch, h_outer, w_outer, c_outer, h_inner, w_inner_outer, reduce_height, reduce_width, reduce_channel, c_inner, w_inner_inner, ) sch.decompose_reduction(compute, reduce_height) # ci_wii = s.fuse(ci, wii) # s.vectorize(ci_wii) return sch
https://github.com/zk-ml/tachikoma
python/tvm/topi/hexagon/slice_ops/depth_to_space.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """ Compute and schedule for depth to space slice op """ from tvm import te, tir, topi from ..utils import get_layout_transform_fn def d2s_compute(inp, block_size, layout, mode): """depth_to_space compute""" return topi.nn.depth_to_space(inp, block_size=block_size, layout=layout, mode=mode) def d2s_schedule(inp, out, input_layout, output_layout): """Schedule for depth to space: top level function""" if (input_layout != output_layout) or ( output_layout not in ("nhwc-8h2w32c2w-2d", "nhwc-8h8w32c-2d") ): raise RuntimeError( f"Unexpected input_layout, output_layout '{input_layout, output_layout}'" ) d2s_func = te.create_prim_func([inp, out]) sch = tir.Schedule(d2s_func, debug_mask="all") compute = sch.get_block("depth_to_space") sch.transform_layout(compute, inp.name, get_layout_transform_fn(input_layout)) sch.transform_layout(compute, out.name, get_layout_transform_fn(output_layout)) return sch
https://github.com/zk-ml/tachikoma
python/tvm/topi/hexagon/slice_ops/dwconv2d.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=line-too-long """Hexagon slice dwconv2d compute and schedule""" import typing import tvm from tvm import te from ..utils import get_layout_transform_fn def dwconv2d_compute( activations: te.Tensor, weights: te.Tensor, out_shape: typing.Tuple, stride: typing.Tuple, dilation: typing.Tuple, dtype: str, ) -> te.Tensor: """Compute for slice dwconv2d op for hexagon. This op makes the following assumptions: 1. This op is written for a sliced dw convolution with 2d physical buffers 2. The input activations is assumed to be in NHWC layout and filter is in HWIO layout Parameters ---------- activations : te.Tensor Input activations padded for inner dimension size weights : te.Tensor Weights without dilation out_shape : typing.Tuple The logical output shape without considering input padding stride : typing.Tuple stride dilation : typing.Tuple dilation dtype : str dtype Returns ------- output : te.Tensor Output of applying 2D depthwise convolution of Weights on Input """ filt_shape = weights.shape reduce_height = tvm.te.reduce_axis((0, filt_shape[0]), name="reduce_height") reduce_width = tvm.te.reduce_axis((0, filt_shape[1]), name="reduce_width") stride_height, stride_width = stride dilation_height, dilation_width = dilation output = tvm.te.compute( out_shape, lambda n, h, w, c: tvm.te.sum( ( activations[ n, h * stride_height + reduce_height * dilation_height, w * stride_width + reduce_width * dilation_width, c, ] * weights[reduce_height, reduce_width, 0, c] ).astype(dtype), axis=[reduce_height, reduce_width], ), name="Output", ) return output def dwconv2d_schedule( outs: te.Tensor, ins: typing.List[te.Tensor], transform_activation_layout: str, transform_weights: str, ) -> tvm.tir.Schedule: """STIR schedule definition for the compute defined above by dwconv2d_compute. - Auto-generated prim_func before applying schedule primitives for reference - The below TVMScript code is for dwconv2d with padded input dimensions and a stride of 1x1 # from tvm.script import tir as T @tvm.script.ir_module class Module: @T.prim_func def main(InputTensor: T.Buffer[(1, 16, 8, 32), "float16"], Weights: T.Buffer[(3, 3, 1, 32), "float16"], Output: T.Buffer[(1, 8, 4, 32), "float16"]) -> None: # function attr dict T.func_attr({"global_symbol": "main", "tir.noalias": True}) # body # with T.block("root") for i0, i1, i2, i3, i4, i5 in T.grid(1, 8, 4, 32, 3, 3): with T.block("Output"): n, h, w, c, reduce_height, reduce_width = T.axis.remap("SSSSRR", [i0, i1, i2, i3, i4, i5]) T.reads(InputTensor[n, h + reduce_height, w + reduce_width, c], Weights[reduce_height, reduce_width, 0, c]) T.writes(Output[n, h, w, c]) with T.init(): Output[n, h, w, c] = T.float16(0) Output[n, h, w, c] = Output[n, h, w, c] + InputTensor[n, h + reduce_height, w + reduce_width, c] * Weights[reduce_height, reduce_width, 0, c] Parameters ---------- outs : te.Tensor The output Tensor as returned by a call to dwconv2d_compute ins : typing.List[te.Tensor] This is a list of 2 tensors - Input activations and Weights transform_activation_layout : str The transformation string representing the expected activations layout transform_weights : typing.Callable The transformation function definition for the expected weights layout Returns ------- sch : tvm.tir.Schedule The STIR schedule for slice dwconv2d compute """ assert len(ins) == 2, "This schedule expects only 2 inputs - Activations and Weights" source_expr = ins + [outs] prim_func = tvm.te.create_prim_func(source_expr) sch = tvm.tir.Schedule(prim_func) compute = sch.get_block("Output") transform_layout_fn = get_layout_transform_fn(transform_activation_layout) transform_layout_weights = get_layout_transform_fn(transform_weights) # Apply layout_transform for activation sch.transform_layout(compute, ins[0].name, transform_layout_fn) # Apply layout_transform for weights sch.transform_layout(compute, ins[1].name, transform_layout_weights) # Apply layout_transform for output sch.transform_layout(compute, outs.name, transform_layout_fn) batch, height, width, channel, reduce_height, reduce_width = sch.get_loops( compute ) # This still returns the original 6d loop h_outer, h_inner = sch.split(height, [None, 8]) w_outer, w_inner = sch.split(width, [None, 4]) w_inner_outer, w_inner_inner = sch.split(w_inner, [2, 2]) c_outer, c_inner = sch.split(channel, [None, 32]) sch.reorder( batch, h_outer, w_outer, c_outer, h_inner, w_inner_outer, reduce_height, reduce_width, c_inner, w_inner_inner, ) sch.decompose_reduction(compute, reduce_height) # ci_wii = sch.fuse(c_inner, w_inner_inner) # sch.vectorize(ci_wii) return sch
https://github.com/zk-ml/tachikoma
python/tvm/topi/hexagon/slice_ops/max_pool2d.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=invalid-name, unused-variable, unused-argument, too-many-locals """ Compute and schedule for max_pool2d slice op Please note the following assumptions made by the implementation: 1) The input must be padded in advance to account for 'padding'. In addition, both input and output must be padded as per the physical buffer layout. 2) The current implementation assumes 'count_include_pad' to be 'True'. It can be modified to support 'False' case but the element count for the pooling window must be pre-computed and provided as an input to reduce the run-time overhead. 3) 'padding' is ignored. It must be handled outside of the sliced op. 4) This implementation will not work if the output includes any physical layout related padding, as it can result into out-of-bound access for the input. """ from tvm import te from tvm import tir from ..utils import get_layout_transform_fn def validate_out_shape(out_shape, in_shape, kernel, stride, dilation): """Validate output shape""" _, oh, ow, _ = out_shape _, ih, iw, _ = in_shape kh, kw = kernel sh, sw = stride dh, dw = dilation if ih < (oh - 1) * sh + dh * (kh - 1) + 1: raise RuntimeError("Output height is too large") if iw < (ow - 1) * sw + dw * (kw - 1) + 1: raise RuntimeError("Output width is too large") def max_pool2d_compute(A, out_shape, kernel, stride, dilation): """max_pool2d compute""" kh, kw = kernel rh = te.reduce_axis((0, kh), name="rh") rw = te.reduce_axis((0, kw), name="rw") ob, oh, ow, oc = out_shape if isinstance(ob, int): validate_out_shape(out_shape, A.shape, kernel, stride, dilation) sh, sw = stride dh, dw = dilation Max = te.compute( out_shape, lambda b, h, w, c: te.max( A[b, h * sh + dh * rh, w * sw + dw * rw, c].astype(A.dtype), axis=[rh, rw] ), name="max", ) return Max def STIR_schedule_nhwc_8h2w32c2w_nhwc_8h8w32c( outs: te.Tensor, ins: te.Tensor, output_layout: str, input_layout: str ): """Schedule for input and output layout nhwc-8h2w32c2w and nhwc-8h8w32c""" func = te.create_prim_func([ins, outs]) s = tir.Schedule(func) # NOTE!!! This scheduling logic is a work in progress. # It is not known to ultimately result in near-optimal Hexagon performance. # The schedule below strives to implement these heuristics: # # (1) For mathematical operations on tensor values, prefer HVX SIMD operations # over per-element scalar operations. # # (2) Minimize the number of memory transfers used to operate on tensor values: # host-memory <--> Hexagon DDR <--> VTCM <--> HVX registers # # As a consequence of (1) + (2), prefer TIR schedules that load each value # into an HVX SIMD tensor exactly once. Max = s.get_block("max") if input_layout in ( "nhwc-8h2w32c2w-2d", "nhwc-8h8w32c-2d", ): input_transform_fn = get_layout_transform_fn(input_layout) s.transform_layout(Max, ("read", 0), input_transform_fn) output_transform_fn = get_layout_transform_fn(output_layout) s.transform_layout(Max, ("write", 0), output_transform_fn) # pylint: disable=line-too-long # # Restructure the loop nestings to have this overall structure: # (loop over different 128-byte output-tensor chunks) : n, ho, wo, co }- the first level of a two-level tensor layout # (loop within one 128-byte output-tensor chunk) : hi, wio, ci, wii }- the second level of a two-level tensor layout # (loop over reduction axes) : rh, rw }- loop over multiple elements of the input tensor # # Note: This schedule is a work in progress. We *expect* that it's # crucially important for the loops to have this relative ordering: # n ... ho ... wo ... co ... hi ... wio ... ci ... wii # because it lets us visit each of the 128-byte output chunks precisely once. ( n, h, w, c, rh, rw, ) = s.get_loops(Max) # Restructure the loops from NHWC to nhwc_8h2w32c2w or nhwc_8h8w32c, with loops for 'max's reduction # axes at the very end. # nhwc_8h2w32c2w layout is for float16 and nhwc-8h8w32c-2d layout is for uint8/int8 if output_layout == "nhwc-8h2w32c2w-2d": ho, hi = s.split(h, [None, 8]) wo, wi = s.split(w, [None, 4]) wio, wii = s.split(wi, [None, 2]) co, ci = s.split(c, [None, 32]) s.reorder(n, ho, wo, co, hi, wio, ci, wii, rh, rw) elif output_layout == "nhwc-8h8w32c-2d": ho, hi = s.split(h, [None, 8]) wo, wi = s.split(w, [None, 8]) co, ci = s.split(c, [None, 32]) s.reorder(n, ho, wo, co, hi, wi, ci, rh, rw) # TODO: Enable vectorization. # Hexagon v69's HVX units support SIMD operations on 64-element float16 vectors. # # TVM's 'vectorize' schedule primitive is the idiomatic way to encourage lower layers of the # compiler to generate this kind of SIMD object code. # # Several requirements must be met to use 'vectorize': # # 1) It can only be applied to a schedule's innermost loop variable. # # 2) Any block-iterator(s) bound to that innermost loop variable must be # *data-parallel* block iterators. # # 3) Ideally, the innermost loop variable will iterate only over the output # tensor's fastest-changing indices and nothing else. But in our case, # our two innermost loops correspond to the the max operator's reduction axes. # # Finding a good way to satisfy all of these requirements at the same time is # left for future work. # ci_wii = s.fuse(ci, wii) # s.vectorize(ci_wii_rh_rw) return s def STIR_schedule_n11c(outs, ins, output_layout: str, input_layout: str): """Schedule for output layout: n11c-1024c, n11c-2048c-2d;""" # NOTE: This function is a variation of the STIR_schedule_maxpool2d # functions. Most of that function's code comments apply to this function # as well, but are ommited for brevity. # NOTE: the "n11c-1024c" output layout is shorthand for this axis mapping: # [n, h, w, c // 1024, te.AXIS_SEPARATOR, c % 1024] func = te.create_prim_func([ins, outs]) s = tir.Schedule(func) Max = s.get_block("max") input_transform_fn = get_layout_transform_fn(input_layout) output_transform_fn = get_layout_transform_fn(output_layout) s.transform_layout(Max, ("read", 0), input_transform_fn) s.transform_layout(Max, ("write", 0), output_transform_fn) ( n, h, w, c, rh, rw, ) = s.get_loops(Max) if output_layout == "n11c-1024c-2d": co, ci = s.split(c, [None, 1024]) else: co, ci = s.split(c, [None, 2048]) # s.vectorize(ci) return s def max_pool2d_STIR_schedule(outs, ins, output_layout: str, input_layout: str): """STIR based schedule""" if output_layout == "nhwc-8h2w32c2w-2d" or "nhwc-8h8w32c-2d": return STIR_schedule_nhwc_8h2w32c2w_nhwc_8h8w32c(outs, ins, output_layout, input_layout) if output_layout == "n11c-1024c-2d" or "n11c-2048c-2d": return STIR_schedule_n11c(outs, ins, output_layout, input_layout) raise RuntimeError(f"Unexpected layout '{output_layout}'")
https://github.com/zk-ml/tachikoma
python/tvm/topi/hexagon/slice_ops/relu.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=invalid-name """Hexagon slice relu op""" from tvm import te, tir, topi from ..utils import get_layout_transform_fn def relu_compute(Input): """Relu topi compute""" return topi.nn.relu(Input) def relu_te_sched(Output, Input, layout): """ Schedule assumes the layout function to be bijective """ s = te.create_schedule(Output.op) s[Input].transform_layout(layout) out_axes = s[Output].transform_layout(layout) fused = s[Output].fuse(out_axes[6], out_axes[7]) s[Output].vectorize(fused) return s def relu_stir_schedule(Input, Output, input_layout, output_layout): """ Schedule assumes the layout function to be bijective """ if (input_layout != output_layout) or (output_layout != "nhwc-8h2w32c2w-2d"): raise RuntimeError( f"Unexpected input_layout, output_layout '{input_layout, output_layout}'" ) relu_func = te.create_prim_func([Input, Output]) sch = tir.Schedule(relu_func, debug_mask="all") block = sch.get_block("compute") sch.transform_layout(block, Input.name, get_layout_transform_fn(input_layout)) sch.transform_layout(block, Output.name, get_layout_transform_fn(output_layout)) n, h, w, c = sch.get_loops(block) h_o, h_i = sch.split(h, [None, 8]) w_o, w_i = sch.split(w, [None, 4]) c_o, c_i = sch.split(c, [None, 32]) wio, wii = sch.split(w_i, [None, 2]) sch.reorder(n, h_o, w_o, c_o, h_i, wio, c_i, wii) fused = sch.fuse(c_i, wii) sch.vectorize(fused) return sch
https://github.com/zk-ml/tachikoma
python/tvm/topi/hexagon/slice_ops/reshape.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """Hexagon slice reshape compute and schedule""" from tvm import te, tir, topi from ..utils import get_layout_transform_fn def reshape_compute(inp: te.Tensor, new_shape: tuple) -> te.Tensor: """Compute for slice reshape op for hexagon. This op makes the following assumptions: 1. This op is written for a sliced reshape operation. 2. The input is assumed to be in NHWC layout. Parameters ---------- Input : te.Tensor Input tensor New Shape: tuple Output shape Returns ------- Output : te.Tensor Output of applying reshape operation on input """ return topi.transform.reshape(inp, new_shape) def stir_sched_nhwc_2d_op( out: te.Tensor, inp: te.Tensor, out_layout: str, in_layout: str, c_split: int, ) -> tir.Schedule: """Schedule for output layout: nc-1024-2d, nc-2048-2d""" reshape_func = te.create_prim_func([inp, out]) sch = tir.Schedule(reshape_func, debug_mask="all") compute = sch.get_block("T_reshape") sch.transform_layout(compute, inp.name, get_layout_transform_fn(in_layout)) sch.transform_layout(compute, out.name, get_layout_transform_fn(out_layout)) i, j = sch.get_loops(compute) jout, channel = sch.split(j, [None, inp.shape[3]]) height, width = sch.split(jout, [inp.shape[1], inp.shape[2]]) channelo, channeli = sch.split(channel, [None, 1024]) channelio, channelii = sch.split(channeli, [None, c_split]) sch.reorder(i, height, width, channelo, channelio, channelii) sch.vectorize(channelii) return sch def stir_schedule_nhwc_8h2w32c2w( out: te.Tensor, inp: te.Tensor, out_layout: str, in_layout: str, ) -> tir.Schedule: """Schedule for input and output layout nhwc-8h2w32c2w""" reshape_func = te.create_prim_func([inp, out]) sch = tir.Schedule(reshape_func, debug_mask="all") compute = sch.get_block("T_reshape") sch.transform_layout(compute, inp.name, get_layout_transform_fn(in_layout)) sch.transform_layout(compute, out.name, get_layout_transform_fn(out_layout)) return sch def reshape_stir_schedule( out: te.Tensor, inp: te.Tensor, output_layout: str, input_layout: str, ) -> tir.Schedule: """STIR schedule definition for the compute of reshape compute. Parameters ---------- outputs : te.Tensor The output tensor as returned by a call to reshape_compute input : te.Tensor Input tensor to reshape out_layout: str The transformation function definition for the expected output layout in_layout: str The transformation function definition for the input layout Returns ------- sch : tvm.tir.Schedule The STIR schedule for slice reshape compute """ if output_layout in ["nhwc-8h2w32c2w-2d", "nhwc-8h8w32c-2d"]: return stir_schedule_nhwc_8h2w32c2w(out, inp, output_layout, input_layout) if output_layout == "nc-1024-2d": return stir_sched_nhwc_2d_op(out, inp, output_layout, input_layout, 64) if output_layout == "nc-2048-2d": return stir_sched_nhwc_2d_op(out, inp, output_layout, input_layout, 128) raise RuntimeError(f"Unexpected layout '{output_layout}'")
https://github.com/zk-ml/tachikoma
python/tvm/topi/hexagon/slice_ops/softmax_slice.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """Hexagon slice softmax compute and schedule""" import typing from tvm import te, tir, topi from ..utils import get_layout_transform_fn def softmax_compute(in_tensor): """ Compute for slice softmax op for hexagon. This op makes the following assumptions: 1. This op is written for a sliced softmax operation. 2. The input is assumed to be in NC layout. """ return topi.nn.softmax(in_tensor, axis=1) def softmax_stir_schedule( out: te.Tensor, inp: te.Tensor, out_layout: typing.Callable, in_layout: typing.Callable ): """ STIR schedule definition for the compute of softmax """ in_layout = get_layout_transform_fn(in_layout) out_layout = get_layout_transform_fn(out_layout) func = te.create_prim_func([inp, out]) sch = tir.Schedule(func, debug_mask="all") max_tensor = sch.get_block("T_softmax_maxelem") exp_tensor = sch.get_block("T_softmax_exp") sum_tensor = sch.get_block("T_softmax_expsum") out_tensor = sch.get_block("T_softmax_norm") sch.transform_layout(max_tensor, inp.name, in_layout) sch.transform_layout(out_tensor, out.name, out_layout) _, c_inner = sch.get_loops(max_tensor) _, c_inner_i = sch.split(c_inner, [None, 64]) rf_max = sch.rfactor(c_inner_i, 0) _, _, max_inner = sch.get_loops(rf_max) sch.vectorize(max_inner) _, loopi = sch.get_loops(exp_tensor) _, loopi_i = sch.split(loopi, [None, 512]) sch.vectorize(loopi_i) _, c_sum_inner = sch.get_loops(sum_tensor) _, c_sum_inner_i = sch.split(c_sum_inner, [None, 64]) rf_sum = sch.rfactor(c_sum_inner_i, 0) _, _, sum_inner = sch.get_loops(rf_sum) sch.vectorize(sum_inner) _, c_out_inner = sch.get_loops(out_tensor) _, c_out_inner_i = sch.split(c_out_inner, [None, 512]) sch.vectorize(c_out_inner_i) return sch
https://github.com/zk-ml/tachikoma
python/tvm/topi/hexagon/slice_ops/tanh.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=invalid-name """ Hexagon tanh slice op compute and schedule """ import tvm from tvm import te, tir from ..utils import get_layout_transform_fn def tanh_te_compute(in_tensor): out_tensor = te.compute( in_tensor.shape, lambda n, h, w, c: tvm.tir.tanh(in_tensor[n, h, w, c]), name="tanhf16" ) return out_tensor def tanhf16_stir_sched_nhwc(func, in_layout, out_layout, h_split_factor=8): """Schedule for nhwc fp16 to nchw fp16 layout""" sch = tir.Schedule(func, debug_mask="all") block_name = "tanhf16" n, h, w, c = sch.get_loops(sch.get_block(block_name)) h_outer, h_inner = sch.split(h, [None, h_split_factor]) w_outer, w_inner = sch.split(w, [None, 4]) c_outer, c_inner = sch.split(c, [None, 32]) w_inner_o, w_inner_i = sch.split(w_inner, [None, 2]) sch.reorder(n, h_outer, w_outer, c_outer, h_inner, w_inner_o, c_inner, w_inner_i) sch.transform_layout(block_name, "A", in_layout) sch.transform_layout(block_name, block_name, out_layout) fused = sch.fuse(c_inner, w_inner_i) sch.vectorize(fused) return sch def tanhf16_schedule(tanh_func, in_layout_str, out_layout_str): in_layout_transform_func = get_layout_transform_fn(in_layout_str) out_layout_transform_func = get_layout_transform_fn(out_layout_str) return tanhf16_stir_sched_nhwc( tanh_func, in_layout_transform_func, out_layout_transform_func, )
https://github.com/zk-ml/tachikoma
python/tvm/topi/hexagon/tensor_intrin.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=invalid-name """Optimized implementation of q_multiply_shift based on LLVM intrinsics""" import tvm from tvm.ir import register_intrin_lowering from tvm import te def _q_multiply_shift_hexagon(op): """ Implementation of q_multiply_shift through hexagon intrinsics vmpyewuh and vmpyowh when q == 31. """ x = op.args[0] y = op.args[1] fractional_bits = op.args[2] shift = op.args[3] # Don't use this intrinsic if we don't have a int32x32 vector # or if we are not multiplying q31 numbers if x.dtype != "int32x32" or fractional_bits.value != 31: return op # Case 1, shift is negative mul_e_1 = tvm.tir.call_llvm_intrin( op.dtype, "llvm.hexagon.V6.vmpyewuh.128B", tvm.tir.const(2, "uint32"), x, y ) mul_o_1 = tvm.tir.call_llvm_intrin( op.dtype, "llvm.hexagon.V6.vmpyowh.sacc.128B", tvm.tir.const(3, "uint32"), mul_e_1, x, y ) fixup = 1 << (-shift - 1) round_mul = mul_o_1 + fixup out_negative_shift = tvm.tir.call_llvm_intrin( op.dtype, "llvm.hexagon.V6.vaslwv.128B", tvm.tir.const(2, "uint32"), round_mul, shift ) # Case 2, shift is positive x = x * (1 << (shift)) mul_e_2 = tvm.tir.call_llvm_intrin( op.dtype, "llvm.hexagon.V6.vmpyewuh.128B", tvm.tir.const(2, "uint32"), x, y ) mul_o_2 = tvm.tir.call_llvm_intrin( op.dtype, "llvm.hexagon.V6.vmpyowh.rnd.sacc.128B", tvm.tir.const(3, "uint32"), mul_e_2, x, y ) # Select depending on the shift return tvm.tir.Select(shift < 0, out_negative_shift, mul_o_2) register_intrin_lowering( "tir.q_multiply_shift", target="hexagon", f=_q_multiply_shift_hexagon, level=99 ) def _q_multiply_shift_per_axis_hexagon(op): """ Implementation of q_multiply_shift_per_axis through hexagon intrinsics vmpyewuh and vmpyowh when q == 31. """ x = op.args[0] y = op.args[1] left_shift = op.args[2] right_shift = op.args[3] fractional_bits = op.args[4] is_lshift_required = op.args[5] is_rshift_required = op.args[6] # Don't use this intrinsic if we don't have a int32x32 vector # or if we are not multiplying q31 numbers if x.dtype != "int32x32" or fractional_bits.value != 31: return op # Don't use this intrinsic when we need do both: left and right shifts. # For now it is not clear how to implement this case through vector HVX instructions without # accuracy drop. if is_rshift_required.value and is_lshift_required.value: return op # Case 1: do the left shift shifted_x = x << left_shift mul_e_1 = tvm.tir.call_llvm_intrin( op.dtype, "llvm.hexagon.V6.vmpyewuh.128B", tvm.tir.const(2, "uint32"), shifted_x, y ) left_shift_out = tvm.tir.call_llvm_intrin( op.dtype, "llvm.hexagon.V6.vmpyowh.rnd.sacc.128B", tvm.tir.const(3, "uint32"), mul_e_1, shifted_x, y, ) # Case 2: do the right shift mul_e_2 = tvm.tir.call_llvm_intrin( op.dtype, "llvm.hexagon.V6.vmpyewuh.128B", tvm.tir.const(2, "uint32"), x, y ) mul_o_2 = tvm.tir.call_llvm_intrin( op.dtype, "llvm.hexagon.V6.vmpyowh.sacc.128B", tvm.tir.const(3, "uint32"), mul_e_2, x, y ) fixup = 1 << (right_shift - 1) round_mul = mul_o_2 + fixup right_shift_out = tvm.tir.call_llvm_intrin( op.dtype, "llvm.hexagon.V6.vasrwv.128B", tvm.tir.const(2, "uint32"), round_mul, right_shift ) # Case 3: do neither right nor left shift mul_e_3 = tvm.tir.call_llvm_intrin( op.dtype, "llvm.hexagon.V6.vmpyewuh.128B", tvm.tir.const(2, "uint32"), x, y ) no_shift_out = tvm.tir.call_llvm_intrin( op.dtype, "llvm.hexagon.V6.vmpyowh.rnd.sacc.128B", tvm.tir.const(3, "uint32"), mul_e_3, x, y ) return tvm.tir.Select( tvm.tir.Not(tvm.tir.Or(is_lshift_required, is_rshift_required)), no_shift_out, tvm.tir.Select(is_lshift_required, left_shift_out, right_shift_out), ) register_intrin_lowering( "tir.q_multiply_shift_per_axis", target="hexagon", f=_q_multiply_shift_per_axis_hexagon, level=99, ) def dot_vrmpy(x_ty, y_ty): """Generates vrmpy instruciton for tensorization.""" int32_lanes = 32 num_int8_elements = 4 # 4 int8 elements in int32 data = te.placeholder((num_int8_elements,), dtype=x_ty, name="data") kernel = te.placeholder((int32_lanes, num_int8_elements), dtype=y_ty, name="kernel") k = te.reduce_axis((0, num_int8_elements), name="k") C = te.compute( (int32_lanes,), lambda i: te.sum(data[k].astype("int32") * kernel[i, k].astype("int32"), axis=k), name="C", ) a_buffer = tvm.tir.decl_buffer( data.shape, dtype=x_ty, name="a_buffer", offset_factor=1, strides=[1] ) b_buffer = tvm.tir.decl_buffer( kernel.shape, dtype=y_ty, name="b_buffer", offset_factor=1, strides=[te.var("ldw"), 1] ) def _intrin_func(ins, outs): def _instr(index): ib = tvm.tir.ir_builder.create() if index == 1: ib.emit(outs[0].vstore(0, tvm.tir.const(0, "int32x32"))) return ib.get() vec_zero = tvm.tir.const(0, "int32x32") if x_ty == "uint8" and y_ty == "uint8": a_uint8 = ins[0].vload([0], "uint8x4") re_int32 = tvm.tir.call_intrin("int32", "tir.reinterpret", a_uint8) vec_b = ins[1].vload([0, 0], "uint8x128") vrmpy_inst_name = "llvm.hexagon.V6.vrmpyub.acc.128B" vec_bi32 = tvm.tir.call_intrin("int32x32", "tir.reinterpret", vec_b) quad_reduction = tvm.tir.call_llvm_pure_intrin( "int32x32", vrmpy_inst_name, tvm.tir.const(3, "uint32"), vec_zero, vec_bi32, re_int32, ) elif x_ty == "uint8" and y_ty == "int8": a_uint8 = ins[0].vload([0], "uint8x4") re_int32 = tvm.tir.call_intrin("int32", "tir.reinterpret", a_uint8) vec_b = ins[1].vload([0, 0], "int8x128") vrmpy_inst_name = "llvm.hexagon.V6.vrmpybusv.acc.128B" vec_bi32 = tvm.tir.call_intrin("int32x32", "tir.reinterpret", vec_b) quad_reduction = tvm.tir.call_llvm_pure_intrin( "int32x32", vrmpy_inst_name, tvm.tir.const(3, "uint32"), vec_zero, re_int32.astype("int32x32"), vec_bi32, ) else: raise ValueError(f"Only (u8, u8) or (u8, i8) dtype pairs are supported by vrmpy.") if index == 0: ib.emit(outs[0].vstore(0, quad_reduction)) else: ib.emit(outs[0].vstore(0, quad_reduction + outs[0].vload([0], "int32x32"))) return ib.get() # body, reset, update return _instr(0), _instr(1), _instr(2) buffer_params = {"offset_factor": 1} return te.decl_tensor_intrin( C.op, _intrin_func, binds={data: a_buffer, kernel: b_buffer}, default_buffer_params=buffer_params, )
https://github.com/zk-ml/tachikoma
python/tvm/topi/hexagon/utils.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=invalid-name """Common hexagon specific utilities""" import math import struct from typing import Tuple from tvm import te def n11c_1024c_2d(n, h, w, c): """Return index map for n11c_1024 2d layout""" return [n, h, w, c // 1024, te.AXIS_SEPARATOR, c % 1024] def n11c_1024c_1d(n, h, w, c): """Return index map for n11c_1024 1d layout""" return [n, h, w, c // 1024, c % 1024] def nhwc_8h2w32c2w_2d(n, h, w, c): """Return index map for nhwc_8h2w32c2w 2d layout""" return [n, h // 8, w // 4, c // 32, te.AXIS_SEPARATOR, h % 8, (w % 4) // 2, c % 32, w % 2] def nhwc_8h2w32c2w_1d(n, h, w, c): """Return index map for nhwc_8h2w32c2w 1d layout""" return [n, h // 8, w // 4, c // 32, h % 8, (w % 4) // 2, c % 32, w % 2] def nhw_32h16w_2d(n, h, w): """Return index map for nhw_32h16w 2d layout""" return [n, h // 32, w // 16, te.AXIS_SEPARATOR, h % 32, w % 16] def nhwc_4h4w32c_1d(n, h, w, c): """Return index map for nhwc_4h4232c 1d layout""" return [n, h // 4, w // 4, c // 32, h % 4, w % 4, c % 32] def nhwc_4h4w32c_2d(n, h, w, c): """Return index map for nhwc_4h4w32c 2d layout""" return [n, h // 4, w // 4, c // 32, te.AXIS_SEPARATOR, h % 4, w % 4, c % 32] def nc_512c_1d(n, c): """Return index map for nc_512c 1d layout""" return [n, c // 512, c % 512] def nc_512c_2d(n, c): """Return index map for nc_512c 2d layout""" return [n, c // 512, te.AXIS_SEPARATOR, c % 512] def nc_1024c_2d(n, c): """Return index map for nc_1024c 2d layout""" return [n, c // 1024, te.AXIS_SEPARATOR, c % 1024] def nhwc_4h2w32c2w_2d(n, h, w, c): """Return index map for nhwc_4h2w32c2w 2d layout""" return [n, h // 4, w // 4, c // 32, te.AXIS_SEPARATOR, h % 4, (w % 4) // 2, c % 32, w % 2] def nhwc_1024c_2d(n, h, w, c): """Return index map for nhwc_1024 2d layout""" return [n, h, w, c // 1024, te.AXIS_SEPARATOR, c % 1024] def nc_1024_2d(n, c): """Return index map for nc_1024 2d layout""" return [n, c // 1024, te.AXIS_SEPARATOR, c % 1024] def nhwc_2048c_2d(n, h, w, c): """Return index map for nhwc_2048 2d layout""" return [n, h, w, c // 2048, te.AXIS_SEPARATOR, c % 2048] def nc_2048_2d(n, c): """Return index map for nc_2048 2d layout""" return [n, c // 2048, te.AXIS_SEPARATOR, c % 2048] def nc_2048c_2d(n, c): """Return index map for nc_2048 2d layout""" return [n, c // 2048, te.AXIS_SEPARATOR, c % 2048] def nhwc_8h8w32c_2d(n, h, w, c): """Return index map for nhwc_8h8w32c 2d layout""" return [n, h // 8, w // 8, c // 32, te.AXIS_SEPARATOR, h % 8, w % 8, c % 32] def n11c_2048c_2d(n, h, w, c): """Return index map for n11c_2048c 2d layout""" return [n, h, w, c // 2048, te.AXIS_SEPARATOR, c % 2048] def iohw_16i32o2i_1d(height, width, in_channel, out_channel): return [ in_channel // 32, out_channel // 32, height, width, (in_channel % 32) // 2, out_channel % 32, in_channel % 2, ] def ohwi32o_1d(height, width, in_channel, out_channel): return [out_channel // 32, height, width, in_channel, out_channel % 32] def get_layout_transform_fn(layout): """Return index map function as per the layout string""" if layout == "nhwc-8h2w32c2w-2d": return nhwc_8h2w32c2w_2d if layout == "nhwc-8h2w32c2w-1d": return nhwc_8h2w32c2w_1d if layout == "n11c-1024c-2d": return n11c_1024c_2d if layout == "n11c-1024c-1d": return n11c_1024c_1d if layout == "nhwc-1024c-2d": return nhwc_1024c_2d if layout == "nc-1024-2d": return nc_1024_2d if layout == "nhw-32h16w-2d": return nhw_32h16w_2d if layout == "nhwc-4h4w32c-2d": return nhwc_4h4w32c_2d if layout == "nhwc-4h4w32c-1d": return nhwc_4h4w32c_1d if layout == "nc-512c-2d": return nc_512c_2d if layout == "nc-512c-1d": return nc_512c_1d if layout == "nhwc-4h2w32c2w-2d": return nhwc_4h2w32c2w_2d if layout == "nc-1024c-2d": return nc_1024c_2d if layout == "iohw-16i32o2i-1d": return iohw_16i32o2i_1d if layout == "nhwc-2048c-2d": return nhwc_2048c_2d if layout == "nc-2048-2d": return nc_2048_2d if layout == "nc-2048c-2d": return nc_2048c_2d if layout == "nhwc-8h8w32c-2d": return nhwc_8h8w32c_2d if layout == "n11c-2048c-2d": return n11c_2048c_2d if layout == "ohwi32o-1d": return ohwi32o_1d raise RuntimeError(f"Unexpected layout '{layout}'") def get_fixed_point_value(flp: float, dtype: str = "int16") -> Tuple[int, int]: """ Return fixed-point value and the corresponding log2 of the scale factor used to compute this value. Parameters ---------- flp : float Floating-point value to be converted dtype : str Type of the resulting fixed-point value. By default, it's set to "int16" Returns ------- fixed_point_value : int Fixed-point value for the given floating-point value exp_scale_factor : int log2 of the scale factor Convert floating-point value into fixed-point number. This is done by multiplying the value by a scaling factor and then rounding it to the nearest integer value. As per IEEE-754 standard, a floating-point value can be represented as follows [see: https://en.wikipedia.org/wiki/IEEE_754-1985]: (-1)^S * M * 2^(E-Bias) Here, * S is the signed bit (0 or 1). * M is the mantissa. It's composed of an implicit 1 for the normalized floating-point values or 0 for the denormalized values, and the fraction part. This ensures that mantissa is always within [0, 2) range. Please note that this function doesn't handle denormalized values. * E is the exponent. In single precision, 23 bits are used to represent the fraction part of the mantissa (and therefore, '23' shows up in one of the computations below) and 8 bits are used for the exponent. Since exponent field needs to reperesent both positive and negative values, a bias (127 for single precision) is added to the actual value. Therefore, to compute the actual exponent, 127 must be subtracted from the stored value. As mentioned above, to find the corresponding fixed-point number, we multiply the value with a scaling factor and then round it to the nearest integer. The scaling factor is chosen to be a power for 2 and it's the largest value that can be safely multiplied to the floating-point value, without causing the resulting value to overflow the range of the integer type used to represent the fixed-point value. So, if we assume the scaling factor to be 2^x, the resulting fixed-point value will be: round((-1)^S * (M) * 2^(E-Bias) * 2^x) This can be simplified to: round((-1)^S * M * 2^(E-Bias+x) Now, if 'int16' is used for fixed-point value, then it has to be >= -(2 * 2^14) and <= (2 * 2^14) - 1. Since M (Mantissa) is always < 2, in order for the fixed-point value to be within this range, 2^(E - Bias + x) must be <= 2^14 - 1. And, if we ignore -1, (E - Bias + x) should be <= 14. Note: if mantissa gets too close to 2, this will cause the resulting value to go out of range and require it to be saturated. In the following implementation, we perform range check and adjust the scale to avoid saturation. For most cases, 2^x, where x = 14 - (E - Bias) or 14 - (E - 127) for single precision, is the best scaling factor for 'int16' type that can be used to convert the floating-point value to fixed-point with the least amount of precision loss. Here is a more rigorous explanation of the above, for non-negative scale values, which are of interest. M < 2, so M * 2^(E-Bias+x) < 2 ^ (E-Bias+x+1) [Note: LHS is a fraction, RHS int] => round(M * 2^(E-Bias+x)) <= 2 ^ (E-Bias+x+1) [Note the "<=", not "<"] We want x s.t. round(M * 2^(E-Bias+x)) <= 2^15 - 1 We know round(M * 2^(E-Bias+x)) <= 2^(E-Bias+x+1) It will be sufficient to choose x s.t. 2^(E-Bias+x+1) <= 2^15 - 1 That is, max x. s.t. 2^(E-Bias+x+1) < 2^15 E-Bias+x+1 < 15 E-Bias+x+1 <= 14 Max x will make E-Bias+x+1 = 14 x = 13 - E + Bias Additonal notes on various floating-point values: ------------------------------------------------ 1) Denormalized values: causes assertion failure. The problem with the denormalized values is that they require a very large scale factor (>= 2^127) to be converted to a fixed-point value. As the denormalzied values get smaller, the scale factor becomes too large to be represented as a IEEE-754 floating point value (as being done in the computaton below) and therefore, the denormalized values aren't being handled here. 2) NaN and INF: assertion failure """ def within_range(val, dtype): if dtype == "int16": return -32768 <= val <= 32767 raise RuntimeError(f"Unsupported dtype, {dtype}'") # Make sure that 'flp' isn't NaN or infinity if math.isnan(flp) or math.isinf(flp): raise RuntimeError("NaN or INF can not be represented as fixed-point") flp_f = struct.pack("f", flp) flp_i = struct.unpack("I", flp_f) exp_stored_value = (flp_i[0] >> 23) & 0xFF if exp_stored_value == 0: raise RuntimeError( "Denormalized values are not considered for float -> fixed-point conversion!" ) exp_value = ((flp_i[0] >> 23) & 0xFF) - 127 if dtype == "int16": max_bits = 14 else: raise RuntimeError(f"Unsupported dtype, {dtype}'") exp_scale_factor = max_bits - exp_value # log2 of the scale_factor if exp_scale_factor > 127: raise RuntimeError("Value too small for fixed-point conversion!") # Scaling factor = 2^exp_scale_factor # Since exp_scale_factor can be -ve or +ve, scaling factor is calculated by first # representing the value in the binary format as per IEEE floating-point standand and then # reinterpreting it as a float using struct.pack and struct.unpack functions. # struct.pack returns a bytes object packed as integer and struct.unpack # unpacks this bytes object into float. scale = ((exp_scale_factor + 127) & 0xFF) << 23 scale_i = struct.pack("I", scale) scale_f = struct.unpack("f", scale_i) fixed_point_value = int(round(flp * scale_f[0])) if not within_range(fixed_point_value, dtype): # Adjust scale factor to avoid overflow. exp_scale_factor -= 1 scale = ((exp_scale_factor + 127) & 0xFF) << 23 scale_i = struct.pack("I", scale) scale_f = struct.unpack("f", scale_i) fixed_point_value = int(round(flp * scale_f[0])) return fixed_point_value, exp_scale_factor def saturate(x: te.Tensor, dtype: str): """Saturate value for the specified data type""" return te.max(te.min_value(dtype), te.min(x, te.max_value(dtype)))
https://github.com/zk-ml/tachikoma
python/tvm/topi/hls/__init__.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=redefined-builtin, wildcard-import """HLS specific declaration and schedules.""" from __future__ import absolute_import as _abs from .injective import schedule_injective, schedule_elemwise, schedule_broadcast from .nn import *
https://github.com/zk-ml/tachikoma
python/tvm/topi/hls/injective.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=invalid-name, unused-variable, """Schedule for composition of injective operator""" import tvm from tvm import te def schedule_injective_from_existing(sch, out): """Schedule for injective op from existing schedule. Parameters ---------- sch: Schedule The schedule to update. out: Tensor The tensor representing the injective op. Returns ------- sch: Schedule The updated schedule. """ fused = sch[out].fuse(*sch[out].op.axis) px, x = sch[out].split(fused, nparts=1) sch[out].bind(px, te.thread_axis("pipeline")) return sch def schedule_injective(outs): """Schedule for injective op. Parameters ---------- outs: Array of Tensor The computation graph description of injective in the format of an array of tensors. Returns ------- sch: Schedule The computation schedule for the op. """ outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs s = te.create_schedule([x.op for x in outs]) tvm.te.schedule.AutoInlineInjective(s) for out in outs: schedule_injective_from_existing(s, out) return s schedule_elemwise = schedule_injective schedule_broadcast = schedule_injective
https://github.com/zk-ml/tachikoma
python/tvm/topi/hls/nn.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=invalid-name,unused-variable,unused-argument """HLS nn operators""" from __future__ import absolute_import as _abs import tvm from tvm import te from .. import tag def _schedule_conv2d(outs): outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs s = te.create_schedule([x.op for x in outs]) tvm.te.schedule.AutoInlineInjective(s) def traverse(OP): """Internal traverse function""" # inline all one-to-one-mapping operators except the last stage (output) if tag.is_injective(OP.tag): if OP not in s.outputs: s[OP].compute_inline() for tensor in OP.input_tensors: if isinstance(tensor.op, tvm.te.ComputeOp): traverse(tensor.op) # schedule conv2d elif OP.tag.find("conv2d") >= 0: Conv2d = OP.output(0) if not Conv2d.op in s.outputs: Out = outs[0].op.output(0) s[Conv2d].compute_at(s[Out], s[Out].op.axis[1]) else: raise RuntimeError("Unsupported operator: %s" % OP.tag) traverse(outs[0].op) px, x = s[outs[0]].split(outs[0].op.axis[0], nparts=1) s[outs[0]].bind(px, te.thread_axis("pipeline")) return s def schedule_conv2d_nchw(outs): """Schedule for conv2d_nchw Parameters ---------- outs: Array of Tensor The computation graph description of conv2d_nchw in the format of an array of tensors. Returns ------- sch: Schedule The computation schedule for the op. """ return _schedule_conv2d(outs) def schedule_conv2d_nhwc(outs): """Schedule for conv2d_nhwc Parameters ---------- outs: Array of Tensor The computation graph description of conv2d_nchw in the format of an array of tensors. Returns ------- sch: Schedule The computation schedule for the op. """ return _schedule_conv2d(outs) def schedule_conv2d_NCHWc(outs): """Schedule for conv2d_NCHW[x]c Parameters ---------- outs : Array of Tensor The computation graph description of conv2d_NCHWc in the format of an array of tensors. Returns ------- sch : Schedule The computation schedule for the op. """ return _schedule_conv2d(outs) def schedule_conv2d_transpose_nchw(outs): """Schedule for conv2d_transpose_nchw Parameters ---------- outs: Array of Tensor The computation graph description of conv2d_transpose_nchw in the format of an array of tensors. Returns ------- s: Schedule The computation schedule for the op. """ return _schedule_conv2d(outs) def schedule_depthwise_conv2d_nchw(outs): """Schedule for depthwise_conv2d_nchw Parameters ---------- outs: Array of Tensor The computation graph description of depthwise_conv2d_nchw in the format of an array of tensors. Returns ------- sch: Schedule The computation schedule for the op. """ return _schedule_conv2d(outs) def schedule_depthwise_conv2d_nhwc(outs): """Schedule for depthwise_conv2d_nhwc Parameters ---------- outs: Array of Tensor The computation graph description of depthwise_conv2d_nhwc in the format of an array of tensors. Returns ------- sch: Schedule The computation schedule for the op. """ return _schedule_conv2d(outs) def schedule_bitserial_conv2d_nchw(outs): """Schedule for bitserial_conv2d_nchw Parameters ---------- outs: Array of Tensor The computation graph description of bitserial_conv2d_nchw in the format of an array of tensors. Returns ------- sch: Schedule The computation schedule for the op. """ return _schedule_conv2d(outs) def schedule_bitserial_conv2d_nhwc(outs): """Schedule for bitserial_conv2d_nhwc Parameters ---------- outs: Array of Tensor The computation graph description of bitserial_conv2d_nchw in the format of an array of tensors. Returns ------- sch: Schedule The computation schedule for the op. """ return _schedule_conv2d(outs) def schedule_reduce(outs): """Schedule for reduction 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, te.tensor.Tensor) else outs s = te.create_schedule([x.op for x in outs]) tvm.te.schedule.AutoInlineInjective(s) def traverse(OP): """Internal traverse function""" # inline all one-to-one-mapping operators except the last stage (output) if tag.is_broadcast(OP.tag): if OP not in s.outputs: s[OP].compute_inline() for tensor in OP.input_tensors: if isinstance(tensor.op, tvm.te.ComputeOp): traverse(tensor.op) elif OP.tag in ["comm_reduce", "comm_reduce_idx"]: if OP.tag == "comm_reduce": Reduce = OP.output(0) else: Reduce = OP.input_tensors[0] if not Reduce.op in s.outputs: Out = outs[0].op.output(0) s[Reduce].compute_at(s[Out], s[Out].op.axis[0]) else: raise RuntimeError("Unsupported operator: %s" % OP.tag) traverse(outs[0].op) fused = s[outs[0]].fuse() px, x = s[outs[0]].split(fused, nparts=1) s[outs[0]].bind(px, te.thread_axis("pipeline")) return s def schedule_softmax(outs): """Schedule for softmax Parameters ---------- outs: Array of Tensor The computation graph description of softmax in the format of an array of tensors. Returns ------- sch: Schedule The computation schedule for the op. """ outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs s = te.create_schedule([x.op for x in outs]) tvm.te.schedule.AutoInlineInjective(s) softmax = outs[0] op_tag = softmax.op.tag if op_tag == "softmax_output": expsum = softmax.op.input_tensors[1] exp = softmax.op.input_tensors[0] max_elem = s[exp].op.input_tensors[1] elif op_tag == "log_softmax_output": exp = None max_elem = softmax.op.input_tensors[1] expsum = softmax.op.input_tensors[2] else: raise ValueError( "Tag is expected to be softmax_output or log_softmax_output. \ Got {0}".format( op_tag ) ) if exp is not None: s[exp].compute_at(s[softmax], s[softmax].op.axis[1]) s[expsum].compute_at(s[softmax], s[softmax].op.axis[1]) s[max_elem].compute_at(s[softmax], s[softmax].op.axis[1]) px, x = s[softmax].split(softmax.op.axis[0], nparts=1) s[softmax].bind(px, te.thread_axis("pipeline")) return s def schedule_dense(outs): """Schedule for dense Parameters ---------- outs: Array of Tensor The computation graph description of dense in the format of an array of tensors. Returns ------- sch: Schedule The computation schedule for the op. """ outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs s = te.create_schedule([x.op for x in outs]) tvm.te.schedule.AutoInlineInjective(s) def traverse(OP): """Internal traverse function""" # inline all one-to-one-mapping operators except the last stage (output) if tag.is_broadcast(OP.tag): if OP not in s.outputs: s[OP].compute_inline() for tensor in OP.input_tensors: if isinstance(tensor.op, tvm.te.ComputeOp): traverse(tensor.op) # schedule dense elif OP.tag == "dense": Dense = OP.output(0) if not Dense.op in s.outputs: Out = outs[0].op.output(0) s[Dense].compute_at(s[Out], s[Out].op.axis[1]) else: raise RuntimeError("Unsupported operator: %s" % OP.tag) traverse(outs[0].op) px, x = s[outs[0]].split(outs[0].op.axis[0], nparts=1) s[outs[0]].bind(px, te.thread_axis("pipeline")) return s def schedule_pool(outs, layout): """Schedule for pool Parameters ---------- outs: Array of Tensor The computation graph description of pool in the format of an array of tensors. Returns ------- sch: Schedule The computation schedule for the op. """ outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs s = te.create_schedule([x.op for x in outs]) tvm.te.schedule.AutoInlineInjective(s) def traverse(OP): """Internal traverse function""" # inline all one-to-one-mapping operators except the last stage (output) if tag.is_broadcast(OP.tag): if OP not in s.outputs: s[OP].compute_inline() for tensor in OP.input_tensors: if isinstance(tensor.op, tvm.te.ComputeOp): traverse(tensor.op) # schedule pool elif OP.tag.startswith("pool"): Pool = OP.output(0) if not Pool.op in s.outputs: Out = outs[0].op.output(0) s[Pool].compute_at(s[Out], s[Out].op.axis[1]) else: raise RuntimeError("Unsupported operator: %s" % OP.tag) traverse(outs[0].op) px, x = s[outs[0]].split(outs[0].op.axis[0], nparts=1) s[outs[0]].bind(px, te.thread_axis("pipeline")) return s def schedule_adaptive_pool(outs): """Schedule for adaptive_pool Parameters ---------- outs: Array of Tensor The computation graph description of adaptive_pool in the format of an array of tensors. Returns ------- sch: Schedule The computation schedule for the op. """ outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs s = te.create_schedule([x.op for x in outs]) tvm.te.schedule.AutoInlineInjective(s) def traverse(OP): """Internal traverse function""" # inline all one-to-one-mapping operators except the last stage (output) if tag.is_broadcast(OP.tag): if OP not in s.outputs: s[OP].compute_inline() for tensor in OP.input_tensors: if isinstance(tensor.op, tvm.te.ComputeOp): traverse(tensor.op) # schedule global_pool elif OP.tag.startswith("adaptive_pool"): Pool = OP.output(0) if not Pool.op in s.outputs: Out = outs[0].op.output(0) s[Pool].compute_at(s[Out], s[Out].op.axis[1]) else: raise RuntimeError("Unsupported operator: %s" % OP.tag) traverse(outs[0].op) px, x = s[outs[0]].split(outs[0].op.axis[0], nparts=1) s[outs[0]].bind(px, te.thread_axis("pipeline")) return s
https://github.com/zk-ml/tachikoma
python/tvm/topi/image/__init__.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=wildcard-import """IMAGE network operators""" from __future__ import absolute_import as _abs from .resize import * from .dilation2d import * from .grid_sample import *
https://github.com/zk-ml/tachikoma
python/tvm/topi/image/dilation2d.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=invalid-name, unused-variable, too-many-locals # pylint: disable=unused-argument, redefined-builtin """Dilation2D operators""" from __future__ import absolute_import as _abs from tvm import te from tvm.topi.utils import simplify from ..nn.pad import pad from ..nn.utils import get_pad_tuple def dilation2d_nchw(input, filter, stride, padding, dilations, out_dtype=None): """Morphological dilation operator in NCHW layout. Parameters ---------- input : tvm.te.Tensor 4-D with shape [batch, in_channel, in_height, in_width] filter : tvm.te.Tensor 3-D with shape [ in_channel, filter_height, filter_width] stride : int or a list/tuple of two ints Stride size, or [stride_height, stride_width] padding : int or str Padding size dilations: int or a list/tuple of two ints dilation size, or [dilation_height, dilation_width] out_dtype : Optional[str] Specifies the output data type. Returns ------- Output : tvm.te.Tensor 4-D with shape [batch, in_channel, out_height, out_width] """ if out_dtype is None: out_dtype = input.dtype assert isinstance(stride, int) or len(stride) == 2 assert isinstance(dilations, int) or len(dilations) == 2 if isinstance(stride, int): stride_h = stride_w = stride else: stride_h, stride_w = stride if isinstance(dilations, int): dilation_h = dilation_w = dilations else: dilation_h, dilation_w = dilations batch, in_channel, in_height, in_width = input.shape channel, kernel_h, kernel_w = filter.shape assert ( in_channel.value == channel.value ), "For Dilation2D input and filter channels should be same." # compute the output shape dilated_kernel_h = (kernel_h - 1) * dilation_h + 1 dilated_kernel_w = (kernel_w - 1) * dilation_w + 1 pad_top, pad_left, pad_down, pad_right = get_pad_tuple( padding, (dilated_kernel_h, dilated_kernel_w) ) out_height = simplify((in_height - dilated_kernel_h + pad_top + pad_down) // stride_h + 1) out_width = simplify((in_width - dilated_kernel_w + pad_left + pad_right) // stride_w + 1) # compute graph pad_before = [0, 0, pad_top, pad_left] pad_after = [0, 0, pad_down, pad_right] temp = pad(input, pad_before, pad_after, name="pad_temp") ry = te.reduce_axis((0, kernel_h), name="ry") rx = te.reduce_axis((0, kernel_w), name="rx") return te.compute( (batch, in_channel, out_height, out_width), lambda nn, ff, yy, xx: te.max( temp[nn, ff, yy * stride_h + ry * dilation_h, xx * stride_w + rx * dilation_w].astype( out_dtype ) + filter[ff, ry, rx].astype(out_dtype), axis=[ry, rx], ), tag="dilation2d_nchw", ) def dilation2d_nhwc(input, filter, stride, padding, dilations, out_dtype=None): """Morphological 2d dilation NHWC layout. Parameters ---------- input : tvm.te.Tensor 4-D with shape [batch, in_height, in_width, in_channel] filter : tvm.te.Tensor 3-D with shape [filter_height, filter_width, in_channel] stride : int or a list/tuple of two ints Stride size, or [stride_height, stride_width] padding : int Padding size dilations: int or a list/tuple of two ints dilation size, or [dilation_height, dilation_width] out_dtype : Optional[str] Specifies the output data type. Returns ------- Output : tvm.te.Tensor 4-D with shape [batch, out_height, out_width, in_channel] """ if out_dtype is None: out_dtype = input.dtype assert isinstance(stride, int) or len(stride) == 2 assert isinstance(dilations, int) or len(dilations) == 2 if isinstance(stride, int): stride_h = stride_w = stride else: stride_h, stride_w = stride if isinstance(dilations, int): dilation_h = dilation_w = dilations else: dilation_h, dilation_w = dilations batch, in_height, in_width, in_channel = input.shape kernel_h, kernel_w, channel = filter.shape assert ( in_channel.value == channel.value ), "For Dilation2D input and filter channels should be same." # compute the output shape dilated_kernel_h = (kernel_h - 1) * dilation_h + 1 dilated_kernel_w = (kernel_w - 1) * dilation_w + 1 pad_top, pad_left, pad_down, pad_right = get_pad_tuple( padding, (dilated_kernel_h, dilated_kernel_w) ) out_height = simplify((in_height - dilated_kernel_h + pad_top + pad_down) // stride_h + 1) out_width = simplify((in_width - dilated_kernel_w + pad_left + pad_right) // stride_w + 1) pad_before = [0, pad_top, pad_left, 0] pad_after = [0, pad_down, pad_right, 0] padded_input = pad(input, pad_before, pad_after, name="padded_input") ry = te.reduce_axis((0, kernel_h), name="ry") rx = te.reduce_axis((0, kernel_w), name="rx") return te.compute( (batch, out_height, out_width, in_channel), lambda nn, yy, xx, ff: te.max( padded_input[ nn, yy * stride_h + ry * dilation_h, xx * stride_w + rx * dilation_w, ff ].astype(out_dtype) + filter[ry, rx, ff].astype(out_dtype), axis=[ry, rx], ), tag="dilation2d_nhcw", )
https://github.com/zk-ml/tachikoma
python/tvm/topi/image/grid_sample.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=invalid-name """affine_grid and grid_sample operator""" from tvm import te, tir def affine_grid(data, target_shape): """affine_grid operator that generates 2D sampling grid. This operation is described in https://arxiv.org/pdf/1506.02025.pdf. It generates a uniform sampling grid within the target shape and normalizes it to [-1, 1]. The provided affine transformation is then applied on the sampling grid. Parameters ---------- data : tvm.Tensor 3-D with shape [batch, 2, 3]. The affine matrix. target_shape: list/tuple of two int Specifies the output shape (H, W). Returns ------- Output : tvm.Tensor 4-D with shape [batch, 2, target_height, target_width] """ assert target_shape is not None assert len(target_shape) == 2 assert ( target_shape[0] > 1 and target_shape[1] > 1 ), "target height/width should be greater than 1" dtype = data.dtype y_step = tir.const((2.0 - 1e-7) / (target_shape[0] - 1), dtype=dtype) x_step = tir.const((2.0 - 1e-7) / (target_shape[1] - 1), dtype=dtype) start = tir.const(-1.0, dtype=dtype) def _compute(n, dim, i, j): y = start + i * y_step x = start + j * x_step return data[n, dim, 0] * x + data[n, dim, 1] * y + data[n, dim, 2] oshape = (data.shape[0], len(target_shape), *target_shape) return te.compute(oshape, _compute, tag="affine_grid") def _grid_sample_2d( data, grid, method="bilinear", layout="NCHW", padding_mode="zeros", align_corners=True ): """Applies bilinear/nearest/bicubic sampling to input feature map. Given :math:`data` and :math:`grid` assuming NCHW layout, then the output is computed by .. math:: x_{src} = grid[batch, 0, y_{dst}, x_{dst}] \\ y_{src} = grid[batch, 1, y_{dst}, x_{dst}] \\ output[batch, channel, y_{dst}, x_{dst}] = G(data[batch, channel, y_{src}, x_{src}) :math:`x_{dst}`, :math:`y_{dst}` enumerate all spatial locations in :math:`output`, and :math:`G()` denotes the interpolation method. The out-boundary points will be padded with zeros if padding_mode is "zeros", or border pixel value if padding_mode is "border", or inner pixel value if padding_mode is "reflection". The left-top corner (-1, -1) and right-bottom corner (1, 1) in grid will be map to (0, 0) and (h - 1, w - 1) of data if align_corners is "True", or (-0.5, -0.5) and (h - 0.5, w - 0.5) of data if align_corners is "False". The shape of the output will be (data.shape[0], data.shape[1], grid.shape[2], grid.shape[3]). The operator assumes that :math:`grid` has been normalized to [-1, 1]. grid_sample often cooperates with affine_grid which generates sampling grids for grid_sample. Parameters ---------- data : tvm.Tensor 4-D with shape [batch, in_channel, in_height, in_width] grid : tvm.Tensor 4-D with shape [batch, 2, out_height, out_width] method : str The interpolation method "nearest", "bilinear", "bicubic" are supported. layout : str The layout of input data and the output. padding_mode : str The padding mode for outside grid values, "zeros", "border", "reflection" are supported. align_corners: bool Geometrically, we consider the pixels of the input as squares rather than points. If set to "True", the extrema ("-1" and "1") are considered as referring to the center points of the input corner pixels. If set to "False", they are instead considered as referring to the corner points of the input corner pixels, making the sampling more resolution agnostic. Returns ------- Output : tvm.Tensor 4-D with shape [batch, in_channel, out_height, out_width] """ assert method in ("bilinear", "nearest", "bicubic"), f"{method} is not supported" assert padding_mode in ("zeros", "border", "reflection"), f"{padding_mode} is not supported" assert layout == "NCHW", f"{layout} is not supported" batch, in_channel, in_height, in_width = data.shape out_height, out_width = grid.shape[2:] def _get_pixel_value(n, c, h, w): return te.if_then_else( te.all(h >= 0, w >= 0, h < in_height, w < in_width), data[n, c, h, w], tir.const(0.0, dtype=data.dtype), ) def _unnormalize(h, w): if align_corners: y = (h + 1) * (in_height - 1) / 2 x = (w + 1) * (in_width - 1) / 2 else: y = -0.5 + (h + 1) * in_height / 2 x = -0.5 + (w + 1) * in_width / 2 return (y, x) def _clip_coordinates(x, size): return te.min(te.max(x, 0), size - 1) def _compute_source_index(n, h, w): y = grid[n, 1, h, w] x = grid[n, 0, h, w] y, x = _unnormalize(y, x) if padding_mode == "reflection": y = _reflect_coordinates(y, in_height) x = _reflect_coordinates(x, in_width) y = _clip_coordinates(y, in_height) x = _clip_coordinates(x, in_width) elif padding_mode == "border": y = _clip_coordinates(y, in_height) x = _clip_coordinates(x, in_width) return (y, x) def _reflect_coordinates(x, size): def __refelection(x, size, corner_start): def __reflect(index, size, corner_start): index_align_corner = te.abs(corner_start - index) size_times = te.truncdiv(index_align_corner.astype("int32"), size).astype("int32") t = tir.Mod(size_times, 2) extra = index_align_corner - size_times * size return tir.if_then_else( tir.EQ(t, 0), extra + corner_start, size - extra + corner_start ) return tir.if_then_else( tir.all(x >= corner_start, x <= size + corner_start), x, __reflect(x, size, corner_start), ) if align_corners: new_x = __refelection(x, size - 1, 0) else: new_x = __refelection(x, size, -0.5) return new_x def _bilinear_sample(n, c, h, w): y, x = _compute_source_index(n, h, w) y0 = te.floor(y).astype("int32") x0 = te.floor(x).astype("int32") y1 = y0 + tir.const(1, "int32") x1 = x0 + tir.const(1, "int32") return ( _get_pixel_value(n, c, y0, x0) * (1.0 - (y - y0)) * (1.0 - (x - x0)) + _get_pixel_value(n, c, y0, x1) * (1.0 - (y - y0)) * (x - x0) + _get_pixel_value(n, c, y1, x0) * (y - y0) * (1.0 - (x - x0)) + _get_pixel_value(n, c, y1, x1) * (y - y0) * (x - x0) ) def _nearest_sample(n, c, h, w): y, x = _compute_source_index(n, h, w) y_new = te.nearbyint(y).astype("int32") x_new = te.nearbyint(x).astype("int32") return _get_pixel_value(n, c, y_new, x_new) def _bicubic_sample(n, c, h, w): A = -0.75 # -0.75 is used in pytorch, it maybe different in other frameworks def cubic_weight_1(fraction): return ((A + 2) * fraction - (A + 3)) * fraction * fraction + 1 def cubic_weight_2(fraction): return ((A * fraction - 5 * A) * fraction + 8 * A) * fraction - 4 * A def cubic_interp_1d(pixel_0, pixel_1, pixel_2, pixel_3, fraction): weights = [0] * 4 weights[0] = cubic_weight_2(fraction + 1) weights[1] = cubic_weight_1(fraction) weights[2] = cubic_weight_1(1 - fraction) weights[3] = cubic_weight_2(2 - fraction) return ( pixel_0 * weights[0] + pixel_1 * weights[1] + pixel_2 * weights[2] + pixel_3 * weights[3] ) y = grid[n, 1, h, w] x = grid[n, 0, h, w] y, x = _unnormalize(y, x) y_floor = te.floor(y).astype("int32") x_floor = te.floor(x).astype("int32") y_fraction = y - y_floor x_fraction = x - x_floor coefficients = [0] * 4 for i in range(4): y_ = y_floor - 1 + i x_0 = x_floor - 1 x_1 = x_floor + 0 x_2 = x_floor + 1 x_3 = x_floor + 2 if padding_mode == "border": y_ = _clip_coordinates(y_, in_height).astype("int32") x_0 = _clip_coordinates(x_0, in_width).astype("int32") x_1 = _clip_coordinates(x_1, in_width).astype("int32") x_2 = _clip_coordinates(x_2, in_width).astype("int32") x_3 = _clip_coordinates(x_3, in_width).astype("int32") elif padding_mode == "reflection": y_ = _reflect_coordinates(y_, in_height) x_0 = _reflect_coordinates(x_0, in_width) x_1 = _reflect_coordinates(x_1, in_width) x_2 = _reflect_coordinates(x_2, in_width) x_3 = _reflect_coordinates(x_3, in_width) y_ = _clip_coordinates(y_, in_height).astype("int32") x_0 = _clip_coordinates(x_0, in_width).astype("int32") x_1 = _clip_coordinates(x_1, in_width).astype("int32") x_2 = _clip_coordinates(x_2, in_width).astype("int32") x_3 = _clip_coordinates(x_3, in_width).astype("int32") coefficients[i] = cubic_interp_1d( _get_pixel_value(n, c, y_, x_0), _get_pixel_value(n, c, y_, x_1), _get_pixel_value(n, c, y_, x_2), _get_pixel_value(n, c, y_, x_3), x_fraction, ) return cubic_interp_1d( coefficients[0], coefficients[1], coefficients[2], coefficients[3], y_fraction ) if method == "bilinear": interpolation = _bilinear_sample elif method == "nearest": interpolation = _nearest_sample else: # method == "bicubic" interpolation = _bicubic_sample return te.compute((batch, in_channel, out_height, out_width), interpolation, tag="grid_sample") def _grid_sample_3d( data, grid, method="bilinear", layout="NCDHW", padding_mode="zeros", align_corners=True ): """Applies bilinear/nearest sampling to input feature map. Given :math:`data` and :math:`grid` assuming NCDHW layout, then the output is computed by .. math:: x_{src} = grid[batch, 0, z_{dst}, y_{dst}, x_{dst}] \\ y_{src} = grid[batch, 1, z_{dst}, y_{dst}, x_{dst}] \\ z_{src} = grid[batch, 2, z_{dst}, y_{dst}, x_{dst}] \\ output[batch, channel, z_{src}, y_{dst}, x_{dst}] = G(data[batch, channel, z_{src}, y_{src}, x_{src}) :math:`x_{dst}`, :math:`y_{dst}`, :math:`z_{dst}` enumerate all spatial locations in :math:`output`, and :math:`G()` denotes the interpolation method. The out-boundary points will be padded with zeros if padding_mode is "zeros", or border pixel value if padding_mode is "border", or inner pixel value if padding_mode is "reflection". The left-top corner (-1, -1, -1) and right-bottom corner (1, 1, 1) in grid will be map to (0, 0, 0) and (d - 1, h - 1, w - 1) of data if align_corners is "True", or (-0.5, -0.5, -0.5) and (d - 0.5, h - 0.5, w - 0.5) of data if align_corners is "False". The shape of the output will be (data.shape[0], data.shape[1], grid.shape[2], grid.shape[3], grid.shape[4]). The operator assumes that :math:`grid` has been normalized to [-1, 1]. grid_sample often cooperates with affine_grid which generates sampling grids for grid_sample. Parameters ---------- data : tvm.Tensor 5-D with shape [batch, in_channel, in_depth, in_height, in_width] grid : tvm.Tensor 5-D with shape [batch, 3, out_depth, out_height, out_width] method : str The interpolation method "nearest", "bilinear"("trilinear") are supported. layout : str The layout of input data and the output. padding_mode : str The padding mode for outside grid values, "zeros", "border", "reflection" are supported. align_corners: bool Geometrically, we consider the pixels of the input as squares rather than points. If set to "True", the extrema ("-1" and "1") are considered as referring to the center points of the input corner pixels. If set to "False", they are instead considered as referring to the corner points of the input corner pixels, making the sampling more resolution agnostic. Returns ------- Output : tvm.Tensor 5-D with shape [batch, in_channel, out_depth, out_height, out_width] """ assert method in ("bilinear", "nearest"), f"{method} is not supported" assert padding_mode in ("zeros", "border", "reflection"), f"{padding_mode} is not supported" assert layout == "NCDHW", f"{layout} is not supported" batch, in_channel, in_depth, in_height, in_width = data.shape out_depth, out_height, out_width = grid.shape[2:] def _get_pixel_value(n, c, d, h, w): return te.if_then_else( te.all(d >= 0, h >= 0, w >= 0, d < in_depth, h < in_height, w < in_width), data[n, c, d, h, w], tir.const(0.0, dtype=data.dtype), ) def _compute_source_index(n, d, h, w): z = grid[n, 2, d, h, w] y = grid[n, 1, d, h, w] x = grid[n, 0, d, h, w] if align_corners: z = (z + 1) * (in_depth - 1) / 2 y = (y + 1) * (in_height - 1) / 2 x = (x + 1) * (in_width - 1) / 2 else: z = -0.5 + (z + 1) * in_depth / 2 y = -0.5 + (y + 1) * in_height / 2 x = -0.5 + (x + 1) * in_width / 2 if padding_mode == "reflection": z = _reflect_coordinates(z, in_depth) y = _reflect_coordinates(y, in_height) x = _reflect_coordinates(x, in_width) z = _clip_coordinates(z, in_depth) y = _clip_coordinates(y, in_height) x = _clip_coordinates(x, in_width) elif padding_mode == "border": z = _clip_coordinates(z, in_depth) y = _clip_coordinates(y, in_height) x = _clip_coordinates(x, in_width) return (z, y, x) def _clip_coordinates(x, size): return te.min(te.max(x, 0), size - 1) def _reflect_coordinates(x, size): def __refelection(x, size, corner_start): def __reflect(index, size, corner_start): index_align_corner = te.abs(corner_start - index) size_times = te.truncdiv(index_align_corner.astype("int32"), size).astype("int32") t = tir.Mod(size_times, 2) extra = index_align_corner - size_times * size return tir.if_then_else( tir.EQ(t, 0), extra + corner_start, size - extra + corner_start ) return tir.if_then_else( tir.all(x >= corner_start, x <= size + corner_start), x, __reflect(x, size, corner_start), ) if align_corners: return __refelection(x, size - 1, 0) return __refelection(x, size, -0.5) def _trilinear_sample(n, c, d, h, w): z, y, x = _compute_source_index(n, d, h, w) z0 = te.floor(z).astype("int32") y0 = te.floor(y).astype("int32") x0 = te.floor(x).astype("int32") z1 = z0 + tir.const(1, "int32") y1 = y0 + tir.const(1, "int32") x1 = x0 + tir.const(1, "int32") return ( _get_pixel_value(n, c, z0, y0, x0) * (1 - (x - x0)) * (1 - (y - y0)) * (1 - (z - z0)) + _get_pixel_value(n, c, z0, y0, x1) * (x - x0) * (1 - (y - y0)) * (1 - (z - z0)) + _get_pixel_value(n, c, z1, y1, x0) * (1 - (x - x0)) * (y - y0) * (z - z0) + _get_pixel_value(n, c, z1, y1, x1) * (x - x0) * (y - y0) * (z - z0) + _get_pixel_value(n, c, z0, y1, x0) * (1 - (x - x0)) * (y - y0) * (1 - (z - z0)) + _get_pixel_value(n, c, z1, y0, x1) * (x - x0) * (1 - (y - y0)) * (z - z0) + _get_pixel_value(n, c, z1, y0, x0) * (1 - (x - x0)) * (1 - (y - y0)) * (z - z0) + _get_pixel_value(n, c, z0, y1, x1) * (x - x0) * (y - y0) * (1 - (z - z0)) ) def _nearest_sample(n, c, d, h, w): z, y, x = _compute_source_index(n, d, h, w) z_new = te.nearbyint(z).astype("int32") y_new = te.nearbyint(y).astype("int32") x_new = te.nearbyint(x).astype("int32") return _get_pixel_value(n, c, z_new, y_new, x_new) if method == "bilinear": interpolation = _trilinear_sample else: # method == "nearest" interpolation = _nearest_sample return te.compute( (batch, in_channel, out_depth, out_height, out_width), interpolation, tag="grid_sample" ) def grid_sample( data, grid, method="bilinear", layout="NCHW", padding_mode="zeros", align_corners=True ): """Applies grid sampling to input feature map. Given :math:`data` and :math:`grid`, then for 4-D the output is computed by .. math:: x_{src} = grid[batch, 0, y_{dst}, x_{dst}] \\ y_{src} = grid[batch, 1, y_{dst}, x_{dst}] \\ output[batch, channel, y_{dst}, x_{dst}] = G(data[batch, channel, y_{src}, x_{src}]) :math:`x_{dst}`, :math:`y_{dst}` enumerate all spatial locations in :math:`output`, and :math:`G()` denotes the interpolation function. The out-boundary points will be padded with zeros if padding_mode is "zeros", or border pixel value if padding_mode is "border", or inner pixel value if padding_mode is "reflection". The left-top corner (-1, -1) and right-bottom corner (1, 1) in grid will be map to (0, 0) and (h - 1, w - 1) of data if align_corners is "True", or (-0.5, -0.5) and (h - 0.5, w - 0.5) of data if align_corners is "False". The shape of the output will be 4-D (data.shape[0], data.shape[1], grid.shape[2], grid.shape[3]), or 5-D (data.shape[0], data.shape[1], grid.shape[2], grid.shape[3], grid.shape[4]). The operator assumes that :math:`grid` has been normalized to [-1, 1]. grid_sample often cooperates with affine_grid which generates sampling grids for grid_sample. Parameters ---------- data : tvm.Tensor 4-D with shape [batch, in_channel, in_height, in_width], or 5-D with shape [batch, in_channel, in_depth, in_height, in_width] grid : tvm.Tensor 4-D with shape [batch, 2, out_height, out_width], or 5-D with shape [batch, 3, out_depth, out_height, out_width] method : str The interpolation method, 4-D "nearest", "bilinear", "bicubic" and 5-D "nearest", "bilinear"("trilinear") are supported. layout : str The layout of input data and the output. padding_mode : str The padding mode for outside grid values, "zeros", "border", "reflection" are supported. align_corners: bool Geometrically, we consider the pixels of the input as squares rather than points. If set to "True", the extrema ("-1" and "1") are considered as referring to the center points of the input corner pixels. If set to "False", they are instead considered as referring to the corner points of the input corner pixels, making the sampling more resolution agnostic. Returns ------- Output : tvm.Tensor 4-D with shape [batch, in_channel, out_height, out_width], or 5-D with shape [batch, in_channel, out_depth, out_height, out_width] """ if len(layout) == 4: compute = _grid_sample_2d elif len(layout) == 5: compute = _grid_sample_3d else: msg = f"layout {layout} is not supported" raise ValueError(msg) return compute(data, grid, method, layout, padding_mode, align_corners)
https://github.com/zk-ml/tachikoma
python/tvm/topi/image/resize.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=invalid-name """TVM operator input resize compute.""" from __future__ import absolute_import import tvm from tvm import te from tvm.topi.utils import nchw_pack_layout, nchw_xc_layout from .. import tag def can_convert_multiply_to_intdiv(origin_size, scaled_size): """Check whether can convert multiplication to division""" # Only support IntImm type if not isinstance(scaled_size, tvm.tir.expr.IntImm): return False div = scaled_size / origin_size.astype("float") if div.value % 1 != 0: return False epsilon = 1e-5 check = 1 / (epsilon * origin_size + epsilon) if div > check: return False return True def get_1d_indices(indices, layout="NCW"): """Get 1d indices""" (cc, inum, ic) = (0, 0, 0) if layout == "NWC": n, x, c = indices cc = None elif layout == "NCW": n, c, x = indices cc = None elif ncw_pack_layout(layout): n, c, x, inum, ic = indices else: # else must be NCHWxc assert ncw_xc_layout(layout) n, c, x, cc = indices return n, c, x, cc, inum, ic def get_2d_indices(indices, layout="NCHW"): """Get 2d indices""" (cc, inum, ic) = (0, 0, 0) if layout == "NHWC": n, y, x, c = indices cc = None elif layout == "NCHW": n, c, y, x = indices cc = None elif nchw_pack_layout(layout): n, c, y, x, inum, ic = indices else: # else must be NCHWxc assert nchw_xc_layout(layout) n, c, y, x, cc = indices return n, c, y, x, cc, inum, ic def get_3d_indices(indices, layout="NCDHW"): """Get 3d indices""" if layout == "NDHWC": n, z, y, x, c = indices cc = None elif layout == "NCDHW": n, c, z, y, x = indices cc = None else: n, c, z, y, x, cc = indices return n, c, z, y, x, cc def get_1d_pixel(data, layout, image_width, n, c, x, cc, ib, ic): """Get 1d pixel""" x = tvm.te.max(tvm.te.min(x, image_width - 1), 0) if layout == "NWC": return data(n, x, c).astype("float") if layout == "NCW": return data(n, c, x).astype("float") if ncw_pack_layout(layout): return data(n, c, x, ib, ic).astype("float") # else must be NCHWxc assert ncw_xc_layout(layout) return data(n, c, x, cc).astype("float") def get_2d_pixel(data, layout, image_height, image_width, n, c, y, x, cc, ib, ic): """Get 2d pixel""" y = tvm.te.max(tvm.te.min(y, image_height - 1), 0) x = tvm.te.max(tvm.te.min(x, image_width - 1), 0) if layout == "NHWC": return data(n, y, x, c).astype("float") if layout == "NCHW": return data(n, c, y, x).astype("float") if nchw_pack_layout(layout): return data(n, c, y, x, ib, ic).astype("float") # else must be NCHWxc assert nchw_xc_layout(layout) return data(n, c, y, x, cc).astype("float") def get_3d_pixel(data, layout, image_depth, image_height, image_width, n, c, z, y, x, cc): """Get 3d pixel""" z = tvm.te.max(tvm.te.min(z, image_depth - 1), 0) y = tvm.te.max(tvm.te.min(y, image_height - 1), 0) x = tvm.te.max(tvm.te.min(x, image_width - 1), 0) if layout == "NDHWC": return data(n, z, y, x, c).astype("float") if layout == "NCDHW": return data(n, c, z, y, x).astype("float") # else must be NCDHWxc return data(n, c, z, y, x, cc).astype("float") def get_inx( x, image_width, target_width, coordinate_transformation_mode, start_x=0, end_x=-1, use_int_div=False, ): """Infer input x from output x with various coordinate transformation methods""" scale_x = te.div(image_width.astype("float"), target_width.astype("float")) if coordinate_transformation_mode == "half_pixel": in_x = (x + 0.5) * scale_x - 0.5 elif coordinate_transformation_mode == "align_corners": in_x = (image_width - 1).astype("float") / (target_width - 1) * x elif coordinate_transformation_mode == "asymmetric": if use_int_div: in_x = te.div(x, te.div(target_width, image_width)) else: in_x = scale_x * x elif coordinate_transformation_mode == "pytorch_half_pixel": in_x = te.if_then_else(target_width > 1, (x + 0.5) * scale_x - 0.5, 0.0) elif coordinate_transformation_mode == "tf_half_pixel_for_nn": in_x = (x + 0.5) * scale_x elif coordinate_transformation_mode == "tf_crop_and_resize": in_x = te.if_then_else( target_width > 1, start_x * (image_width - 1) + x * (end_x - start_x) * (image_width - 1).astype("float") / (target_width - 1), 0.5 * (start_x + end_x) * (image_width - 1), ) else: raise ValueError( "Unsupported coordinate_transformation_mode: {}".format(coordinate_transformation_mode) ) return in_x def get_closest_index(in_x, rounding_method, boxes, use_int_div=False): """get the closest index to a value based on a certain rounding method""" if use_int_div: closest_x_index = in_x.astype("int32") return closest_x_index if rounding_method == "round" or boxes is not None: closest_x_index = te.round(in_x).astype("int32") elif rounding_method == "round_prefer_floor": closest_x_index = te.ceil(in_x - 0.5).astype("int32") elif rounding_method == "round_prefer_ceil": closest_x_index = te.floor(in_x + 0.5).astype("int32") elif rounding_method == "floor": # Add epsilon to floor to prevent gpu rounding errors. epsilon = 1e-5 closest_x_index = te.floor(in_x + epsilon).astype("int32") elif rounding_method == "ceil": # Subract epsilon from ceil to prevent gpu rounding errors. epsilon = 1e-5 closest_x_index = te.ceil(in_x - epsilon).astype("int32") else: raise ValueError("Uknown rounding method: {}".format(rounding_method)) return closest_x_index def _lerp(A, B, t): """Perform Linear interpolation in 1D""" return A * (1.0 - t) + B * t def _cubic_spline_weights(t, alpha): """create cubic spline weights in 1D""" t2 = t * t t3 = t * t * t w1 = alpha * (t3 - 2 * t2 + t) w2 = (alpha + 2) * t3 - (3 + alpha) * t2 + 1 w3 = -(alpha + 2) * t3 + (3 + 2 * alpha) * t2 - alpha * t w4 = -alpha * t3 + alpha * t2 return [w1, w2, w3, w4] def _cubic_kernel(inputs, w): """perform cubic interpolation in 1D""" return sum([a_i * w_i for a_i, w_i in zip(inputs, w)]) def _resize_1d( indices, data, roi, image_width, target_width, boxes=None, box_indices=None, method=None, extrapolation_value=0.0, layout="NCW", coordinate_transformation_mode="align_corners", rounding_method="", alpha=-0.5, exclude_outside=0, out_dtype=None, ): """Perform resize operation on the data with selected method and options. Parameters ---------- indices : tuple The indices of input data data : tvm.te.Tensor inputs is a 3-D tensor with shape [batch, channel, in_width] or [batch, in_width, channel] roi: Tuple of Float or Expr The region of interest for cropping the input image. Expected to be of size 2, and format [start_w, end_w]. Only used if coordinate_transformation_mode is tf_crop_and_resize. image_width : integer Input image width target_width : integer The target resized image width boxes : tvm.te.Tensor, optional A 2-D tensor of shape [num_boxes, 4]. Each row of the tensor specifies the coordinates of a box. box_indices : tvm.te.Tensor, optional A 1-D tensor of shape [num_boxes], box_indices[i] specifies the data that the i-th box refers to. extrapolation_value: float, optional Value used for extrapolation, when applicable. layout: string, optional "NCW", "NWC", or "NCWc". method: string, optional method of interpolation ("nearest", "linear", "bicubic") coordinate_transformation_mode : string, optional Describes how to transform the coordinate in the resized tensor to the coordinate in the original tensor. [half_pixel, align_corners, asymmetric, pytorch_half_pixel, tf_half_pixel_for_nn, and tf_crop_and_resize]. rounding_method: string, optional indicates how to find the "nearest" pixel in nearest_neighbor method [round, floor, ceil] alpha: float, optional Bicubic spline coefficient exclude_outside: bool, optional: Exclude values outside the image fdor bicubic interpolation out_dtype: string, optional Type to return. If left None will be same as input type. Returns ------- output : out_dtype The computed result with type out_dtype """ def _cast_output(value, data_dtype="float32", out_dtype=None): if out_dtype: dtype = out_dtype else: dtype = data_dtype return value.astype(dtype) n, c, x, cc, inum, ic = get_1d_indices(indices, layout) box_idx = box_indices(n) if box_indices is not None else n if boxes is not None: # TODO(mbrookhart): Find an example of this raise NotImplementedError("resize1d with image boxes not yet implemented") in_x = get_inx( x, image_width, target_width, coordinate_transformation_mode, roi[0], roi[1], ) if method == "nearest_neighbor": if rounding_method == "": if coordinate_transformation_mode == "align_corners": rounding_method = "round" else: rounding_method = "floor" closest_x_index = get_closest_index(in_x, rounding_method, boxes) value = get_1d_pixel( data, layout, image_width, box_idx, c, closest_x_index, cc, inum, ic, ) elif method == "linear": x_int = te.floor(in_x).astype("int32") x_lerp = in_x - x_int p = [0 for i in range(2)] for i in range(2): p[i] = get_1d_pixel( data, layout, image_width, box_idx, c, x_int + i, cc, inum, ic, ) value = _lerp(*p, x_lerp) elif method == "cubic": xint = te.floor(in_x).astype("int32") xfract = in_x - te.floor(in_x) # Get the surrounding values p = [0 for i in range(4)] for i in range(4): p[i] = get_1d_pixel( data, layout, image_width, box_idx, c, xint + i - 1, cc, inum, ic, ) wx = _cubic_spline_weights(xfract, alpha) if exclude_outside: for i in range(4): wx[i] = te.if_then_else( te.any(xint - 1 + i < 0, xint + i > image_width), 0.0, wx[i] ) sum_wx = sum(wx) wx = [w / sum_wx for w in wx] value = _cubic_kernel(p, wx) else: raise ValueError("Unknown resize method:", method) if coordinate_transformation_mode == "tf_crop_and_resize": # use extrapolation_value if in_x is out of boundary value = tvm.tir.if_then_else( in_x < 0, extrapolation_value, tvm.tir.if_then_else(in_x > image_width - 1, extrapolation_value, value), ) return _cast_output(value, data.dtype, out_dtype=out_dtype) def resize1d( data, roi, size, layout="NCW", method="linear", coordinate_transformation_mode="half_pixel", rounding_method="", bicubic_alpha=-0.5, bicubic_exclude=0, extrapolation_value=0.0, out_dtype=None, output_shape=None, ): """Perform resize operation on the data. Parameters ---------- data : tvm.te.Tensor inputs is a 3-D tensor with shape [batch, channel in_width] or [batch in_width, channel] roi: Tuple of Float or Expr The region of interest for cropping the input image. Expected to be of size 2, and format [start_w, end_w]. Only used if coordinate_transformation_mode is tf_crop_and_resize. size: Tuple Output resolution scale to layout: string, optional "NCW", "NWC", or "NCWc". coordinate_transformation_mode: string, optional Describes how to transform the coordinate in the resized tensor to the coordinate in the original tensor. Refer to the ONNX Resize operator specification for details. Available options are "half_pixel", "align_corners" and "asymmetric". method: string, optional method of interpolation ("nearest", "linear", "bicubic") coordinate_transformation_mode : string, optional Describes how to transform the coordinate in the resized tensor to the coordinate in the original tensor. [half_pixel, align_corners, asymmetric, pytorch_half_pixel, tf_half_pixel_for_nn, and tf_crop_and_resize]. rounding_method: Method for rounding coordinate locations bicubic_alpha: float, optional Bicubic spline coefficient bicubic_exclude: bool, optional: Exclude values outside the image fdor bicubic interpolation extrapolation_value: float, optional Value used for extrapolation, when applicable. out_dtype: string, optional Type to return. If left None will be same as input type. output_shape: tvm.tir.container.Array, optional Shape to return. If left None will be inferred (If shape is determined dynamically, pass out_dtype.shape as output_shape) Returns ------- output : tvm.te.Tensor 4-D with shape [batch, chananel, in_width*scale] or [batch, in_width*scale, channel] or 5-D with shape [batch, channel-major, in_width*scale, channel-minor] """ method = method.lower() if layout == "NWC": in_n, in_w, in_c = data.shape if output_shape is None: output_shape = [in_n, size[0], in_c] elif layout == "NCW": in_n, in_c, in_w = data.shape if output_shape is None: output_shape = [in_n, in_c, size[0]] elif ncw_pack_layout(layout): # for NCWinic in_n, in_c, in_w, in_inum, in_ic = data.shape if output_shape is None: output_shape = [in_n, in_c, size[0], in_inum, in_ic] elif ncw_xc_layout(layout): # for NCWxc in_n, in_c, in_w, in_cc = data.shape if output_shape is None: output_shape = [in_n, in_c, size[0], in_cc] else: raise ValueError("%s layout is not supported." % layout) if isinstance(size, tuple): size = list(size) for i in range(1): if isinstance(size[i], int): size[i] = tvm.tir.IntImm("int32", size[i]) def compute_func(*indices): return _resize_1d( indices, data, roi, in_w, size[0], method=method, layout=layout, coordinate_transformation_mode=coordinate_transformation_mode, rounding_method=rounding_method, alpha=bicubic_alpha, exclude_outside=bicubic_exclude, extrapolation_value=extrapolation_value, out_dtype=out_dtype, ) return te.compute(output_shape, compute_func, name="resize", tag=tag.INJECTIVE) def _resize_2d( indices, data, roi, image_height, image_width, target_height, target_width, boxes=None, box_indices=None, method=None, extrapolation_value=0.0, layout="NCHW", coordinate_transformation_mode="align_corners", rounding_method="", alpha=-0.5, exclude_outside=0, out_dtype=None, ): """Perform resize operation on the data with selected method and options. Parameters ---------- indices : tuple The indices of input data data : tvm.te.Tensor inputs is a 4-D tensor with shape [batch, channel, in_height, in_width] or [batch, in_height, in_width, channel] roi: Tuple of Float or Expr The region of interest for cropping the input image. Expected to be of size 4, and format [start_h, start_w, end_h, end_w]. Only used if coordinate_transformation_mode is tf_crop_and_resize. image_height : integer Input image height image_width : integer Input image width target_height : integer The target resized image height target_width : integer The target resized image width boxes : tvm.te.Tensor, optional A 2-D tensor of shape [num_boxes, 4]. Each row of the tensor specifies the coordinates of a box. method: string, optional method of interpolation ("nearest", "linear", "bicubic") box_indices : tvm.te.Tensor, optional A 1-D tensor of shape [num_boxes], box_indices[i] specifies the data that the i-th box refers to. extrapolation_value: float, optional Value used for extrapolation, when applicable. layout: string, optional "NCHW", "NHWC", or "NCHWc". coordinate_transformation_mode : string, optional Describes how to transform the coordinate in the resized tensor to the coordinate in the original tensor. [half_pixel, align_corners, asymmetric, pytorch_half_pixel, tf_half_pixel_for_nn, and tf_crop_and_resize]. rounding_method: string, optional indicates how to find the "nearest" pixel in nearest_neighbor method [round, floor, ceil] alpha: float, optional Bicubic spline coefficient exclude_outside: bool, optional: Exclude values outside the image fdor bicubic interpolation out_dtype: string, optional Type to return. If left None will be same as input type. Returns ------- output : out_dtype The computed result with type out_dtype """ def _cast_output(value, data_dtype="float32", out_dtype=None): if out_dtype: dtype = out_dtype else: dtype = data_dtype return value.astype(dtype) height_use_int_div = False width_use_int_div = False if method == "nearest_neighbor" and coordinate_transformation_mode == "asymmetric": height_use_int_div = can_convert_multiply_to_intdiv(image_height, target_height) width_use_int_div = can_convert_multiply_to_intdiv(image_width, target_width) n, c, y, x, cc, inum, ic = get_2d_indices(indices, layout) box_idx = box_indices(n) if box_indices is not None else n if boxes is not None: y1, x1 = boxes(n, 0), boxes(n, 1) y2, x2 = boxes(n, 2), boxes(n, 3) in_h = (image_height - 1) * (y2 - y1) in_w = (image_width - 1) * (x2 - x1) h_scale = in_h.astype("float") / (target_height - 1) w_scale = in_w.astype("float") / (target_width - 1) in_y = y1 * (image_height - 1) + h_scale * y in_x = x1 * (image_width - 1) + w_scale * x else: in_x = get_inx( x, image_width, target_width, coordinate_transformation_mode, roi[1], roi[3], width_use_int_div, ) in_y = get_inx( y, image_height, target_height, coordinate_transformation_mode, roi[0], roi[2], height_use_int_div, ) if method == "nearest_neighbor": if rounding_method == "": if coordinate_transformation_mode == "align_corners": rounding_method = "round" else: rounding_method = "floor" closest_x_index = get_closest_index(in_x, rounding_method, boxes, width_use_int_div) closest_y_index = get_closest_index(in_y, rounding_method, boxes, height_use_int_div) value = get_2d_pixel( data, layout, image_height, image_width, box_idx, c, closest_y_index, closest_x_index, cc, inum, ic, ) elif method == "linear": y_int = te.floor(in_y).astype("int32") x_int = te.floor(in_x).astype("int32") y_lerp = in_y - y_int x_lerp = in_x - x_int p = [[0 for i in range(2)] for j in range(2)] for j in range(2): for i in range(2): p[j][i] = get_2d_pixel( data, layout, image_height, image_width, box_idx, c, y_int + j, x_int + i, cc, inum, ic, ) top = _lerp(*p[0], x_lerp) bottom = _lerp(*p[1], x_lerp) value = _lerp(top, bottom, y_lerp) elif method == "cubic": xint = te.floor(in_x).astype("int32") xfract = in_x - te.floor(in_x) yint = te.floor(in_y).astype("int32") yfract = in_y - te.floor(in_y) # Get the surrounding values p = [[0 for i in range(4)] for j in range(4)] for j in range(4): for i in range(4): p[j][i] = get_2d_pixel( data, layout, image_height, image_width, box_idx, c, yint + j - 1, xint + i - 1, cc, inum, ic, ) wx = _cubic_spline_weights(xfract, alpha) wy = _cubic_spline_weights(yfract, alpha) if exclude_outside: for i in range(4): wx[i] = te.if_then_else( te.any(xint - 1 + i < 0, xint + i > image_width), 0.0, wx[i] ) wy[i] = te.if_then_else( te.any(yint - 1 + i < 0, yint + i > image_height), 0.0, wy[i] ) sum_wx = sum(wx) sum_wy = sum(wy) wx = [w / sum_wx for w in wx] wy = [w / sum_wy for w in wy] col0 = _cubic_kernel(p[0], wx) col1 = _cubic_kernel(p[1], wx) col2 = _cubic_kernel(p[2], wx) col3 = _cubic_kernel(p[3], wx) value = _cubic_kernel([col0, col1, col2, col3], wy) else: raise ValueError("Unknown resize method:", method) if coordinate_transformation_mode == "tf_crop_and_resize": out = tvm.tir.if_then_else( in_y < 0, extrapolation_value, tvm.tir.if_then_else(in_y > image_height - 1, extrapolation_value, value), ) # use extrapolation_value if in_x is out of boundary value = tvm.tir.if_then_else( in_x < 0, extrapolation_value, tvm.tir.if_then_else(in_x > image_width - 1, extrapolation_value, out), ) return _cast_output(value, data.dtype, out_dtype=out_dtype) def resize2d( data, roi, size, layout="NCHW", method="linear", coordinate_transformation_mode="half_pixel", rounding_method="", bicubic_alpha=-0.5, bicubic_exclude=0, extrapolation_value=0.0, out_dtype=None, output_shape=None, ): """Perform resize operation on the data. Parameters ---------- data : tvm.te.Tensor inputs is a 4-D tensor with shape [batch, channel, in_height, in_width] or [batch, in_height, in_width, channel] roi: Tuple of Float or Expr The region of interest for cropping the input image. Expected to be of size 4, and format [start_h, start_w, end_h, end_w]. Only used if coordinate_transformation_mode is tf_crop_and_resize. size: Tuple Output resolution scale to layout: string, optional "NCHW", "NHWC", or "NCHWc". coordinate_transformation_mode: string, optional Describes how to transform the coordinate in the resized tensor to the coordinate in the original tensor. Refer to the ONNX Resize operator specification for details. Available options are "half_pixel", "align_corners" and "asymmetric". method: string, optional method of interpolation ("nearest", "linear", "bicubic") coordinate_transformation_mode : string, optional Describes how to transform the coordinate in the resized tensor to the coordinate in the original tensor. [half_pixel, align_corners, asymmetric, pytorch_half_pixel, tf_half_pixel_for_nn, and tf_crop_and_resize]. rounding_method: Method for rounding coordinate locations bicubic_alpha: float, optional Bicubic spline coefficient bicubic_exclude: bool, optional: Exclude values outside the image fdor bicubic interpolation extrapolation_value: float, optional Value used for extrapolation, when applicable. out_dtype: string, optional Type to return. If left None will be same as input type. output_shape: tvm.tir.container.Array, optional Shape to return. If left None will be inferred (If shape is determined dynamically, pass out_dtype.shape as output_shape) Returns ------- output : tvm.te.Tensor 4-D with shape [batch, channel, in_height*scale, in_width*scale] or [batch, in_height*scale, in_width*scale, channel] or 5-D with shape [batch, channel-major, in_height*scale, in_width*scale, channel-minor] """ method = method.lower() if layout == "NHWC": in_n, in_h, in_w, in_c = data.shape if output_shape is None: output_shape = [in_n, size[0], size[1], in_c] elif layout == "NCHW": in_n, in_c, in_h, in_w = data.shape if output_shape is None: output_shape = [in_n, in_c, size[0], size[1]] elif nchw_pack_layout(layout): # for NCHWinic in_n, in_c, in_h, in_w, in_inum, in_ic = data.shape if output_shape is None: output_shape = [in_n, in_c, size[0], size[1], in_inum, in_ic] elif nchw_xc_layout(layout): # for NCHWxc in_n, in_c, in_h, in_w, in_cc = data.shape if output_shape is None: output_shape = [in_n, in_c, size[0], size[1], in_cc] else: raise ValueError("%s layout is not supported." % layout) if isinstance(size, tuple): size = list(size) for i in range(2): if isinstance(size[i], int): size[i] = tvm.tir.IntImm("int32", size[i]) def compute_func(*indices): return _resize_2d( indices, data, roi, in_h, in_w, size[0], size[1], method=method, layout=layout, coordinate_transformation_mode=coordinate_transformation_mode, rounding_method=rounding_method, alpha=bicubic_alpha, exclude_outside=bicubic_exclude, extrapolation_value=extrapolation_value, out_dtype=out_dtype, ) return te.compute(output_shape, compute_func, name="resize", tag=tag.INJECTIVE) def crop_and_resize( data, boxes, box_indices, crop_size, layout="NCHW", method="bilinear", extrapolation_value=None, out_dtype=None, ): """Perform crop and resize operation on the data. Parameters ---------- data : tvm.te.Tensor inputs is a 4-D tensor with shape [batch, channel, in_height, in_width] or [batch, in_height, in_width, channel] boxes : tvm.te.Tensor A 2-D tensor of shape [num_boxes, 4]. Each row of the tensor specifies the coordinates of a box. box_indices : tvm.te.Tensor A 1-D tensor of shape [num_boxes], box_indices[i] specifies the data that the i-th box refers to. crop_size : Tuple The target size of each box. layout : string, optional "NCHW", "NHWC" method : {"bilinear", "nearest_neighbor"} Method to be used for resizing. extrapolation_value: float, optional Value used for extrapolation, when applicable. out_dtype : string, optional Type to return. If left None will be same as input type. Returns ------- output : tvm.te.Tensor 4-D with shape [num_boxes, channel, crop_height, crop_width] or [num_boxes, crop_height, crop_width, channel] """ method = method.lower() target_h = crop_size[0] target_w = crop_size[1] if layout == "NHWC": output_shape = [box_indices.shape[0], crop_size[0], crop_size[1], data.shape[3]] image_h = data.shape[1].astype("int32") image_w = data.shape[2].astype("int32") elif layout == "NCHW": output_shape = [box_indices.shape[0], data.shape[1], crop_size[0], crop_size[1]] image_h = data.shape[2].astype("int32") image_w = data.shape[3].astype("int32") elif layout.startswith("NCHW"): # for NCHWxc output_shape = [ box_indices.shape[0], data.shape[1], crop_size[0], crop_size[1], data.shape[4], ] image_h = data.shape[2].astype("int32") image_w = data.shape[3].astype("int32") else: raise ValueError("%s layout is not supported." % layout) if method == "bilinear": method = "linear" def compute_func(*indices): return _resize_2d( indices, data, [0.0] * 4, image_h, image_w, target_h, target_w, boxes, box_indices, method=method, extrapolation_value=extrapolation_value, layout=layout, coordinate_transformation_mode="tf_crop_and_resize", out_dtype=out_dtype, ) return te.compute(output_shape, compute_func, name="crop_and_resize", tag=tag.INJECTIVE) def _resize_3d( indices, data, roi, image_depth, image_height, image_width, target_depth, target_height, target_width, boxes=None, box_indices=None, method=None, extrapolation_value=0.0, layout="NCHW", coordinate_transformation_mode="align_corners", rounding_method="", alpha=-0.5, exclude_outside=0, out_dtype=None, ): """Perform resize operation on the data with selected method and options. Parameters ---------- indices : tuple The indices of input data data : tvm.te.Tensor inputs is a 4-D tensor with shape [batch, channel, in_height, in_width] or [batch, in_height, in_width, channel] roi: Tuple of Float or Expr The region of interest for cropping the input image. Expected to be of size 6, and format [start_d, start_h, start_w, end_d, end_h, end_w]. Only used if coordinate_transformation_mode is tf_crop_and_resize. image_depth : integer Input image depth image_height : integer Input image height image_width : integer Input image width target_depth : integer The target resized image depth target_height : integer The target resized image height target_width : integer The target resized image width boxes : tvm.te.Tensor, optional A 2-D tensor of shape [num_boxes, 4]. Each row of the tensor specifies the coordinates of a box. box_indices : tvm.te.Tensor, optional A 1-D tensor of shape [num_boxes], box_indices[i] specifies the data that the i-th box refers to. method: string, optional method of interpolation ("nearest", "linear", "bicubic") extrapolation_value: float, optional Value used for extrapolation, when applicable. layout: string, optional "NCHW", "NHWC", or "NCHWc". coordinate_transformation_mode : string, optional Describes how to transform the coordinate in the resized tensor to the coordinate in the original tensor. [half_pixel, align_corners, asymmetric, pytorch_half_pixel, tf_half_pixel_for_nn, and tf_crop_and_resize]. rounding_method: string, optional indicates how to find the "nearest" pixel in nearest_neighbor method [round, floor, ceil] alpha: float, optional Bicubic spline coefficient exclude_oiutside: bool, optional: Exclude values outside the image fdor bicubic interpolation out_dtype: string, optional Type to return. If left None will be same as input type. Returns ------- output : out_dtype The computed result with type out_dtype """ def _cast_output(value, data_dtype="float32", out_dtype=None): if out_dtype: dtype = out_dtype else: dtype = data_dtype return value.astype(dtype) n, c, z, y, x, cc = get_3d_indices(indices, layout) box_idx = box_indices(n) if box_indices is not None else n if boxes is not None: # TODO(mbrookhart): Find an example of this raise NotImplementedError("resize1d with image boxes not yet implemented") in_z = get_inx(z, image_depth, target_depth, coordinate_transformation_mode, roi[2], roi[5]) in_y = get_inx(y, image_height, target_height, coordinate_transformation_mode, roi[1], roi[4]) in_x = get_inx(x, image_width, target_width, coordinate_transformation_mode, roi[0], roi[3]) if method == "nearest_neighbor": if rounding_method == "": if coordinate_transformation_mode == "align_corners": rounding_method = "round" else: rounding_method = "floor" closest_z_index = get_closest_index(in_z, rounding_method, boxes) closest_y_index = get_closest_index(in_y, rounding_method, boxes) closest_x_index = get_closest_index(in_x, rounding_method, boxes) value = get_3d_pixel( data, layout, image_depth, image_height, image_width, box_idx, c, closest_z_index, closest_y_index, closest_x_index, cc, ) elif method == "linear": z_int = te.floor(in_z).astype("int32") y_int = te.floor(in_y).astype("int32") x_int = te.floor(in_x).astype("int32") z_lerp = in_z - z_int y_lerp = in_y - y_int x_lerp = in_x - x_int p = [[[0 for i in range(2)] for j in range(2)] for k in range(2)] for k in range(2): for j in range(2): for i in range(2): p[k][j][i] = get_3d_pixel( data, layout, image_depth, image_height, image_width, box_idx, c, z_int + k, y_int + j, x_int + i, cc, ) l = [[0 for i in range(2)] for j in range(2)] for j in range(2): for i in range(2): l[j][i] = _lerp(*p[j][i], x_lerp) top = _lerp(*l[0], y_lerp) bottom = _lerp(*l[1], y_lerp) value = _lerp(top, bottom, z_lerp) elif method == "cubic": zint = te.floor(in_z).astype("int32") zfract = in_z - te.floor(in_z) yint = te.floor(in_y).astype("int32") yfract = in_y - te.floor(in_y) xint = te.floor(in_x).astype("int32") xfract = in_x - te.floor(in_x) # Get the surrounding values p = [[[0 for i in range(4)] for j in range(4)] for k in range(4)] for k in range(4): for j in range(4): for i in range(4): p[k][j][i] = get_3d_pixel( data, layout, image_depth, image_height, image_width, box_idx, c, zint + k - 1, yint + j - 1, xint + i - 1, cc, ) wz = _cubic_spline_weights(zfract, alpha) wy = _cubic_spline_weights(yfract, alpha) wx = _cubic_spline_weights(xfract, alpha) if exclude_outside: for i in range(4): wz[i] = te.if_then_else( te.any(xint - 1 + i < 0, xint + i > image_height), 0.0, wx[i] ) wy[i] = te.if_then_else( te.any(yint - 1 + i < 0, yint + i > image_height), 0.0, wy[i] ) wx[i] = te.if_then_else( te.any(xint - 1 + i < 0, xint + i > image_width), 0.0, wx[i] ) sum_wz = sum(wz) sum_wy = sum(wy) sum_wx = sum(wx) wz = [w / sum_wz for w in wz] wy = [w / sum_wy for w in wy] wx = [w / sum_wx for w in wx] l = [[0 for i in range(4)] for j in range(4)] for j in range(4): for i in range(4): l[j][i] = _cubic_kernel(p[j][i], wx) col0 = _cubic_kernel(l[0], wy) col1 = _cubic_kernel(l[1], wy) col2 = _cubic_kernel(l[2], wy) col3 = _cubic_kernel(l[3], wy) value = _cubic_kernel([col0, col1, col2, col3], wz) else: raise ValueError("Unknown resize method:", method) if coordinate_transformation_mode == "tf_crop_and_resize": out = tvm.tir.if_then_else( in_z < 0, extrapolation_value, tvm.tir.if_then_else(in_z > image_depth - 1, extrapolation_value, value), ) out = tvm.tir.if_then_else( in_y < 0, extrapolation_value, tvm.tir.if_then_else(in_y > image_height - 1, extrapolation_value, value), ) # use extrapolation_value if in_x is out of boundary value = tvm.tir.if_then_else( in_x < 0, extrapolation_value, tvm.tir.if_then_else(in_x > image_width - 1, extrapolation_value, out), ) return _cast_output(value, data.dtype, out_dtype=out_dtype) def resize3d( data, roi, size, layout="NCDHW", method="linear", coordinate_transformation_mode="half_pixel", rounding_method="", bicubic_alpha=-0.5, bicubic_exclude=0, extrapolation_value=0.0, out_dtype=None, output_shape=None, ): """Perform resize operation on the data. Parameters ---------- data : tvm.te.Tensor inputs is a 5-D tensor with shape [batch, channel, in_depth, in_height, in_width] or [batch, in_depth, in_height, in_width, channel] roi: Tuple of Float or Expr The region of interest for cropping the input image. Expected to be of size 6, and format [start_d, start_h, start_w, end_d, end_h, end_w]. Only used if coordinate_transformation_mode is tf_crop_and_resize. size: Tuple Output resolution scale to layout: string, optional "NCDHW", "NDHWC", or "NCDHWc". method: string, optional method of interpolation ("nearest", "linear", "bicubic") coordinate_transformation_mode : string, optional Describes how to transform the coordinate in the resized tensor to the coordinate in the original tensor. [half_pixel, align_corners, asymmetric, pytorch_half_pixel, tf_half_pixel_for_nn, and tf_crop_and_resize]. rounding_method: Method for rounding coordinate locations bicubic_alpha: float, optional Bicubic spline coefficient bicubic_exclude: bool, optional: Exclude values outside the image fdor bicubic interpolation extrapolation_value: float, optional Value used for extrapolation, when applicable. out_dtype: string, optional Type to return. If left None will be same as input type. output_shape: tvm.tir.container.Array, optional Shape to return. If left None will be inferred (If shape is determined dynamically, pass out_dtype.shape as output_shape) Returns ------- output : tvm.te.Tensor 4-D with shape [batch, channel, in_depth*scale, in_height*scale, in_width*scale] or [batch, in_depth*scale, in_height*scale, in_width*scale, channel] or 5-D with shape [batch, channel-major, in_depth*scale, in_height*scale, in_width*scale, channel-minor] """ method = method.lower() if layout == "NDHWC": in_n, in_d, in_h, in_w, in_c = data.shape output_shape = [in_n, size[0], size[1], size[2], in_c] elif layout == "NCDHW": in_n, in_c, in_d, in_h, in_w = data.shape output_shape = [in_n, in_c, size[0], size[1], size[2]] # Otherwise layout must be NCHWxc else: in_n, in_c, in_d, in_h, in_w, in_cc = data.shape output_shape = [in_n, in_c, size[0], size[1], size[2], in_cc] if isinstance(size, tuple): size = list(size) for i in range(3): if isinstance(size[i], int): size[i] = tvm.tir.IntImm("int32", size[i]) def compute_func(*indices): return _resize_3d( indices, data, roi, in_d, in_h, in_w, size[0], size[1], size[2], method=method, layout=layout, coordinate_transformation_mode=coordinate_transformation_mode, rounding_method=rounding_method, alpha=bicubic_alpha, exclude_outside=bicubic_exclude, extrapolation_value=extrapolation_value, out_dtype=out_dtype, ) return te.compute(output_shape, compute_func, name="resize", tag=tag.INJECTIVE)
https://github.com/zk-ml/tachikoma
python/tvm/topi/intel_graphics/__init__.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=redefined-builtin, wildcard-import """Intel Gen9 GPU specific declaration and schedules.""" from __future__ import absolute_import as _abs from .conv2d import * from . import conv2d_alter_op from .depthwise_conv2d import *
https://github.com/zk-ml/tachikoma
python/tvm/topi/intel_graphics/conv2d.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=invalid-name,unused-variable,unused-argument,no-else-return, too-many-arguments, too-many-locals, too-many-statements, no-member, too-many-branches, too-many-boolean-expressions """conv2d schedule on Intel Graphics""" from __future__ import absolute_import as _abs import tvm from tvm import te from tvm import autotvm from tvm.autotvm.task.space import SplitEntity, OtherOptionEntity from .. import nn from .. import utils from ..utils import simplify, get_const_tuple, traverse_inline def _get_default_config(cfg, data, kernel, strides, padding, out_dtype, is_depthwise=False): if is_depthwise: raise RuntimeError("Depthwise not supported for intel graphics.") batch_size, in_channel, height, width = get_const_tuple(data.shape) out_channel, _, hkernel, _ = get_const_tuple(kernel.shape) HSTR, _ = strides ic_bn = 1 oc_bn, oc_bn_upper = 16, 16 for i in range(oc_bn_upper, 0, -1): if out_channel % i == 0: oc_bn = i break if HSTR == 2: if out_channel + hkernel == 515: block_oh = 4 block_ow = 4 else: block_oh = 4 block_ow = 5 elif hkernel == 3: if out_channel == 512: block_oh = 2 block_ow = 7 else: block_oh = 2 block_ow = 14 else: block_oh = 1 block_ow = 16 cfg["tile_ic"] = SplitEntity([in_channel // ic_bn, ic_bn]) cfg["tile_oc"] = SplitEntity([out_channel // oc_bn, oc_bn]) cfg["block_oh"] = OtherOptionEntity(block_oh) cfg["block_ow"] = OtherOptionEntity(block_ow) def _create_schedule_template(cfg, dshape, kshape, strides, padding, dilation): """Create schedule configuration from input arguments""" n, ic, h, w = dshape oc, _, kh, kw = kshape pt, pl, pb, pr = nn.get_pad_tuple(padding, (kh, kw)) sh, sw = strides if isinstance(strides, (tuple, list)) else (strides, strides) oh = (h - kh + pt + pb) // sh + 1 ow = (w - kw + pl + pr) // sw + 1 ic_bn_upper = 32 oc_bn_upper = 64 oc_bn_lower = min(oc, 8) ic_bn_candidates, oc_bn_candidates = [], [] for i in range(1, ic + 1): if ic % i == 0 and i <= ic_bn_upper: ic_bn_candidates.append(i) if not ic_bn_candidates: ic_bn_candidates.append(1) ic_bn_candidates.append(ic) for i in range(1, oc + 1): if oc % i == 0 and oc_bn_lower <= i <= oc_bn_upper: oc_bn_candidates.append(i) if not oc_bn_candidates: oc_bn_candidates.append(1) oc_bn_candidates.append(oc) blk_candidates_low_limits = 5 blk_oh_list, blk_ow_list = [], [] for i, j in zip(range(oh, 0, -1), range(ow, 0, -1)): if i <= 16 and oh % i == 0: blk_oh_list.append(i) if j <= 16 and ow % j == 0: blk_ow_list.append(j) if len(blk_oh_list) < blk_candidates_low_limits: for i in range(2, oh): if i not in blk_oh_list: blk_oh_list.append(i) if len(blk_oh_list) >= 5: break if len(blk_ow_list) < blk_candidates_low_limits: for i in range(min(ow - 1, 16), 1, -1): if i not in blk_ow_list: blk_ow_list.append(i) if len(blk_ow_list) >= 5: break # Create schedule config cfg.define_knob("tile_ic", ic_bn_candidates) cfg.define_knob("tile_oc", oc_bn_candidates) cfg.define_knob("block_oh", blk_oh_list) cfg.define_knob("block_ow", blk_ow_list) ##### SCHEDULE UTILITIES ##### def tile_and_bind3d(s, tensor, z, y, x, z_factor=2, y_factor=None, x_factor=None): """tile and bind 3d""" y_factor = y_factor or z_factor x_factor = x_factor or y_factor zo, zi = s[tensor].split(z, z_factor) yo, yi = s[tensor].split(y, y_factor) xo, xi = s[tensor].split(x, x_factor) s[tensor].reorder(zo, yo, xo, zi, yi, xi) thread_z = te.thread_axis((0, z_factor), "threadIdx.z") thread_y = te.thread_axis((0, y_factor), "threadIdx.y") thread_x = te.thread_axis((0, x_factor), "threadIdx.x") s[tensor].bind(zo, te.thread_axis("blockIdx.z")) s[tensor].bind(zi, thread_z) s[tensor].bind(yo, te.thread_axis("blockIdx.y")) s[tensor].bind(yi, thread_y) s[tensor].bind(xo, te.thread_axis("blockIdx.x")) s[tensor].bind(xi, thread_x) return xi, thread_z, thread_y, thread_x def _pack_data(data, kernel, ic_bn, oc_bn): n, _, ih, iw = get_const_tuple(data.shape) oc, ic, kh, kw = get_const_tuple(kernel.shape) ic_chunk = ic // ic_bn oc_chunk = oc // oc_bn data = te.compute( (n, ic_chunk, ih, iw, ic_bn), lambda bs, c, h, w, vc: data[bs, c * ic_bn + vc, h, w], name="data_vec", ) kernel = te.compute( (oc_chunk, ic_chunk, kh, kw, ic_bn, oc_bn), lambda occ, icc, k_h, k_w, icb, ocb: kernel[occ * oc_bn + ocb, icc * ic_bn + icb, k_h, k_w], name="kernel_vec", ) return data, kernel @autotvm.register_topi_compute("conv2d_NCHWc.intel_graphics") def conv2d_NCHWc( cfg, data, kernel, strides, padding, dilation, layout, out_layout, out_dtype="float32" ): """Conv2D operator for Intel Graphics backend. Parameters ---------- data : tvm.te.Tensor 4-D with shape [batch, in_channel, in_height, in_width] kernel : tvm.te.Tensor 5-D with shape [num_filter, in_channel, filter_height, filter_width, nnum_filter_vec] stride : int or a list/tuple of two ints stride size, or [stride_height, stride_width] padding : int or a list/tuple of two ints padding size, or [pad_height, pad_width] layout : str layout of data Returns ------- output : tvm.te.Tensor 4-D with shape [batch, out_channel, out_height, out_width] """ if len(data.shape) == 5: batch, ic_chunk, ih, iw, ic_bn = get_const_tuple(data.shape) oc_chunk, _, kernel_height, kernel_width, _, oc_bn = get_const_tuple(kernel.shape) in_channel = ic_chunk * ic_bn num_filter = oc_chunk * oc_bn else: batch, in_channel, ih, iw = get_const_tuple(data.shape) num_filter, _, kernel_height, kernel_width = get_const_tuple(kernel.shape) dh, dw = dilation if isinstance(dilation, (tuple, list)) else (dilation, dilation) pad_top, pad_left, pad_down, pad_right = nn.get_pad_tuple( padding, (kernel_height, kernel_width) ) assert (dh, dw) == (1, 1), "Does not support dilation" if isinstance(strides, (tuple, list)): stride_h, stride_w = strides else: stride_h, stride_w = strides, strides data_shape = (batch, in_channel, ih, iw) kernel_shape = (num_filter, in_channel, kernel_height, kernel_width) _create_schedule_template(cfg, data_shape, kernel_shape, strides, padding, dilation) if cfg.is_fallback: _get_default_config( cfg, te.placeholder((batch, in_channel, ih, iw), dtype=data.dtype), te.placeholder( (num_filter, in_channel, kernel_height, kernel_width), dtype=kernel.dtype ), strides, padding, out_dtype, ) ic_bn = cfg["tile_ic"].val if hasattr(cfg["tile_ic"], "val") else cfg["tile_ic"].size[-1] oc_bn = cfg["tile_oc"].val if hasattr(cfg["tile_oc"], "val") else cfg["tile_oc"].size[-1] # Pack data if raw 4-D data is provided. if len(data.shape) == 4: data, kernel = _pack_data(data, kernel, ic_bn, oc_bn) out_channel = num_filter out_height = simplify((ih - kernel_height + pad_top + pad_down) // stride_h + 1) out_width = simplify((iw - kernel_width + pad_left + pad_right) // stride_w + 1) oshape = (batch, out_channel // oc_bn, out_height, out_width, oc_bn) rc = te.reduce_axis((0, in_channel), name="rc") ry = te.reduce_axis((0, kernel_height), name="ry") rx = te.reduce_axis((0, kernel_width), name="rx") block_h = cfg["block_oh"].val block_w = cfg["block_ow"].val c_h = out_height c_w = out_width if out_height % block_h != 0: c_h = (out_height // block_h + 1) * block_h if out_width % block_w != 0: c_w = (out_width // block_w + 1) * block_w cshape = (batch, out_channel // oc_bn, c_h, c_w, oc_bn) pad_before = [0, 0, pad_top, pad_left, 0] pad_after = [0, 0, pad_down + c_h - out_height, pad_right + c_w - out_width, 0] DOPAD = ( pad_top != 0 or pad_left != 0 or pad_down + c_h - out_height != 0 or pad_right + c_w - out_width != 0 ) DOUNPACK = c_h - out_height != 0 or c_w - out_width != 0 if DOPAD: temp = nn.pad(data, pad_before, pad_after, name="pad_temp") else: temp = data conv = te.compute( cshape, lambda nn, ff, yy, xx, ff_v: te.sum( temp[nn, rc // ic_bn, yy * stride_h + ry, xx * stride_w + rx, rc % ic_bn].astype( out_dtype ) * kernel[ff, rc // ic_bn, ry, rx, rc % ic_bn, ff_v].astype(out_dtype), axis=[rc, ry, rx], ), tag="conv2d_NCHWc", name="conv2d_NCHWc", ) if DOUNPACK: output = te.compute( oshape, lambda nn, ff, yy, xx, ff_v: conv[nn][ff][yy][xx][ff_v], name="output_unpack", tag="conv2d_NCHWc_unpack", ) else: output = conv return output @autotvm.register_topi_schedule("conv2d_NCHWc.intel_graphics") def schedule_conv2d_NCHWc(cfg, outs): """Schedule for conv2d_nchw for Intel Graphics Parameters ---------- outs: Array of Tensor The computation graph description of conv2d_nchw in the format of an array of tensors. Returns ------- s: Schedule The computation schedule for conv2d_nchw. """ outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs s = te.create_schedule([x.op for x in outs]) def _callback(op): """inline all one-to-one-mapping operators except the last stage (output)""" if "conv2d_NCHWc" in op.tag: _schedule_cl_spatialpack_NCHWc(cfg, s, op) traverse_inline(s, outs[0].op, _callback) return s def _schedule_cl_spatialpack_NCHWc(cfg, s, op): output = op.output(0) if op.name == "conv2d_NCHWc": temp = op.input_tensors[0] kernel = op.input_tensors[1] temp_W = s.cache_read(temp, "warp", [output]) conv_L = s.cache_write(output, "local") if output.op in s.outputs: conv = output else: s[output].compute_inline() conv = s.outputs[0] SCHEDULE_OUTPUT = False else: # conv2d_NCHWc_unpack conv = op.input_tensors[0] temp = s[conv].op.input_tensors[0] kernel = s[conv].op.input_tensors[1] temp_W = s.cache_read(temp, "warp", [conv]) conv_L = s.cache_write(conv, "local") SCHEDULE_OUTPUT = True kernel_L = s.cache_read(kernel, "local", [conv_L]) if temp.name == "pad_temp": data = temp.op.input_tensors[0] # TODO(@Laurawly): Do we need to schedule pad op here? else: data = temp if autotvm.GLOBAL_SCOPE.in_tuning: # only in autotuning, input data of conv2d_NCHWc will be 4-D. # skip this part during tuning to make records accurate. # this part will be folded during Relay fold_constant pass. s[data].pragma(s[data].op.axis[0], "debug_skip_region") s[kernel].pragma(s[kernel].op.axis[0], "debug_skip_region") elif isinstance(kernel.op, tvm.te.ComputeOp) and kernel.name == "kernel_vec": # data and kernel are not pre-computed, schedule layout transform here. # TODO(@Laurawly): Add schedule for data and kernel pack pass OUTPUT_BLOCK_HEIGHT = cfg["block_oh"].val OUTPUT_BLOCK_WIDTH = cfg["block_ow"].val # schedule conv z_factor = 1 y_factor = 1 x_factor = 16 thread_z = te.thread_axis((0, z_factor), "threadIdx.z") thread_y = te.thread_axis((0, y_factor), "threadIdx.y") thread_x = te.thread_axis((0, x_factor), "threadIdx.x") _, co, oh, ow, vc = s[conv].op.axis ooh, ioh = s[conv].split(oh, factor=OUTPUT_BLOCK_HEIGHT) oow, iow = s[conv].split(ow, factor=OUTPUT_BLOCK_WIDTH) s[conv].reorder(_, co, ooh, oow, vc, ioh, iow) coo, coi = s[conv].split(co, nparts=1) ooho, oohi = s[conv].split(ooh, factor=z_factor) oowo, oowi = s[conv].split(oow, factor=y_factor) vco, vci = s[conv].split(vc, factor=x_factor) s[conv].reorder(_, coo, vco, ooho, oowo, coi, oohi, oowi, vci, ioh, iow) s[conv].bind(oohi, thread_z) s[conv].bind(oowi, thread_y) s[conv].bind(vci, thread_x) s[conv].bind(ooho, te.thread_axis("blockIdx.z")) s[conv].bind(oowo, te.thread_axis("blockIdx.y")) s[conv].bind(coi, te.thread_axis("blockIdx.x")) # schedule conv_L s[conv_L].compute_at(s[conv], vci) i, oc, h, w, vc = s[conv_L].op.axis rc, ry, rx = s[conv_L].op.reduce_axis s[conv_L].reorder(i, oc, rc, ry, rx, vc, h, w) s[temp_W].compute_at(s[conv_L], rc) if kernel.shape[3].value != 7: s[conv_L].unroll(ry) s[conv_L].unroll(rx) # schedule temp if temp.op.name == "pad_temp": _, ci, h, w, vci = s[temp].op.axis tile_and_bind3d(s, temp, ci, h, w, 1, 16, 16) # schedule temp_W _, ci, h, w, vci = s[temp_W].op.axis zo, zi = s[temp_W].split(vci, 1) yo, yi = s[temp_W].split(h, 1) xo, xi = s[temp_W].split(w, 16) s[temp_W].reorder(zo, yo, xo, zi, yi, xi) s[temp_W].bind(zi, thread_z) s[temp_W].bind(yi, thread_y) s[temp_W].bind(xi, thread_x) s[temp_W].storage_align(s[temp_W].op.axis[2], 16, 0) # schedule kernel_L if OUTPUT_BLOCK_HEIGHT == 2 and OUTPUT_BLOCK_WIDTH == 14: s[kernel_L].compute_at(s[conv_L], ry) else: s[kernel_L].compute_at(s[conv_L], rx) # schedule output if SCHEDULE_OUTPUT: if output.op in s.outputs: out = output else: s[output].compute_inline() out = s.outputs[0] _, co, h, w, vc = s[out].op.axis tile_and_bind3d(s, out, w, h, vc, 4, 8, 8) def conv2d_nchw(data, kernel, stride, padding, dilation, out_dtype="float32"): """Conv2D operator for Intel Graphics backend. Parameters ---------- data : tvm.te.Tensor 4-D with shape [batch, in_channel, in_height, in_width] kernel : tvm.te.Tensor 4-D with shape [num_filter, in_channel, filter_height, filter_width] stride : int or a list/tuple of two ints stride size, or [stride_height, stride_width] padding : int or a list/tuple of two ints padding size, or [pad_height, pad_width] Returns ------- output : tvm.te.Tensor 4-D with shape [batch, out_channel, out_height, out_width] """ assert data.shape[0].value == 1, "only support batch size=1 convolution on intel gpu" assert data.dtype == kernel.dtype, "Do not support inputs with different data types now." return _decl_cl_spatialpack(data, kernel, stride, padding, out_dtype) def schedule_conv2d_nchw(outs): """Schedule for conv2d_nchw for Intel Graphics Parameters ---------- outs: Array of Tensor The computation graph description of conv2d_nchw in the format of an array of tensors. Returns ------- s: Schedule The computation schedule for conv2d_nchw. """ outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs s = te.create_schedule([x.op for x in outs]) def _callback(op): """inline all one-to-one-mapping operators except the last stage (output)""" if "conv2d" in op.tag: _schedule_cl_spatialpack(s, op) traverse_inline(s, outs[0].op, _callback) return s def _decl_cl_spatialpack(data, kernel, stride, padding, out_dtype="float16"): batch, in_channel, in_height, in_width = [utils.get_const_int(x) for x in data.shape] num_filter, channel, kernel_h, kernel_w = [utils.get_const_int(x) for x in kernel.shape] pad_top, pad_left, pad_down, pad_right = nn.get_pad_tuple(padding, (kernel_h, kernel_w)) if isinstance(stride, (tuple, list)): stride_h, stride_w = stride else: stride_h, stride_w = stride, stride out_channel = num_filter out_height = simplify((in_height - kernel_h + pad_top + pad_down) // stride_h + 1) out_width = simplify((in_width - kernel_w + pad_left + pad_right) // stride_w + 1) oshape = (batch, out_channel, out_height, out_width) rc = te.reduce_axis((0, in_channel), name="rc") ry = te.reduce_axis((0, kernel_h), name="ry") rx = te.reduce_axis((0, kernel_w), name="rx") if stride_h == 2: if num_filter + kernel_h == 515: block_h = 4 block_w = 4 else: block_h = 4 block_w = 5 elif kernel_h == 3: if num_filter == 512: block_h = 2 block_w = 7 else: block_h = 2 block_w = 14 elif kernel_h == 7 and padding == 3 and stride == 1: block_h = 3 block_w = 4 else: block_h = 1 block_w = 16 attrs = {"block_h": block_h, "block_w": block_w} c_h = out_height c_w = out_width if out_height % block_h != 0: c_h = (out_height // block_h + 1) * block_h if out_width % block_w != 0: c_w = (out_width // block_w + 1) * block_w pad_before = [0, 0, pad_top, pad_left] pad_after = [0, 0, pad_down + c_h - block_h, pad_right + c_w - block_w] temp = nn.pad(data, pad_before, pad_after, name="pad_temp") nv = 16 if num_filter % nv != 0: num_filter = (num_filter // nv + 1) * nv out_channel = num_filter cshape = (batch, out_channel // nv, c_h, c_w, nv) kvshape = (num_filter // nv, channel, kernel_h, kernel_w, nv) kernel_vec = te.compute( kvshape, lambda co, ci, kh, kw, vc: kernel[co * nv + vc][ci][kh][kw], name="kernel_vec" ) conv = te.compute( cshape, lambda nn, ff, yy, xx, vc: te.sum( temp[nn, rc, yy * stride_h + ry, xx * stride_w + rx].astype(out_dtype) * kernel_vec[ff, rc, ry, rx, vc].astype(out_dtype), axis=[rc, ry, rx], ), name="conv", attrs=attrs, ) output = te.compute( oshape, lambda nn, ff, yy, xx: conv[nn][ff // nv][yy][xx][ff % nv], name="output_unpack", tag="conv2d", ) return output def _schedule_cl_spatialpack(s, op): output = op.output(0) _, _, out_height, out_width = [utils.get_const_int(x) for x in output.shape] conv = op.input_tensors[0] temp = s[conv].op.input_tensors[0] kernel_vec = s[conv].op.input_tensors[1] kernel = s[kernel_vec].op.input_tensors[0] temp_W = s.cache_read(temp, "shared", [conv]) conv_L = s.cache_write(conv, "local") kernel_L = s.cache_read(kernel_vec, "local", [conv_L]) _, in_channel, temp_h, temp_w = [utils.get_const_int(x) for x in temp.shape] attrs = s[conv].op.attrs OUTPUT_BLOCK_HEIGHT = attrs["block_h"] OUTPUT_BLOCK_WIDTH = attrs["block_w"] # schedule conv z_factor = 1 y_factor = 1 x_factor = 16 thread_z = te.thread_axis((0, z_factor), "threadIdx.z") thread_y = te.thread_axis((0, y_factor), "threadIdx.y") thread_x = te.thread_axis((0, x_factor), "threadIdx.x") _, co, oh, ow, vc = s[conv].op.axis ooh, ioh = s[conv].split(oh, factor=OUTPUT_BLOCK_HEIGHT) oow, iow = s[conv].split(ow, factor=OUTPUT_BLOCK_WIDTH) s[conv].reorder(_, co, ooh, oow, vc, ioh, iow) coo, coi = s[conv].split(co, nparts=1) ooho, oohi = s[conv].split(ooh, factor=z_factor) oowo, oowi = s[conv].split(oow, factor=y_factor) vco, vci = s[conv].split(vc, factor=x_factor) s[conv].reorder(_, coo, vco, ooho, oowo, coi, oohi, oowi, vci, ioh, iow) s[conv].bind(oohi, thread_z) s[conv].bind(oowi, thread_y) s[conv].bind(vci, thread_x) s[conv].bind(ooho, te.thread_axis("blockIdx.z")) s[conv].bind(oowo, te.thread_axis("blockIdx.y")) s[conv].bind(coi, te.thread_axis("blockIdx.x")) # schedule conv_L s[conv_L].compute_at(s[conv], vci) i, oc, h, w, vc = s[conv_L].op.axis rc, ry, rx = s[conv_L].op.reduce_axis s[conv_L].reorder(i, oc, rc, ry, rx, vc, h, w) s[temp_W].compute_at(s[conv_L], rc) if kernel.shape[3].value != 7: s[conv_L].unroll(ry) s[conv_L].unroll(rx) # schedule temp _, ci, h, w = s[temp].op.axis tile_and_bind3d(s, temp, ci, h, w, 1, 16, 16) # schedule temp_W _, ci, h, w = s[temp_W].op.axis zo, zi = s[temp_W].split(ci, 1) yo, yi = s[temp_W].split(h, 1) xo, xi = s[temp_W].split(w, 16) s[temp_W].reorder(zo, yo, xo, zi, yi, xi) s[temp_W].bind(zi, thread_z) s[temp_W].bind(yi, thread_y) s[temp_W].bind(xi, thread_x) s[temp_W].storage_align(s[temp_W].op.axis[2], 16, 0) s[kernel_vec].compute_inline() # schedule kernel_L if OUTPUT_BLOCK_HEIGHT == 2 and OUTPUT_BLOCK_WIDTH == 14: s[kernel_L].compute_at(s[conv_L], ry) else: s[kernel_L].compute_at(s[conv_L], rx) # schedule output if output.op in s.outputs: out = output else: s[output].compute_inline() out = s.outputs[0] _, co, h, w = s[out].op.axis tile_and_bind3d(s, out, w, h, co, 4, 8, 8)
https://github.com/zk-ml/tachikoma
python/tvm/topi/intel_graphics/conv2d_alter_op.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=invalid-name,unused-variable,unused-argument,no-member """Conv2D alter op and legalize functions for x86""" import tvm from tvm import te from tvm import relay from tvm import autotvm from ..utils import get_const_tuple from ..nn import conv2d_alter_layout, conv2d_infer_layout from .conv2d import _get_default_config @conv2d_alter_layout.register(["intel_graphics"]) def _alter_conv2d_layout(attrs, inputs, tinfos, out_type): target = tvm.target.Target.current(allow_none=False) dispatch_ctx = autotvm.task.DispatchContext.current if isinstance(dispatch_ctx, autotvm.task.ApplyGraphBest): cfg = dispatch_ctx.query(target, None) workload = cfg.workload else: _, outs = relay.backend.te_compiler.select_implementation( relay.op.get("nn.conv2d"), attrs, tinfos, out_type, target ) workload = autotvm.task.get_workload(outs) if workload is None: # The best implementation is not an AutoTVM template, # we then assume it's not necessary to alter this op. return None cfg = dispatch_ctx.query(target, workload) topi_tmpl = workload[0] new_attrs = {k: attrs[k] for k in attrs.keys()} padding = attrs.get_int_tuple("padding") strides = attrs.get_int_tuple("strides") dilation = attrs.get_int_tuple("dilation") data_layout = attrs["data_layout"] kernel_layout = attrs["kernel_layout"] data_tensor, kernel_tensor = tinfos data_dtype = data_tensor.dtype kernel_dtype = kernel_tensor.dtype out_dtype = out_type.dtype if topi_tmpl == "conv2d_NCHWc.intel_graphics": assert data_layout == "NCHW" and kernel_layout == "OIHW" if cfg.is_fallback: _get_default_config(cfg, data_tensor, kernel_tensor, strides, padding, out_dtype, False) batch_size, in_channel, height, width = get_const_tuple(data_tensor.shape) out_channel, _, kh, kw = get_const_tuple(kernel_tensor.shape) ic_bn = cfg["tile_ic"].val if hasattr(cfg["tile_ic"], "val") else cfg["tile_ic"].size[-1] oc_bn = cfg["tile_oc"].val if hasattr(cfg["tile_oc"], "val") else cfg["tile_oc"].size[-1] # update new attrs new_attrs["channels"] = out_channel new_attrs["data_layout"] = "NCHW%dc" % ic_bn # (oc, ic, h, w) -> (OC, IC, h, w, ic, oc) new_attrs["kernel_layout"] = "OIHW%di%do" % (ic_bn, oc_bn) new_attrs["out_layout"] = "NCHW%dc" % oc_bn # Store altered operator's config new_data = te.placeholder( (batch_size, in_channel // ic_bn, height, width, ic_bn), dtype=data_dtype ) new_kernel = te.placeholder( (out_channel // oc_bn, in_channel // ic_bn, kh, kw, ic_bn, oc_bn), dtype=kernel_dtype ) new_workload = autotvm.task.args_to_workload( [ new_data, new_kernel, strides, padding, dilation, new_attrs["data_layout"], new_attrs["out_layout"], out_dtype, ], "conv2d_NCHWc.intel_graphics", ) dispatch_ctx.update(target, new_workload, cfg) return relay.nn.contrib_conv2d_nchwc(*inputs, **new_attrs) return None @conv2d_infer_layout.register("intel_graphics") def _conv2d_infer_layout(workload, cfg): _, data, kernel, strides, padding, dilation, layout, dtype = workload batch_size, in_channel, in_height, in_width = data[1] out_channel, _, k_height, k_width = kernel[1] out_height = (in_height + 2 * padding[0] - k_height) // strides[0] + 1 out_width = (in_width + 2 * padding[1] - k_width) // strides[1] + 1 tile_ic, tile_oc = cfg["tile_ic"].size[-1], cfg["tile_oc"].size[-1] in_shape = (batch_size, in_channel // tile_ic, in_height, in_width, tile_ic) in_layout = "NCHW%dc" % tile_ic out_shape = (batch_size, out_channel // tile_oc, out_height, out_width, tile_oc) out_layout = "NCHW%dc" % tile_oc return ((in_shape, in_layout),), ((out_shape, out_layout),)
https://github.com/zk-ml/tachikoma
python/tvm/topi/intel_graphics/depthwise_conv2d.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=invalid-name """Schedule for depthwise_conv2d with auto fusion""" import tvm from tvm import te from tvm import autotvm from ..utils import traverse_inline from .. import nn from ..nn.depthwise_conv2d import depthwise_conv2d_infer_layout # register original implementation of depthwise_conv2d_nchw since we don't need to change this part @autotvm.register_topi_compute("depthwise_conv2d_nchw.intel_graphics") def depthwise_conv2d_nchw(_, data, kernel, strides, padding, dilation, out_dtype): return nn.depthwise_conv2d_nchw(data, kernel, strides, padding, dilation, out_dtype) @autotvm.register_topi_schedule("depthwise_conv2d_nchw.intel_graphics") def schedule_depthwise_conv2d_nchw(cfg, outs): """Schedule for depthwise_conv2d nchw forward. Parameters ---------- outs: Array of Tensor The computation graph description of depthwise_conv2d in the format of an array of tensors. Returns ------- s: Schedule The computation schedule for depthwise_conv2d nchw. """ outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs s = te.create_schedule([x.op for x in outs]) def _callback(op): if op.tag == "depthwise_conv2d_nchw": pad_data = op.input_tensors[0] kernel = op.input_tensors[1] conv = op.output(0) ##### space definition begin ##### n, f, y, x = s[conv].op.axis cfg.define_split("tile_f", f, num_outputs=4) cfg.define_split("tile_y", y, num_outputs=4) cfg.define_split("tile_x", x, num_outputs=4) cfg.define_knob("auto_unroll_max_step", [0, 256, 1500]) target = tvm.target.Target.current() if target.kind.name in ["nvptx", "rocm"]: cfg.define_knob("unroll_explicit", [1]) else: cfg.define_knob("unroll_explicit", [0, 1]) # fallback support if cfg.is_fallback: ref_log = autotvm.tophub.load_reference_log( target.kind.name, target.model, "depthwise_conv2d_nchw.intel_graphics" ) cfg.fallback_with_reference_log(ref_log) cfg["unroll_explicit"].val = 0 ##### space definition end ##### s[pad_data].compute_inline() if isinstance(kernel.op, tvm.te.ComputeOp) and "dilate" in kernel.op.tag: s[kernel].compute_inline() if conv.op in s.outputs: output = conv OL = s.cache_write(conv, "local") else: output = s.outputs[0].output(0) s[conv].set_scope("local") OL = conv # create cache stage AA = s.cache_read(pad_data, "shared", [OL]) WW = s.cache_read(kernel, "shared", [OL]) AL = s.cache_read(AA, "local", [OL]) WL = s.cache_read(WW, "local", [OL]) # tile and bind spatial axes n, f, y, x = s[output].op.axis bf, vf, tf, fi = cfg["tile_f"].apply(s, output, f) by, vy, ty, yi = cfg["tile_y"].apply(s, output, y) bx, vx, tx, xi = cfg["tile_x"].apply(s, output, x) kernel_scope, n = s[output].split(n, nparts=1) bf = s[output].fuse(n, bf) s[output].bind(bf, te.thread_axis("blockIdx.z")) s[output].bind(by, te.thread_axis("blockIdx.y")) s[output].bind(bx, te.thread_axis("blockIdx.x")) s[output].bind(vf, te.thread_axis("vthread")) s[output].bind(vy, te.thread_axis("vthread")) s[output].bind(vx, te.thread_axis("vthread")) s[output].bind(tf, te.thread_axis("threadIdx.z")) s[output].bind(ty, te.thread_axis("threadIdx.y")) s[output].bind(tx, te.thread_axis("threadIdx.x")) s[output].reorder(bf, by, bx, vf, vy, vx, tf, ty, tx, fi, yi, xi) s[OL].compute_at(s[output], tx) # cooperative fetching s[AA].compute_at(s[output], bx) s[WW].compute_at(s[output], bx) s[AL].compute_at(s[output], tx) s[WL].compute_at(s[output], tx) for load in [AA, WW]: fused = s[load].fuse(*list(s[load].op.axis)) fused, tx = s[load].split(fused, cfg["tile_x"].size[2]) fused, ty = s[load].split(fused, cfg["tile_y"].size[2]) fused, tz = s[load].split(fused, cfg["tile_f"].size[2]) s[load].bind(tz, te.thread_axis("threadIdx.z")) s[load].bind(ty, te.thread_axis("threadIdx.y")) s[load].bind(tx, te.thread_axis("threadIdx.x")) s[output].pragma(kernel_scope, "auto_unroll_max_step", cfg["auto_unroll_max_step"].val) s[output].pragma(kernel_scope, "unroll_explicit", cfg["unroll_explicit"].val) traverse_inline(s, outs[0].op, _callback) return s @depthwise_conv2d_infer_layout.register("intel_graphics") def _depthwise_conv2d_infer_layout(workload, _): """Infer input/output shapes and layouts from a workload and cfg. Parameters ---------- workload : tuple conv2d workload cfg : tuple tvm.autotvm config Returns ------- Output : [tuple of tuple and str, tuple of tuple and str] Input shapes and layouts, and output shapes and layouts """ _, data, kernel, strides, padding, _, _ = workload batch_size, in_channel, in_height, in_width = data[1] filter_channel, channel_multiplier, k_height, k_width = kernel[1] out_channel = filter_channel * channel_multiplier out_height = (in_height + 2 * padding[0] - k_height) // strides[0] + 1 out_width = (in_width + 2 * padding[1] - k_width) // strides[1] + 1 in_shape = (batch_size, in_channel, in_height, in_width) out_shape = (batch_size, out_channel, out_height, out_width) in_layout = out_layout = "NCHW" return ((in_shape, in_layout),), ((out_shape, out_layout),)
https://github.com/zk-ml/tachikoma
python/tvm/topi/mali/__init__.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=redefined-builtin, wildcard-import """ARM Mali GPU specific declaration and schedules.""" from __future__ import absolute_import as _abs from .conv2d import * from .depthwise_conv2d import * from .dense import *
https://github.com/zk-ml/tachikoma
python/tvm/topi/mali/conv2d.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=invalid-name,unused-variable,unused-argument,no-else-return """conv2d schedule on ARM Mali GPU""" import logging import tvm from tvm import te from tvm import relay from tvm import autotvm from tvm.autotvm.task.space import get_factors from ..utils import traverse_inline, get_const_int, get_const_tuple from .. import nn from ..nn.winograd_util import winograd_transform_matrices from ..nn.conv2d import conv2d_winograd_nhwc, _conv2d_winograd_nhwc_impl # reuse some compute declarations from ARM CPU from ..arm_cpu.conv2d_spatial_pack import conv2d_spatial_pack_nchw from ..arm_cpu.conv2d_spatial_pack import conv2d_spatial_pack_nhwc logger = logging.getLogger("topi") @autotvm.register_topi_compute("conv2d_nchw_spatial_pack.mali") def conv2d_nchw_spatial_pack(cfg, data, kernel, strides, padding, dilation, out_dtype): """TOPI compute callback for conv2d Parameters ---------- cfg: ConfigEntity The config for this template data : tvm.te.Tensor 4-D with shape [batch, in_channel, in_height, in_width] kernel : tvm.te.Tensor 4-D with shape [num_filter, in_channel, filter_height, filter_width] or pre-packed 5-D with shape [num_filter_chunk, in_channel, filter_height, filter_width, num_filter_block] strides : list of two ints [stride_height, stride_width] padding : list of two ints [pad_height, pad_width] dilation : list of two ints [dilation_height, dilation_width] out_dtype: str The output type. This is used for mixed precision. Returns ------- output : tvm.te.Tensor 4-D with shape [batch, out_channel, out_height, out_width] """ return conv2d_spatial_pack_nchw( cfg, data, kernel, strides, padding, dilation, out_dtype, num_tile=3 ) @autotvm.register_topi_schedule("conv2d_nchw_spatial_pack.mali") def schedule_conv2d_nchw_spatial_pack(cfg, outs): """TOPI schedule callback for conv2d Parameters ---------- cfg: ConfigEntity The configuration of this template outs: Array of Tensor The computation graph description of convolution2d in the format of an array of tensors. Returns ------- s: Schedule The computation schedule for conv2d """ s = te.create_schedule([x.op for x in outs]) def _callback(op): # schedule conv2d if "spatial_conv2d_output" in op.tag: _schedule_spatial_pack(cfg, s, op, layout="NCHW") traverse_inline(s, outs[0].op, _callback) return s @autotvm.register_topi_compute("conv2d_nhwc_spatial_pack.mali") def conv2d_nhwc_spatial_pack(cfg, data, kernel, strides, padding, dilation, out_dtype): """Compute conv2d with NHWC layout""" return conv2d_spatial_pack_nhwc( cfg, data, kernel, strides, padding, dilation, out_dtype, num_tile=3 ) @autotvm.register_topi_schedule("conv2d_nhwc_spatial_pack.mali") def schedule_conv2d_nhwc_spatial_pack(cfg, outs): """Create schedule for conv2d_nhwc""" s = te.create_schedule([x.op for x in outs]) def _callback(op): # schedule conv2d if "spatial_conv_output_NHWC" in op.tag: _schedule_spatial_pack(cfg, s, op, layout="NHWC") traverse_inline(s, outs[0].op, _callback) return s def _schedule_spatial_pack(cfg, s, op, layout): """schedule the spatial packing for conv2d""" assert layout in ("NCHW", "NHWC") output = op.output(0) conv = op.input_tensors[0] data_vec = conv.op.input_tensors[0] data_pad = data_vec.op.input_tensors[0] s[data_pad].compute_inline() kernel_vec = conv.op.input_tensors[1] if kernel_vec.op.name == "kernel_vec": kernel = kernel_vec.op.input_tensors[0] else: kernel = kernel_vec if isinstance(kernel.op, tvm.te.ComputeOp) and "dilate" in kernel.op.tag: s[kernel].compute_inline() data = s[data_vec].op.input_tensors[0] max_unroll = 16 vec_size = [1, 2, 4, 8, 16] # get tunable parameters (they are defined in compute) _, TC, VC = cfg["tile_co"].size _, TH, VH = cfg["tile_oh"].size _, TW, VW = cfg["tile_ow"].size # schedule padding if isinstance(data.op, tvm.te.ComputeOp) and "pad" in data.op.tag: data_pad = data s[data_pad].compute_inline() # schedule data packing if layout == "NCHW": if isinstance(data_vec.op, tvm.te.ComputeOp) and data_vec.op.name == "data_vec_undilated": _, h, w, ci, _, _, vh, vw = s[data_vec].op.axis else: _, h, w, ci, vh, vw = s[data_vec].op.axis z, y, x, unroll1, unroll2 = h, w, ci, vh, vw else: if isinstance(data_vec.op, tvm.te.ComputeOp) and data_vec.op.name == "data_vec_undilated": _, oho, owo, _, _, ic, ohi, owi = s[data_vec].op.axis else: _, oho, owo, ohi, owi, ic = s[data_vec].op.axis z, y, x, unroll1, unroll2 = oho, owo, ohi, ic, owi tile_and_bind3d(s, data_vec, z, y, x, 1) if unroll1.dom.extent.value < max_unroll: s[data_vec].unroll(unroll1) if unroll2.dom.extent.value < max_unroll: s[data_vec].unroll(unroll2) if isinstance(kernel_vec.op, tvm.te.ComputeOp) and kernel_vec.name == "kernel_vec": if not autotvm.GLOBAL_SCOPE.in_tuning: max_threads = tvm.target.Target.current(allow_none=False).max_num_threads ax1, ax2, ax3, ax4, ax5 = s[kernel_vec].op.axis fused = s[kernel_vec].fuse(ax1, ax2, ax3, ax4, ax5) fused, vec = s[kernel_vec].split(fused, VC) bb, tt = s[kernel_vec].split(fused, max_threads) s[kernel_vec].bind(bb, te.thread_axis("blockIdx.x")) s[kernel_vec].bind(tt, te.thread_axis("threadIdx.x")) if VC in vec_size: s[kernel_vec].vectorize(vec) # schedule convolution ic, kh, kw = s[conv].op.reduce_axis if layout == "NCHW": kh_dim, kw_dim = kernel_vec.shape[2], kernel_vec.shape[3] else: kh_dim, kw_dim = kernel_vec.shape[0], kernel_vec.shape[1] cfg["ann_reduce"].apply( s, conv, [kh, kw], axis_lens=[get_const_int(kh_dim), get_const_int(kw_dim)], max_unroll=max_unroll, ) if layout == "NCHW": n, c, h, w, vh, vw, vc = s[conv].op.axis cfg["reorder_0"].apply(s, conv, [n, c, h, w, ic, kh, kw, vh, vw, vc]) tile_and_bind3d(s, conv, c, h, w, TC, TH, TW) unroll_vec_axes = [vh, vw, vc] axis_lens = [VH, VW, VC] else: n, oho, owo, oco, ohi, owi, oci = s[conv].op.axis cfg["reorder_conv"].apply(s, conv, [n, oho, owo, oco, kh, kw, ic, ohi, owi, oci]) tile_and_bind3d(s, conv, oho, owo, oco, TH, TW, TC) unroll_vec_axes = [ohi, owi, oci] axis_lens = [VH, VW, VC] cfg["ann_spatial"].apply( s, conv, unroll_vec_axes, axis_lens, max_unroll=max_unroll, vec_size=vec_size, cfg=cfg, ) # schedule output if output.op not in s.outputs: # has bias s[output].compute_inline() output = s.outputs[0] if layout == "NCHW": _, co, oh, ow = s[output].op.axis tile_and_bind3d(s, output, co, oh, ow, TC, TH, TW) else: _, oh, ow, co = s[output].op.axis tile_and_bind3d(s, output, oh, ow, co, TH, TW, TC) return s ##### WINOGRAD TEMPLATE ##### def _pick_tile_size(data, kernel, layout="NCHW"): if layout == "NCHW": N, CI, H, W = get_const_tuple(data.shape) else: assert layout == "NHWC" N, H, W, CI = get_const_tuple(data.shape) if H % 4 == 0: return 4 else: return 2 @autotvm.register_topi_compute("conv2d_nchw_winograd.mali") def conv2d_nchw_winograd(cfg, data, kernel, strides, padding, dilation, out_dtype): tile_size = _pick_tile_size(data, kernel) return _decl_winograd(cfg, data, kernel, strides, padding, dilation, out_dtype, tile_size) @autotvm.register_topi_schedule("conv2d_nchw_winograd.mali") def schedule_conv2d_nchw_winograd(cfg, outs): s = te.create_schedule([x.op for x in outs]) def _callback(op): if "winograd_conv2d_output" in op.tag: _schedule_winograd(cfg, s, op) traverse_inline(s, outs[0].op, _callback) return s def _decl_winograd(cfg, data, kernel, strides, padding, dilation, out_dtype, tile_size): N, CI, IH, IW = get_const_tuple(data.shape) if isinstance(dilation, int): dilation_h = dilation_w = dilation else: dilation_h, dilation_w = dilation if len(kernel.shape) == 4: if dilation_h != 1 or dilation_w != 1: kernel = nn.dilate(kernel, (1, 1, dilation_h, dilation_w)) pre_computed = False CO, _, KH, KW = get_const_tuple(kernel.shape) else: assert (dilation_h, dilation_w) == (1, 1), "Does not support dilation" pre_computed = True H_CAT, W_CAT, CO, CI, VC = get_const_tuple(kernel.shape) CO *= VC KH, KW = H_CAT - tile_size + 1, W_CAT - tile_size + 1 HSTR, WSTR = strides if isinstance(strides, (tuple, list)) else (strides, strides) pt, pl, pb, pr = nn.get_pad_tuple(padding, (KH, KW)) assert KH == 3 and KW == 3 and HSTR == 1 and WSTR == 1 data_pad = nn.pad(data, (0, 0, pt, pl), (0, 0, pb, pr), name="data_pad") r = KW m = tile_size alpha = m + r - 1 A, B, G = winograd_transform_matrices(m, r, out_dtype) H = (IH + pt + pb - 3) // HSTR + 1 W = (IW + pl + pr - 3) // WSTR + 1 nH, nW = (H + m - 1) // m, (W + m - 1) // m P = N * nH * nW ##### space definition begin ##### tile_bna_candidates = [1, 2, 4, 8, 16] factors = get_factors(CO) cfg.define_knob("tile_bna", [x for x in tile_bna_candidates if x in factors]) cfg.define_knob("tile_bnb", [1, 2, 4, 8, 16]) cfg.define_split("tile_t1", CI, num_outputs=2, max_factor=128) cfg.define_split("tile_t2", CO, num_outputs=2, max_factor=128) cfg.define_split("c_unroll", CI, num_outputs=2, max_factor=8) cfg.define_knob("yt", [1, 2, 4, 8, 16, 32]) ##### space definition end ##### if cfg.is_fallback: cfg["tile_bnb"].val = 4 cfg["tile_bna"].val = 4 while CO % cfg["tile_bna"].val != 0: cfg["tile_bna"].val //= 2 cfg["yt"].val = 8 cfg.fallback_split("tile_t1", [-1, 128]) cfg.fallback_split("tile_t2", [-1, 128]) cfg.fallback_split("c_unroll", [-1, 8]) bna = cfg["tile_bna"].val bnb = cfg["tile_bnb"].val P_round = (P + bnb - 1) // bnb * bnb assert CO % bna == 0 and P_round % bnb == 0 # pack input tile input_tile = te.compute( (CI, P_round // bnb, alpha, alpha, bnb), lambda ci, b, eps, nu, bb: tvm.tir.if_then_else( b * bnb + bb < P, data_pad[(b * bnb + bb) // (nH * nW)][ci][(b * bnb + bb) // nW % nH * m + eps][ (b * bnb + bb) % nW * m + nu ], tvm.tir.const(0, data_pad.dtype), ), name="d", ) if autotvm.GLOBAL_SCOPE.in_tuning: kvshape = (alpha, alpha, CO // bna, CI, bna) U = tvm.te.placeholder(kvshape, kernel.dtype, name="U") else: # transform kernel if pre_computed: U = kernel else: r_kh = te.reduce_axis((0, KH), "r_kh") r_kw = te.reduce_axis((0, KW), "r_kw") U = te.compute( (alpha, alpha, CO // bna, CI, bna), lambda eps, nu, co, ci, vco: te.sum( kernel[co * bna + vco][ci][r_kh][r_kw] * G[eps][r_kh] * G[nu][r_kw], axis=[r_kh, r_kw], ), name="U", ) # transform image r_a = te.reduce_axis((0, alpha), "r_a") r_b = te.reduce_axis((0, alpha), "r_b") V = te.compute( (alpha, alpha, P_round // bnb, CI, bnb), lambda eps, nu, p, ci, vp: te.sum( input_tile[ci][p][r_a][r_b][vp] * B[r_a][eps] * B[r_b][nu], axis=[r_a, r_b] ), name="V", ) idxdiv = tvm.tir.indexdiv idxmod = tvm.tir.indexmod # batch gemm ci = te.reduce_axis((0, CI), name="c") M = te.compute( (alpha, alpha, CO, P_round), lambda eps, nu, co, p: te.sum( U[eps][nu][idxdiv(co, bna)][ci][idxmod(co, bna)] * V[eps][nu][idxdiv(p, bnb)][ci][idxmod(p, bnb)], axis=ci, ), name="M", ) r_a = te.reduce_axis((0, alpha), "r_a") r_b = te.reduce_axis((0, alpha), "r_b") Y = te.compute( (CO, P, m, m), lambda co, p, vh, vw: te.sum(M[r_a][r_b][co][p] * A[r_a][vh] * A[r_b][vw], axis=[r_a, r_b]), name="Y", ) # unpack output output = te.compute( (N, CO, H, W), lambda n, co, h, w: Y[ co, n * nH * nW + idxdiv(h, m) * nW + idxdiv(w, m), idxmod(h, m), idxmod(w, m) ] # The following hack term is used to make the padding in batch gemm ("M") # effective, otherwise the padding will be eliminated by bound inference. # Use `tvm.tir.Mul` instead of `*` to avoid issues in const folding. + tvm.tir.Mul(tvm.tir.const(0, out_dtype), M[alpha - 1][alpha - 1][CO - 1][P_round - 1]), name="output", tag="winograd_conv2d_output", ) # we have to manually assign effective GFLOP for winograd cfg.add_flop(2 * N * CO * H * W * KH * KW * CI) return output def _schedule_winograd(cfg, s, op): """schedule winograd fast convolution F(2x2, 3x3) for conv2d""" # get ops and tensors output = op.output(0) Y = op.input_tensors[0] M, A = s[Y].op.input_tensors U, V = s[M].op.input_tensors d, B = s[V].op.input_tensors data_pad = s[d].op.input_tensors[0] # padding s[data_pad].compute_inline() # transform kernel if isinstance(U.op, tvm.te.ComputeOp): kernel, G = s[U].op.input_tensors s[G].compute_inline() ( eps, nu, co, ci, vco, ) = s[U].op.axis if not autotvm.GLOBAL_SCOPE.in_tuning: r_kh, r_kw = s[U].op.reduce_axis s[U].reorder(co, ci, eps, nu, r_kh, r_kw, vco) _ = [s[U].unroll(x) for x in [eps, nu, r_kh, r_kw]] s[U].vectorize(vco) tile_and_bind(s, U, co, ci, 1, 256) # dilation if isinstance(kernel.op, tvm.te.ComputeOp) and "dilate" in kernel.op.tag: s[kernel].compute_inline() # transform image s[B].compute_inline() VL = s.cache_write(V, "local") eps, nu, p, ci, vp = s[V].op.axis s[V].reorder(p, ci, eps, nu, vp) for axis in [eps, nu]: s[V].unroll(axis) s[V].vectorize(vp) fused = s[V].fuse(p, ci) bb, tt = cfg["tile_t1"].apply(s, V, fused) s[V].bind(bb, te.thread_axis("blockIdx.x")) s[V].bind(tt, te.thread_axis("threadIdx.x")) eps, nu, p, ci, vp = s[VL].op.axis r_a, r_b = s[VL].op.reduce_axis for axis in [eps, nu, r_a, r_b]: s[VL].unroll(axis) s[VL].vectorize(vp) s[d].compute_at(s[V], tt) s[VL].compute_at(s[V], tt) # batch gemm bna = cfg["tile_bna"].val bnb = cfg["tile_bnb"].val eps, nu, k, b = s[M].op.axis alpha = eps.dom.extent c = s[M].op.reduce_axis[0] yo, xo, yi, xi = s[M].tile(k, b, bna, bnb) c, c_unroll = cfg["c_unroll"].apply(s, M, c) s[M].reorder(yo, xo, c, c_unroll, yi, xi) s[M].unroll(c_unroll) s[M].unroll(yi) s[M].vectorize(xi) z = s[M].fuse(eps, nu) tile_and_bind3d(s, M, z, yo, xo, 1, cfg["yt"].val, 1) # inverse transform s[A].compute_inline() k, b, vh, vw = s[Y].op.axis r_a, r_b = s[Y].op.reduce_axis for axis in [vh, vw, r_a, r_b]: s[Y].unroll(axis) # schedule output and fusion if output.op not in s.outputs: s[output].compute_inline() output = s.outputs[0] n, co, h, w = s[output].op.axis m = alpha - 3 + 1 h, w, hi, wi = s[output].tile(h, w, m, m) s[output].unroll(hi) s[output].unroll(wi) fused = s[output].fuse(n, co, h, w) bb, tt = cfg["tile_t2"].apply(s, output, fused) s[output].bind(bb, te.thread_axis("blockIdx.x")) s[output].bind(tt, te.thread_axis("threadIdx.x")) s[Y].compute_at(s[output], tt) ##### REGISTER ALTER OP LAYOUT ##### @nn.conv2d_alter_layout.register(["mali"]) def _alter_conv2d_layout(attrs, inputs, tinfos, out_type): target = tvm.target.Target.current(allow_none=False) dispatch_ctx = autotvm.task.DispatchContext.current new_attrs = {k: attrs[k] for k in attrs.keys()} strides = attrs.get_int_tuple("strides") padding = attrs.get_int_tuple("padding") dilation = attrs.get_int_tuple("dilation") data_layout = attrs["data_layout"] kernel_layout = attrs["kernel_layout"] data, kernel = tinfos out_dtype = out_type.dtype impl, outs = relay.backend.te_compiler.select_implementation( relay.op.get("nn.conv2d"), attrs, tinfos, out_type, target ) workload = autotvm.task.get_workload(outs) if workload is None: # The best implementation is not an AutoTVM template. # It may be from the auto-scheduler if impl.name.find("winograd") != -1: if dilation != (1, 1): logger.warning("Does not support weight pre-transform for dilated convolution.") return None assert data_layout == "NHWC" and kernel_layout == "HWIO" N, H, W, CI = get_const_tuple(data.shape) KH, KW, _, CO = get_const_tuple(kernel.shape) # Pre-compute weight transformation in winograd tile_size = _pick_tile_size(tinfos[0], tinfos[1], layout="NHWC") # HWIO -> OIHW kernel_transform = relay.transpose(inputs[1], axes=[3, 2, 0, 1]) # alpha, alpha, CO, CI weight = relay.nn.contrib_conv2d_winograd_weight_transform( kernel_transform, tile_size=tile_size ) new_attrs["tile_size"] = tile_size new_attrs["channels"] = CO return relay.nn.contrib_conv2d_winograd_without_weight_transform( inputs[0], weight, **new_attrs ) return None cfg = dispatch_ctx.query(target, workload) if cfg.is_fallback: # if is fallback, clear query cache and return None autotvm.task.clear_fallback_cache(target, workload) return None topi_tmpl = workload[0] idxd = tvm.tir.indexdiv if topi_tmpl == "conv2d_nchw_spatial_pack.mali": assert data_layout == "NCHW" and kernel_layout == "OIHW" N, CI, H, W = get_const_tuple(data.shape) CO, _, KH, KW = get_const_tuple(kernel.shape) VC = cfg["tile_co"].size[-1] new_attrs["kernel_layout"] = "OIHW%do" % VC new_data = data new_kernel = te.placeholder((idxd(CO, VC), CI, KH, KW, VC), dtype=kernel.dtype) new_workload = autotvm.task.args_to_workload( [new_data, new_kernel, strides, padding, dilation, out_dtype], "conv2d_nchw_spatial_pack.mali", ) dispatch_ctx.update(target, new_workload, cfg) return relay.nn.conv2d(*inputs, **new_attrs) elif topi_tmpl == "conv2d_nchw_winograd.mali": assert data_layout == "NCHW" and kernel_layout == "OIHW" N, CI, H, W = get_const_tuple(data.shape) CO, _, KH, KW = get_const_tuple(kernel.shape) tile_size = _pick_tile_size(data, kernel) VC = cfg["tile_bna"].val weight_expr = inputs[1] weight_expr = relay.nn.contrib_conv2d_winograd_weight_transform( weight_expr, tile_size=tile_size ) weight_expr = relay.reshape( weight_expr, newshape=(KH + tile_size - 1, KW + tile_size - 1, idxd(CO, VC), VC, CI) ) weight_expr = relay.transpose(weight_expr, axes=[0, 1, 2, 4, 3]) new_attrs["tile_size"] = tile_size new_data = data new_kernel = te.placeholder( (KH + tile_size - 1, KW + tile_size - 1, idxd(CO, VC), CI, VC), kernel.dtype ) new_workload = autotvm.task.args_to_workload( [new_data, new_kernel, strides, padding, dilation, out_dtype], "conv2d_nchw_winograd.mali", ) dispatch_ctx.update(target, new_workload, cfg) return relay.nn.contrib_conv2d_winograd_without_weight_transform( inputs[0], weight_expr, **new_attrs ) else: return None @conv2d_winograd_nhwc.register(["mali"]) def conv2d_winograd_nhwc_mali( data, weight, strides, padding, dilation, out_dtype, pre_computed=False, auto_scheduler_rewritten_layout="", ): """Conv2D Winograd in NHWC layout. This is a clean version to be used by the auto-scheduler for mali. """ tile_size = _pick_tile_size(data, weight, layout="NHWC") return _conv2d_winograd_nhwc_impl( data, weight, strides, padding, dilation, out_dtype, tile_size, pre_computed, auto_scheduler_rewritten_layout, ) ##### SCHECULE UTILITIES ##### def tile_and_bind(s, tensor, y, x, y_factor, x_factor=None): """tile and bind to GPU threads""" x_factor = x_factor or y_factor yo, xo, yi, xi = s[tensor].tile(y, x, y_factor, x_factor) s[tensor].bind(xo, te.thread_axis("blockIdx.x")) s[tensor].bind(xi, te.thread_axis("threadIdx.x")) s[tensor].bind(yo, te.thread_axis("blockIdx.y")) s[tensor].bind(yi, te.thread_axis("threadIdx.y")) return yo, xo, yi, xi def tile_and_bind3d(s, tensor, z, y, x, z_factor=2, y_factor=None, x_factor=None): """tile and bind 3d""" y_factor = y_factor or z_factor x_factor = x_factor or y_factor zo, zi = s[tensor].split(z, z_factor) yo, yi = s[tensor].split(y, y_factor) xo, xi = s[tensor].split(x, x_factor) s[tensor].bind(zo, te.thread_axis("blockIdx.z")) s[tensor].bind(zi, te.thread_axis("threadIdx.z")) s[tensor].bind(yo, te.thread_axis("blockIdx.y")) s[tensor].bind(yi, te.thread_axis("threadIdx.y")) s[tensor].bind(xo, te.thread_axis("blockIdx.x")) s[tensor].bind(xi, te.thread_axis("threadIdx.x")) s[tensor].reorder(zo, yo, xo, zi, yi, xi) return zo, yo, xo, zi, yi, xi
https://github.com/zk-ml/tachikoma
python/tvm/topi/mali/dense.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=invalid-name,unused-variable """dense schedule on ARM Mali GPU""" from tvm import te from tvm import autotvm from .. import nn from ..utils import traverse_inline @autotvm.register_topi_compute("dense.mali") def dense(_, data, weight, bias=None, out_dtype=None): """Dense operator on Mali""" return nn.dense(data, weight, bias, out_dtype) @autotvm.register_topi_schedule("dense.mali") def schedule_dense(cfg, outs): """Schedule for dense operator. Parameters ---------- cfg: ConfigEntity The config entity for this template outs: Array of Tensor The computation graph description of dense in the format of an array of tensors. Returns ------- s: Schedule The computation schedule for dense. """ outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs s = te.create_schedule([x.op for x in outs]) def _callback(op): if op.tag == "dense": vec_size = [1, 2, 4, 8, 16] max_unroll = 32 dense_out = op.output(0) output = outs[0] y, x = s[output].op.axis c = s[dense_out].op.reduce_axis[0] ##### space definition begin ##### cfg.define_split("tile_y", y, num_outputs=3) cfg.define_split("tile_x", x, num_outputs=3) cfg.define_split("c_unroll", c, num_outputs=2, max_factor=64) # fallback support if cfg.is_fallback: ref_log = autotvm.tophub.load_reference_log("mali", "rk3399", "dense.mali") cfg.fallback_with_reference_log(ref_log) ##### space definition end ##### if dense_out.op in s.outputs: dense_out = s.cache_write(output, "local") by, ty, yi = cfg["tile_y"].apply(s, output, y) bx, tx, xi = cfg["tile_x"].apply(s, output, x) s[output].bind(by, te.thread_axis("blockIdx.y")) s[output].bind(bx, te.thread_axis("blockIdx.x")) s[output].bind(ty, te.thread_axis("threadIdx.y")) s[output].bind(tx, te.thread_axis("threadIdx.x")) if cfg["tile_y"].size[-1] < max_unroll: s[output].unroll(yi) if cfg["tile_x"].size[-1] in vec_size: s[output].vectorize(xi) s[dense_out].compute_at(s[output], tx) k = s[dense_out].op.reduce_axis[0] y, x = s[dense_out].op.axis k, k_unroll = cfg["c_unroll"].apply(s, dense_out, k) s[dense_out].reorder(k, k_unroll, y, x) s[dense_out].unroll(k_unroll) if cfg["tile_y"].size[-1] < max_unroll: s[dense_out].unroll(y) if cfg["tile_x"].size[-1] in vec_size: s[dense_out].vectorize(x) traverse_inline(s, outs[0].op, _callback) return s def fuse_and_bind(s, tensor, axis=None, num_thread=None): """fuse all the axis and bind to GPU threads""" # TODO(@comaniac): figure out where this function is used. axis = axis or s[tensor].op.axis fused = s[tensor].fuse(*axis) bx, tx = s[tensor].split(fused, num_thread) s[tensor].bind(bx, te.thread_axis("blockIdx.x")) s[tensor].bind(tx, te.thread_axis("threadIdx.x")) return bx, tx
https://github.com/zk-ml/tachikoma
python/tvm/topi/mali/depthwise_conv2d.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=invalid-name,unused-variable,unused-argument """depthwise_conv2d schedule on ARM Mali GPU""" import tvm from tvm import te from tvm import autotvm from .. import nn from ..utils import traverse_inline # register original implementation of depthwise_conv2d_nchw since we don't need to change this part @autotvm.register_topi_compute("depthwise_conv2d_nchw.mali") def depthwise_conv2d_nchw(cfg, data, kernel, strides, padding, dilation, out_dtype): return nn.depthwise_conv2d_nchw(data, kernel, strides, padding, dilation, out_dtype) # register customized schedule for Mali. @autotvm.register_topi_schedule("depthwise_conv2d_nchw.mali") def schedule_depthwise_conv2d_nchw(cfg, outs): """Schedule depthwise conv2d Parameters ---------- cfg: ConfigEntity The configuration of this template outs: Array of Tensor The computation graph description of depthwise convolution2d in the format of an array of tensors. Returns ------- s: Schedule The computation schedule for depthwise_conv2d nchw. """ outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs s = te.create_schedule([x.op for x in outs]) def _callback(op): """traverse to find op to schedule""" # schedule depthwise_conv2d if op.tag == "depthwise_conv2d_nchw": pad_data = op.input_tensors[0] kernel = op.input_tensors[1] conv = op.output(0) _schedule(cfg, s, pad_data, kernel, conv, "NCHW") traverse_inline(s, outs[0].op, _callback) return s # register original implementation of depthwise_conv2d_nhwc since we don't need to change this part @autotvm.register_topi_compute("depthwise_conv2d_nhwc.mali") def depthwise_conv2d_nhwc(cfg, data, kernel, strides, padding, dilation, out_dtype): return nn.depthwise_conv2d_nhwc(data, kernel, strides, padding, dilation, out_dtype) # register customized schedule for Mali. @autotvm.register_topi_schedule("depthwise_conv2d_nhwc.mali") def schedule_depthwise_conv2d_nhwc(cfg, outs): """Schedule depthwise conv2d Parameters ---------- cfg: ConfigEntity The configuration of this template outs: Array of Tensor The computation graph description of depthwise convolution2d in the format of an array of tensors. Returns ------- s: Schedule The computation schedule for depthwise_conv2d nchw. """ outs = [outs] if isinstance(outs, te.tensor.Tensor) else outs s = te.create_schedule([x.op for x in outs]) def _callback(op): """traverse to find op to schedule""" # schedule depthwise_conv2d if op.tag == "depthwise_conv2d_nhwc": pad_data = op.input_tensors[0] kernel = op.input_tensors[1] conv = op.output(0) _schedule(cfg, s, pad_data, kernel, conv, "NHWC") traverse_inline(s, outs[0].op, _callback) return s def _schedule(cfg, s, pad_data, kernel, conv, layout): """schedule depthwise_conv2d""" assert layout in ("NCHW", "NHWC") max_unroll = 16 vec_size = [1, 2, 4, 8, 16] ##### space definition begin ##### if layout == "NCHW": n, c, h, w = s[conv].op.axis else: n, h, w, c = s[conv].op.axis bc, tc, ci = cfg.define_split("tile_c", c, num_outputs=3) bh, th, hi = cfg.define_split("tile_y", h, num_outputs=3) bw, tw, wi = cfg.define_split("tile_x", w, num_outputs=3) cfg.define_annotate("ann_spatial", [ci, hi, wi], policy="try_unroll_vec") # fallback support if cfg.is_fallback: if layout == "NCHW": ref_log = autotvm.tophub.load_reference_log( "mali", "rk3399", "depthwise_conv2d_nchw.mali" ) cfg.fallback_with_reference_log(ref_log) else: cfg.fallback_split("tile_c", [-1, 4, 2]) cfg.fallback_split("tile_y", [-1, 4, 2]) cfg.fallback_split("tile_x", [-1, 4, 2]) ###### space definition end ###### # schedule padding if layout == "NCHW": n, c, h, w = s[pad_data].op.axis z, y, x = c, h, w z_factor, y_factor, x_factor = cfg["tile_c"].size[1], 1, 1 else: n, h, w, c = s[pad_data].op.axis z, y, x = h, w, c z_factor, y_factor, x_factor = 1, 1, cfg["tile_c"].size[1] tile_and_bind3d(s, pad_data, z, y, x, z_factor, y_factor, x_factor) # schedule dilation if isinstance(kernel.op, tvm.te.ComputeOp) and "dilate" in kernel.op.tag: s[kernel].compute_inline() # schedule conv if conv.op not in s.outputs: s[conv].set_scope("local") OL = conv output = s.outputs[0].output(0) else: OL = s.cache_write(conv, "local") output = conv if layout == "NCHW": n, c, h, w = s[output].op.axis else: n, h, w, c = s[output].op.axis bc, tc, ci = cfg["tile_c"].apply(s, output, c) bh, th, hi = cfg["tile_y"].apply(s, output, h) bw, tw, wi = cfg["tile_x"].apply(s, output, w) if layout == "NCHW": bz, tz, by, ty, bx, tx = bc, tc, bh, th, bw, tw else: bz, tz, by, ty, bx, tx = bh, th, bw, tw, bc, tc bz = s[output].fuse(n, bz) s[output].bind(bz, te.thread_axis("blockIdx.z")) s[output].bind(tz, te.thread_axis("threadIdx.z")) s[output].bind(by, te.thread_axis("blockIdx.y")) s[output].bind(ty, te.thread_axis("threadIdx.y")) s[output].bind(bx, te.thread_axis("blockIdx.x")) s[output].bind(tx, te.thread_axis("threadIdx.x")) di, dj = s[OL].op.reduce_axis s[OL].unroll(di) s[OL].unroll(dj) s[OL].compute_at(s[output], tx) if layout == "NCHW": n, ci, hi, wi = s[OL].op.axis else: n, hi, wi, ci = s[OL].op.axis cfg["ann_spatial"].apply( s, OL, [ci, hi, wi], axis_lens=[cfg["tile_c"].size[2], cfg["tile_y"].size[2], cfg["tile_x"].size[2]], max_unroll=max_unroll, vec_size=vec_size, cfg=cfg, ) def tile_and_bind3d(s, tensor, z, y, x, z_factor=2, y_factor=None, x_factor=None): """tile and bind 3d""" y_factor = y_factor or z_factor x_factor = x_factor or y_factor zo, zi = s[tensor].split(z, z_factor) yo, yi = s[tensor].split(y, y_factor) xo, xi = s[tensor].split(x, x_factor) s[tensor].bind(zo, te.thread_axis("blockIdx.z")) s[tensor].bind(zi, te.thread_axis("threadIdx.z")) s[tensor].bind(yo, te.thread_axis("blockIdx.y")) s[tensor].bind(yi, te.thread_axis("threadIdx.y")) s[tensor].bind(xo, te.thread_axis("blockIdx.x")) s[tensor].bind(xi, te.thread_axis("threadIdx.x")) return zo, zi, yo, yi, xo, xi
https://github.com/zk-ml/tachikoma
python/tvm/topi/math.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """Elementwise operators""" # pylint: disable=redefined-builtin,unused-argument import tvm from tvm import te from . import tag from . import cpp from .utils import get_const_tuple @tvm.te.tag_scope(tag=tag.ELEMWISE) def identity(x): """Take identity of input x. Parameters ---------- x : tvm.te.Tensor Input argument. Returns ------- y : tvm.te.Tensor The result. """ # pylint: disable=unnecessary-lambda return te.compute(x.shape, lambda *i: x(*i)) @tvm.te.tag_scope(tag=tag.ELEMWISE) def negative(x): """Take negation of input x. Parameters ---------- x : tvm.te.Tensor Input argument. Returns ------- y : tvm.te.Tensor The result. """ # pylint: disable=unnecessary-lambda return te.compute(x.shape, lambda *i: -x(*i)) @tvm.te.tag_scope(tag=tag.ELEMWISE) def exp(x): """Take exponential of input x. Parameters ---------- x : tvm.te.Tensor Input argument. Returns ------- y : tvm.te.Tensor The result. """ return te.compute(x.shape, lambda *i: te.exp(x(*i))) @tvm.te.tag_scope(tag=tag.ELEMWISE) def erf(x): """Take gauss error function of input x. Parameters ---------- x : tvm.te.Tensor Input argument. Returns ------- y : tvm.te.Tensor The result. """ return te.compute(x.shape, lambda *i: te.erf(x(*i))) @tvm.target.generic_func def erf_legalize(attrs, inputs, types): """Legalizes ERF op. Parameters ---------- attrs : tvm.ir.Attrs Attributes of current convolution inputs : list of tvm.relay.Expr The args of the Relay expr to be legalized types : list of types List of input and output types Returns ------- result : tvm.relay.Expr The legalized expr. """ # Note changed by default. return None @tvm.te.tag_scope(tag=tag.ELEMWISE) def tanh(x): """Take hyperbolic tanh of input x. Parameters ---------- x : tvm.te.Tensor Input argument. Returns ------- y : tvm.te.Tensor The result. """ return te.compute(x.shape, lambda *i: te.tanh(x(*i))) @tvm.te.tag_scope(tag=tag.ELEMWISE) def tan(x): """Take tan of input x. Parameters ---------- x : tvm.te.Tensor Input argument. Returns ------- y : tvm.te.Tensor The result. """ return te.compute(x.shape, lambda *i: te.tan(x(*i))) @tvm.te.tag_scope(tag=tag.ELEMWISE) def cos(x): """Take cos of input x. Parameters ---------- x : tvm.te.Tensor Input argument. Returns ------- y : tvm.te.Tensor The result. """ return te.compute(x.shape, lambda *i: te.cos(x(*i))) @tvm.te.tag_scope(tag=tag.ELEMWISE) def cosh(x): """Take cosh of input x. Parameters ---------- x : tvm.te.Tensor Input argument. Returns ------- y : tvm.te.Tensor The result. """ return te.compute(x.shape, lambda *i: te.cosh(x(*i))) @tvm.te.tag_scope(tag=tag.ELEMWISE) def sin(x): """Take sin of input x. Parameters ---------- x : tvm.te.Tensor Input argument. Returns ------- y : tvm.te.Tensor The result. """ return te.compute(x.shape, lambda *i: te.sin(x(*i))) @tvm.te.tag_scope(tag=tag.ELEMWISE) def sinh(x): """Take sinh of input x. Parameters ---------- x : tvm.te.Tensor Input argument. Returns ------- y : tvm.te.Tensor The result. """ return te.compute(x.shape, lambda *i: te.sinh(x(*i))) @tvm.te.tag_scope(tag=tag.ELEMWISE) def acos(x): """Take arc cos of input x. Parameters ---------- x : tvm.te.Tensor Input argument. Returns ------- y : tvm.te.Tensor The result. """ return te.compute(x.shape, lambda *i: te.acos(x(*i))) @tvm.te.tag_scope(tag=tag.ELEMWISE) def acosh(x): """Take arc cosh of input x. Parameters ---------- x : tvm.te.Tensor Input argument. Returns ------- y : tvm.te.Tensor The result. """ return te.compute(x.shape, lambda *i: te.acosh(x(*i))) @tvm.te.tag_scope(tag=tag.ELEMWISE) def asin(x): """Take arc sin of input x. Parameters ---------- x : tvm.te.Tensor Input argument. Returns ------- y : tvm.te.Tensor The result. """ return te.compute(x.shape, lambda *i: te.asin(x(*i))) @tvm.te.tag_scope(tag=tag.ELEMWISE) def asinh(x): """Take arc sinh of input x. Parameters ---------- x : tvm.te.Tensor Input argument. Returns ------- y : tvm.te.Tensor The result. """ return te.compute(x.shape, lambda *i: te.asinh(x(*i))) @tvm.te.tag_scope(tag=tag.ELEMWISE) def atan(x): """Take atan of input x. Parameters ---------- x : tvm.te.Tensor Input argument. Returns ------- y : tvm.te.Tensor The result. """ return te.compute(x.shape, lambda *i: te.atan(x(*i))) @tvm.te.tag_scope(tag=tag.ELEMWISE) def atanh(x): """Take atanh of input x. Parameters ---------- x : tvm.te.Tensor Input argument. Returns ------- y : tvm.te.Tensor The result. """ return te.compute(x.shape, lambda *i: te.atanh(x(*i))) @tvm.te.tag_scope(tag=tag.ELEMWISE) def floor(x): """Take floor of input x. Parameters ---------- x : tvm.te.Tensor Input argument. Returns ------- y : tvm.te.Tensor The result. """ return te.compute(x.shape, lambda *i: te.floor(x(*i))) @tvm.te.tag_scope(tag=tag.ELEMWISE) def ceil(x): """Take ceil of input x. Parameters ---------- x : tvm.te.Tensor Input argument. Returns ------- y : tvm.te.Tensor The result. """ return te.compute(x.shape, lambda *i: te.ceil(x(*i))) def sign(x): """Returns -1, 0, 1 based on sign of x. Parameters ---------- x : tvm.te.Tensor Input argument. Returns ------- y : tvm.te.Tensor The result. """ return cpp.sign(x) @tvm.te.tag_scope(tag=tag.ELEMWISE) def trunc(x): """Take truncated value of the input of x, element-wise. Parameters ---------- x : tvm.te.Tensor Input argument. Returns ------- y : tvm.te.Tensor The result. """ return te.compute(x.shape, lambda *i: te.trunc(x(*i))) @tvm.te.tag_scope(tag=tag.ELEMWISE) def abs(x): """Take absolute value of the input of x, element-wise. Parameters ---------- x : tvm.te.Tensor Input argument. Returns ------- y : tvm.te.Tensor The result. """ return te.compute(x.shape, lambda *i: te.abs(x(*i))) @tvm.te.tag_scope(tag=tag.ELEMWISE) def isnan(x): """Check if value of x is NaN, element-wise. Parameters ---------- x : tvm.te.Tensor Input argument. Returns ------- y : tvm.te.Tensor The result. """ return te.compute(x.shape, lambda *i: te.isnan(x(*i))) @tvm.te.tag_scope(tag=tag.ELEMWISE) def isfinite(x): """Check if value of x is finite, element-wise. Parameters ---------- x : tvm.te.Tensor Input argument. Returns ------- y : tvm.te.Tensor The result. """ return te.compute(x.shape, lambda *i: te.isfinite(x(*i))) @tvm.te.tag_scope(tag=tag.ELEMWISE) def isinf(x): """Check if value of x is infinite, element-wise. Parameters ---------- x : tvm.te.Tensor Input argument. Returns ------- y : tvm.te.Tensor The result. """ return te.compute(x.shape, lambda *i: te.isinf(x(*i))) @tvm.te.tag_scope(tag=tag.ELEMWISE) def round(x): """Round elements of x to nearest integer. Parameters ---------- x : tvm.te.Tensor Input argument. Returns ------- y : tvm.te.Tensor The result. """ return te.compute(x.shape, lambda *i: te.round(x(*i))) @tvm.te.tag_scope(tag=tag.ELEMWISE) def log(x): """Take logarithm of input x. Parameters ---------- x : tvm.te.Tensor Input argument. Returns ------- y : tvm.te.Tensor The result. """ return te.compute(x.shape, lambda *i: te.log(x(*i))) @tvm.te.tag_scope(tag=tag.ELEMWISE) def log2(x): """Take logarithm to the base 2 of input x. Parameters ---------- x : tvm.te.Tensor Input argument. Returns ------- y : tvm.te.Tensor The result. """ return te.compute(x.shape, lambda *i: te.log2(x(*i))) @tvm.te.tag_scope(tag=tag.ELEMWISE) def log10(x): """Take logarithm to the base 10 of input x. Parameters ---------- x : tvm.te.Tensor Input argument. Returns ------- y : tvm.te.Tensor The result. """ return te.compute(x.shape, lambda *i: te.log10(x(*i))) @tvm.te.tag_scope(tag=tag.ELEMWISE) def sqrt(x): """Take square root of input x. Parameters ---------- x : tvm.te.Tensor Input argument. Returns ------- y : tvm.te.Tensor The result. """ return te.compute(x.shape, lambda *i: te.sqrt(x(*i))) @tvm.te.tag_scope(tag=tag.ELEMWISE) def rsqrt(x): """Take inverse square root of input x. Parameters ---------- x : tvm.te.Tensor Input argument. Returns ------- y : tvm.te.Tensor The result. """ return te.compute(x.shape, lambda *i: te.rsqrt(x(*i))) @tvm.te.tag_scope(tag=tag.ELEMWISE) def sigmoid(x): """Take sigmoid tanh of input x. Parameters ---------- x : tvm.te.Tensor Input argument. Returns ------- y : tvm.te.Tensor The result. """ return te.compute(x.shape, lambda *i: te.sigmoid(x(*i))) @tvm.te.tag_scope(tag=tag.ELEMWISE) def left_shift(x, n): """Take n bits left shift of input x. Parameters ---------- x : tvm.te.Tensor Input argument. n : int Number of bits. Returns ------- y : tvm.te.Tensor The result. """ return te.compute(x.shape, lambda *i: x(*i) << n) @tvm.te.tag_scope(tag=tag.ELEMWISE) def right_shift(x, n): """Take n bits right shift of input x. Parameters ---------- x : tvm.te.Tensor Input argument. n : int Number of bits. Returns ------- y : tvm.te.Tensor The result. """ return te.compute(x.shape, lambda *i: x(*i) >> n) @tvm.te.tag_scope(tag=tag.ELEMWISE) def clip(x, a_min, a_max): """Clip (limit) the values in an array. Given an interval, values outside the interval are clipped to the interval edges. Parameters ---------- x : tvm.te.Tensor Input argument. a_min : int or float Minimum value. a_max : int or float Maximum value. Returns ------- y : tvm.te.Tensor The result. """ def _compute(*indices): value = x(*indices) const_min = tvm.tir.const(a_min, value.dtype) const_max = tvm.tir.const(a_max, value.dtype) return tvm.te.max(tvm.te.min(value, const_max), const_min) return te.compute(x.shape, _compute) @tvm.te.tag_scope(tag=tag.ELEMWISE) def fixed_point_multiply(x, multiplier, shift): """Fixed point multiplication between data and a fixed point constant expressed as multiplier * 2^(-shift), where multiplier is a Q-number with 31 fractional bits Parameters ---------- x : tvm.te.Tensor or Expr Input argument. multiplier : int Multiplier of a fixed floating point number described as multiplier*2^(-shift). shift : int Shift of a fixed floating point number described as multiplier*2^(-shift). Returns ------- y : tvm.te.Tensor The result. """ def _compute(*indices): value = x(*indices) return tvm.tir.q_multiply_shift( value, tvm.tir.const(multiplier, "int32"), tvm.tir.const(31, "int32"), tvm.tir.const(shift, "int32"), ) return te.compute(x.shape, _compute) @tvm.te.tag_scope(tag=tag.BROADCAST) def fixed_point_multiply_per_axis( x: te.Tensor, y: te.Tensor, lshift: te.Tensor, rshift: te.Tensor, is_lshift_required: int, is_rshift_required: int, axes, ): """Fixed point multiplication between data and a fixed point constant expressed as multiplier * 2^(-shift), where multiplier is a Q-number with 31 fractional bits Parameters ---------- x : tvm.te.Tensor Input argument. y : tvm.te.Tensor Multiplier of a fixed floating point number described as multiplier*2^(-shift). lshift : tvm.te.Tensor Left shifts of a fixed floating point number described as multiplier*2^(-shift). rshift : tvm.te.Tensor Right shifts of a fixed floating point number described as multiplier*2^(-shift). is_lshift_required : int Whether we need to do left shift or not. is_rshift_required : int Whether we need to do right shift or not. Returns ------- z : tvm.te.Tensor The result. """ def _compute(*indices): elements = [] for element in get_const_tuple(axes): elements += [indices[element]] param_indices = tuple(elements) value = x(*indices) m = y(*param_indices) l_shift = lshift(*param_indices) r_shift = rshift(*param_indices) return tvm.tir.q_multiply_shift_per_axis( value, m, l_shift, r_shift, tvm.tir.const(31, "int32"), tvm.tir.const(is_lshift_required, "bool"), tvm.tir.const(is_rshift_required, "bool"), ) return te.compute(x.shape, _compute) def cast(x, dtype, span=None): """Cast input to specified data type. Parameters ---------- x : tvm.te.Tensor or Expr Input argument. dtype : str Data type. span : Optional[Span] The location of the cast in the source. Returns ------- y : tvm.te.Tensor The result. """ if isinstance(x, te.tensor.Tensor): return te.compute(x.shape, lambda *i: x(*i).astype(dtype), tag=tag.ELEMWISE) # pylint: disable=import-outside-toplevel from tvm.tir import _ffi_api return _ffi_api._cast(dtype, x, span) def reinterpret(x, dtype): """Reinterpret input to specified data type. Parameters ---------- x : tvm.te.Tensor Input argument. dtype : str Data type. Returns ------- y : tvm.te.Tensor The result. """ return cpp.reinterpret(x, dtype) def fast_exp(x): """Take exponential of input x using fast_exp implementation Parameters ---------- x : tvm.te.Tensor Input argument. Returns ------- y : tvm.te.Tensor The result. """ return cpp.fast_exp(x, x.dtype, tag.ELEMWISE) def fast_tanh(x): """Take hyperbolic tangent of input x using fast_tanh implementation Parameters ---------- x : tvm.te.Tensor Input argument. Returns ------- y : tvm.te.Tensor The result. """ return cpp.fast_tanh(x, x.dtype, tag.ELEMWISE) def fast_erf(x): """Take gauss error function of input x using fast_erf implementation. Parameters ---------- x : tvm.te.Tensor Input argument. Returns ------- y : tvm.te.Tensor The result. """ return cpp.fast_erf(x, x.dtype, tag.ELEMWISE) def ceil_log2(x): """Compute integer ceil log2 with a special code path for vulkan SPIR-V does not support log2 on fp64. Instead, we compute integer ceil_log2 via clz intrinsic when the target is vulkan. Parameters ---------- x : tvm.te.Tensor Input argument. Returns ------- y : tvm.te.Tensor The result. """ if not isinstance(x, tvm.tir.PrimExpr): x = tvm.tir.const(x) if "float" in x.dtype: return tvm.tir.ceil(tvm.tir.log2(x)) if "vulkan" in tvm.target.Target.current().kind.name: clz = tvm.tir.clz(x) bits = int(x.dtype[-2:]) res = tvm.tir.if_then_else(x & (x - 1) == 0, bits - clz - 1, bits - clz) if res.dtype != x.dtype: return cast(res, x.dtype) return res return cast(tvm.tir.ceil(tvm.tir.log2(cast(x, "float64"))), x.dtype)
https://github.com/zk-ml/tachikoma
python/tvm/topi/nn/__init__.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=wildcard-import """Neural network operators""" from __future__ import absolute_import as _abs from .conv1d import * from .conv2d import * from .conv3d import * from .correlation import * from .deformable_conv2d import * from .depthwise_conv2d import * from .elemwise import * from .dilate import * from .flatten import * from .dense import * from .mapping import * from .pooling import * from .softmax import * from .conv3d_transpose import * from .conv2d_transpose import * from .conv1d_transpose import * from .bnn import * from .qnn import * from .upsampling import * from .layer_norm import layer_norm from .local_response_norm import * from .bitserial_conv2d import * from .bitserial_dense import * from .batch_matmul import * from .batch_norm import * from .sparse import * from .pad import * from .fifo_buffer import * from .depth_to_space import * from .space_to_depth import * from .space_to_batch_nd import * from .batch_to_space_nd import * from .loss import * from .lstm import *
https://github.com/zk-ml/tachikoma
python/tvm/topi/nn/batch_matmul.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """Batch matrix multiplication""" # pylint: disable=invalid-name import logging import tvm from tvm import auto_scheduler, te from ..utils import get_const_tuple logger = logging.getLogger("topi") def batch_matmul( tensor_a, tensor_b, oshape=None, out_dtype=None, transpose_a=False, transpose_b=True, auto_scheduler_rewritten_layout="", meta_schedule_original_shape=None, ): """Compute batch matrix multiplication of `tensor_a` and `tensor_b`. Both `tensor_a` and `tensor_b` can be transposed. For legacy reason, we use NT format (transpose_a=False, transpose_b=True) by default. Parameters ---------- tensor_a : tvm.te.Tensor 3-D with shape [batch, M, K] or [batch, K, M]. tensor_b : tvm.te.Tensor 3-D with shape [batch, K, N] or [batch, N, K]. oshape : List[Optional] Explicit intended output shape of the computation. Can be useful in cases with dynamic input shapes. out_dtype : Optional[str] Specifies the output data type for mixed precision batch matmul. transpose_a : Optional[bool] = False Whether the first tensor is in transposed format. transpose_b : Optional[bool] = True Whether the second tensor is in transposed format. auto_scheduler_rewritten_layout: Optional[str] = "" The layout after auto-scheduler's layout rewrite pass. meta_schedule_original_shape: Optional[List[PrimExpr]] = None The original shape of the tensor Returns ------- output : tvm.te.Tensor 3-D with shape [batch, M, N] """ assert len(tensor_a.shape) == 3, "tensor_a only support 3-dim" if transpose_a: XB, XK, XI = get_const_tuple(tensor_a.shape) else: XB, XI, XK = get_const_tuple(tensor_a.shape) if auto_scheduler_rewritten_layout: # Infer shape for the rewritten layout YB, YK, YJ = auto_scheduler.get_shape_from_rewritten_layout( auto_scheduler_rewritten_layout, ["b", "k", "j"] ) auto_scheduler.remove_index_check(tensor_b) elif meta_schedule_original_shape: auto_scheduler.rewrite_tensor_shape(tensor_b, meta_schedule_original_shape) if transpose_b: YB, YJ, YK = get_const_tuple(tensor_b.shape) else: YB, YK, YJ = get_const_tuple(tensor_b.shape) else: assert len(tensor_b.shape) == 3, "tensor_b only support 3-dim" if transpose_b: YB, YJ, YK = get_const_tuple(tensor_b.shape) else: YB, YK, YJ = get_const_tuple(tensor_b.shape) assert XK == YK or isinstance(YK, tvm.tir.expr.Var), "shapes of x and y are inconsistent" k = te.reduce_axis((0, XK), name="k") if oshape is None: assert XB == YB or XB == 1 or YB == 1, "batch dimension doesn't match" batch = ( tvm.tir.expr.SizeVar("batch", "int32") if isinstance(XB, tvm.tir.expr.Var) or isinstance(YB, tvm.tir.expr.Var) else te.max(XB, YB) ) oshape = (batch, XI, YJ) if out_dtype is None: out_dtype = tensor_a.dtype if tensor_a.dtype != tensor_b.dtype: logger.warning( "tensor_a has different data type with tensor_b: %s, %s", tensor_a.dtype, tensor_b.dtype, ) if (transpose_a, transpose_b) == (True, True): compute_lambda = lambda b, i, j: te.sum( tensor_a[b if XB != 1 else 0, k, i].astype(out_dtype) * tensor_b[b if YB != 1 else 0, j, k].astype(out_dtype), axis=k, ) compute_name = "T_batch_matmul_TT" elif (transpose_a, transpose_b) == (True, False): compute_lambda = lambda b, i, j: te.sum( tensor_a[b if XB != 1 else 0, k, i].astype(out_dtype) * tensor_b[b if YB != 1 else 0, k, j].astype(out_dtype), axis=k, ) compute_name = "T_batch_matmul_TN" elif (transpose_a, transpose_b) == (False, True): compute_lambda = lambda b, i, j: te.sum( tensor_a[b if XB != 1 else 0, i, k].astype(out_dtype) * tensor_b[b if YB != 1 else 0, j, k].astype(out_dtype), axis=k, ) compute_name = "T_batch_matmul_NT" else: # (transpose_a, transpose_b) == (False, False): compute_lambda = lambda b, i, j: te.sum( tensor_a[b if XB != 1 else 0, i, k].astype(out_dtype) * tensor_b[b if YB != 1 else 0, k, j].astype(out_dtype), axis=k, ) compute_name = "T_batch_matmul_NN" output = te.compute( oshape, compute_lambda, name=compute_name, tag="batch_matmul", attrs={"layout_free_placeholders": [tensor_b]}, ) if auto_scheduler_rewritten_layout: output = auto_scheduler.rewrite_compute_body(output, auto_scheduler_rewritten_layout) return output @tvm.target.generic_func def batch_matmul_legalize(attrs, inputs, types): """Legalizes batch_matmul op. Parameters ---------- attrs : tvm.ir.Attrs Attributes of current batch_matmul inputs : list of tvm.relay.Expr The args of the Relay expr to be legalized types : list of types List of input and output types Returns ------- result : tvm.relay.Expr The legalized expr """ # not to change by default # pylint: disable=unused-argument return None
https://github.com/zk-ml/tachikoma
python/tvm/topi/nn/batch_norm.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """Batch normalization.""" import typing from tvm import te from tvm import topi def batch_norm( data: te.Tensor, gamma: te.Tensor, beta: te.Tensor, moving_mean: te.Tensor, moving_var: te.Tensor, axis: typing.Optional[int] = None, epsilon: typing.Optional[float] = None, center: typing.Optional[bool] = None, scale: typing.Optional[bool] = None, ) -> typing.List[te.Tensor]: """Batch normalization layer (Ioffe and Szegedy, 2014). Normalizes the input at each batch, i.e. applies a transformation that maintains the mean activation close to 0 and the activation standard deviation close to 1. Parameters ---------- data : tvm.te.Tensor Input to be batch-normalized. gamma : tvm.te.Tensor Scale factor to be applied to the normalized tensor. beta : tvm.te.Tensor Offset to be applied to the normalized tensor. moving_mean : tvm.te.Tensor Running mean of input. moving_var : tvm.te.Tensor Running variance of input. axis : int, optional, default=1 Specify along which shape axis the normalization should occur. epsilon : float, optional, default=1e-5 Small float added to variance to avoid dividing by zero. center : bool, optional, default=True If True, add offset of beta to normalized tensor, If False, beta is ignored. scale : bool, optional, defualt=True If True, scale normalized tensor by gamma. If False, gamma is ignored. Returns ------- output : list of tvm.te.Tensor Normalized data with same shape as input moving_mean : tvm.te.Tensor Running mean of input. moving_var : tvm.te.Tensor Running variance of input. """ if axis is None: axis = 1 if epsilon is None: epsilon = 1e-5 if center is None: center = True if scale is None: scale = True shape = [1] * len(data.shape) shape[axis] = data.shape[axis] moving_mean_rs = topi.reshape(moving_mean, shape) moving_var_rs = topi.reshape(moving_var, shape) out = (data - moving_mean_rs) / topi.math.sqrt(moving_var_rs + epsilon) if scale: out = out * topi.reshape(gamma, shape) if center: out = out + topi.reshape(beta, shape) # Moving mean and var aren't updated during test. To avoid # placeholder reuse, we multiply by 1 and return them. return [out, moving_mean * 1, moving_var * 1]
https://github.com/zk-ml/tachikoma
python/tvm/topi/nn/batch_to_space_nd.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=invalid-name """TVM operator batch_to_space_nd compute.""" from __future__ import absolute_import from . import cpp def batch_to_space_nd(data, block_shape, crop_begin_list, crop_end_list): """Perform space to batch transformation on the data Parameters ---------- data : tvm.te.Tensor N-D Tensor with shape [batch, spatial_shape, remaining_shapes], where spatial_shape has M dimensions. block_size : list of ints list of size [M] where M is number of spatial dims, specifies block size for each spatial dimension. crop_begin_list : list of ints list of shape [M] where M is number of spatial dims, specifies begin crop size for each spatial dimension. crop_end_list : list of ints list of shape [M] where M is number of spatial dims, specifies end crop size for each spatial dimension. Returns ------- output : tvm.te.Tensor """ return cpp.nn.batch_to_space_nd(data, block_shape, crop_begin_list, crop_end_list)
https://github.com/zk-ml/tachikoma
python/tvm/topi/nn/bitserial_conv2d.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=invalid-name, too-many-locals, too-many-arguments # pylint: disable=unused-argument, redefined-builtin """Bitserial Conv2D operators""" import tvm from tvm import te from .pad import pad from .utils import get_pad_tuple from .bitserial_util import bitpack from ..utils import get_const_tuple def bitserial_conv2d_nchw( data, kernel, stride, padding, activation_bits, weight_bits, pack_dtype="uint32", out_dtype="int16", unipolar=True, ): """Bitserial Conv2D operator. Parameters ---------- data : tvm.te.Tensor 4-D with shape [batch, in_channel, in_height, in_width] kernel : tvm.te.Tensor 4-D with shape [num_filter, in_channel, filter_height, filter_width] stride : int or a list/tuple of two ints stride size, or [stride_height, stride_width] padding : int or a list/tuple of two or four ints padding size, [pad_height, pad_width], [pad_top, pad_left, pad_down, pad_right] activation_bits: int number of bits used for activations/input elements weight_bits: int number of bits used for weight elements out_dtype: str return type of convolution pack_dtype: str bit packing type unipolar: bool if binarization style is in unipolar 1/0 format, instead of bipolar -1/+1 format Returns ------- output : tvm.te.Tensor 4-D with shape [batch, out_channel, out_height, out_width] """ assert isinstance(stride, int) or len(stride) == 2 Input_q = bitpack(data, activation_bits, pack_axis=1, bit_axis=2, pack_type=pack_dtype) if len(kernel.shape) == 4: Filter_q = bitpack(kernel, weight_bits, pack_axis=1, bit_axis=4, pack_type=pack_dtype) else: Filter_q = kernel batch, in_channel, activation_bits, in_height, in_width = Input_q.shape num_filter, _, kernel_h, kernel_w, weight_bits = Filter_q.shape if isinstance(padding, int) or (isinstance(padding, (tuple, list)) and len(padding) == 2): TPAD, LPAD, DPAD, RPAD = get_pad_tuple(padding, kernel) else: TPAD, LPAD, DPAD, RPAD = padding pad_before = [0, 0, 0, TPAD, LPAD] pad_after = [0, 0, 0, DPAD, RPAD] PadInput_q = pad(Input_q, pad_before, pad_after, name="pad_temp") # compute the output shape if isinstance(stride, int): stride_h = stride_w = stride else: stride_h, stride_w = stride out_channel = num_filter out_height = (in_height - kernel_h + TPAD + DPAD) // stride_h + 1 out_width = (in_width - kernel_w + LPAD + RPAD) // stride_w + 1 rc = te.reduce_axis((0, in_channel), name="rc") ry = te.reduce_axis((0, kernel_h), name="ry") rx = te.reduce_axis((0, kernel_w), name="rx") b1 = te.reduce_axis((0, activation_bits), name="b1") b2 = te.reduce_axis((0, weight_bits), name="b2") if unipolar: def _conv(nn, ff, yy, xx): b1b2 = (b1 + b2).astype(out_dtype) return te.sum( ( ( tvm.tir.popcount( PadInput_q[nn, rc, b1, yy * stride_h + ry, xx * stride_w + rx] & Filter_q[ff, rc, ry, rx, b2] ) - tvm.tir.popcount( PadInput_q[nn, rc, b1, yy * stride_h + ry, xx * stride_w + rx] & ~Filter_q[ff, rc, ry, rx, b2] ) ) << (b1b2) ).astype(out_dtype), axis=[rc, ry, rx, b2, b1], ).astype(out_dtype) else: def _conv(nn, ff, yy, xx): b1b2 = (b1 + b2).astype(out_dtype) return te.sum( ( tvm.tir.popcount( PadInput_q[nn, rc, b1, yy * stride_h + ry, xx * stride_w + rx] & Filter_q[ff, rc, ry, rx, b2] ) << (b1b2) ).astype(out_dtype), axis=[rc, ry, rx, b2, b1], ).astype(out_dtype) return te.compute( (batch, out_channel, out_height, out_width), _conv, name="Conv2dOutput", tag="bitserial_conv2d_nchw", ) def bitserial_conv2d_nhwc( data, kernel, stride, padding, activation_bits, weight_bits, pack_dtype="uint32", out_dtype="int16", unipolar=True, ): """Bitserial Conv2D operator. Parameters ---------- data : tvm.te.Tensor 4-D with shape [batch, in_height, in_width, in_channel] kernel : tvm.te.Tensor 4-D with shape [filter_height, filter_width, in_channel, num_filter] stride : int or a list/tuple of two ints stride size, or [stride_height, stride_width] padding : int or a list/tuple of two or four ints padding size, [pad_height, pad_width], [pad_top, pad_left, pad_down, pad_right] activation_bits: int number of bits used for activations/input elements weight_bits: int number of bits used for weight elements out_dtype: str return type of convolution pack_dtype: str bit packing type unipolar: bool if binarization style is in unipolar 1/0 format, instead of bipolar -1/+1 format Returns ------- output : tvm.te.Tensor 4-D with shape [batch, out_height, out_width, out_channel] """ assert isinstance(stride, int) or len(stride) == 2 Input_q = bitpack(data, activation_bits, pack_axis=3, bit_axis=4, pack_type=pack_dtype) if len(kernel.shape) == 4: Filter_q = bitpack(kernel, weight_bits, pack_axis=2, bit_axis=4, pack_type=pack_dtype) kernel_h, kernel_w, _, num_filter, _ = get_const_tuple(Filter_q.shape) else: Filter_q = kernel kernel_h, kernel_w, _, _, num_filter = get_const_tuple(Filter_q.shape) batch, in_height, in_width, in_channel_q, _ = get_const_tuple(Input_q.shape) if isinstance(padding, int) or (isinstance(padding, (tuple, list)) and len(padding) == 2): TPAD, LPAD, DPAD, RPAD = get_pad_tuple(padding, kernel) else: TPAD, LPAD, DPAD, RPAD = padding pad_before = [0, TPAD, LPAD, 0, 0] pad_after = [0, DPAD, RPAD, 0, 0] # compute the output shape if isinstance(stride, int): stride_h = stride_w = stride else: stride_h, stride_w = stride out_channel = num_filter out_height = (in_height - kernel_h + TPAD + DPAD) // stride_h + 1 out_width = (in_width - kernel_w + LPAD + RPAD) // stride_w + 1 PadInput_q = pad(Input_q, pad_before, pad_after, name="PaddedInput") rc = te.reduce_axis((0, in_channel_q), name="rc") ry = te.reduce_axis((0, kernel_h), name="ry") rx = te.reduce_axis((0, kernel_w), name="rx") b1 = te.reduce_axis((0, activation_bits), name="b1") b2 = te.reduce_axis((0, weight_bits), name="b2") if unipolar: def _conv(nn, yy, xx, ff): b1b2 = (b1 + b2).astype(out_dtype) return te.sum( ( ( tvm.tir.popcount( PadInput_q[nn, yy * stride_h + ry, xx * stride_w + rx, rc, b1] & Filter_q[ry, rx, rc, ff, b2] ) - tvm.tir.popcount( PadInput_q[nn, yy * stride_h + ry, xx * stride_w + rx, rc, b1] & ~Filter_q[ry, rx, rc, ff, b2] ) ) << b1b2 ).astype(out_dtype), axis=[rc, ry, rx, b2, b1], ) else: def _conv(nn, yy, xx, ff): b1b2 = (b1 + b2).astype(out_dtype) return te.sum( ( tvm.tir.popcount( PadInput_q[nn, yy * stride_h + ry, xx * stride_w + rx, rc, b1] & Filter_q[ry, rx, rc, ff, b2] ) << b1b2 ).astype(out_dtype), axis=[rc, ry, rx, b2, b1], ) conv = te.compute( (batch, out_height, out_width, out_channel), _conv, name="Conv2dOutput", tag="bitserial_conv2d_nhwc", ) return conv @tvm.target.generic_func def bitserial_conv2d_legalize(attrs, inputs, types): """Legalizes Bitserial Conv2D op. Parameters ---------- attrs : tvm.ir.Attrs Attributes of current convolution inputs : list of tvm.relay.Expr The args of the Relay expr to be legalized types : list of types List of input and output types Returns ------- result : tvm.relay.Expr The legalized expr """ # not to change by default return None
https://github.com/zk-ml/tachikoma
python/tvm/topi/nn/bitserial_dense.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=invalid-name, too-many-locals, too-many-arguments """Bitserial Dense operator.""" from __future__ import absolute_import import tvm from tvm import te from tvm.topi.utils import get_const_tuple from .bitserial_util import bitpack def bitserial_dense( data, weight, data_bits, weight_bits, pack_dtype="uint32", out_dtype="int16", unipolar=True ): """The default implementation of bitserial dense in topi. Parameters ---------- data : tvm.te.Tensor 2-D with shape [batch, in_dim] weight : tvm.te.Tensor 2-D with shape [out_dim, in_dim] or 3-D with shape [out_dim, weight_bits, in_dim] Returns ------- output : tvm.te.Tensor 2-D with shape [batch, out_dim] """ data_packed = bitpack(data, data_bits, pack_axis=1, bit_axis=1, pack_type=pack_dtype) if len(weight.shape) == 2: weight_packed = bitpack(weight, weight_bits, pack_axis=1, bit_axis=1, pack_type=pack_dtype) else: weight_packed = weight Y, DB, K = get_const_tuple(data_packed.shape) X, WB, _ = get_const_tuple(weight_packed.shape) oshape = (Y, X) k = te.reduce_axis((0, K), name="k") db = te.reduce_axis((0, DB), name="db") wb = te.reduce_axis((0, WB), name="wb") matmul_unipolar = te.compute( oshape, lambda i, j: te.sum( ( tvm.tir.popcount(weight_packed[j, wb, k] & data_packed[i, db, k]) - tvm.tir.popcount(~weight_packed[j, wb, k] & data_packed[i, db, k]) ).astype(out_dtype) << (db + wb).astype(out_dtype), axis=[wb, db, k], ), tag="bitserial_dense_unipolar", ) matmul = te.compute( oshape, lambda i, j: te.sum( tvm.tir.popcount(weight_packed[j, wb, k] & data_packed[i, db, k]).astype(out_dtype) << (db + wb).astype(out_dtype), axis=[wb, db, k], ), tag="bitserial_dense", ) if unipolar: return matmul_unipolar return matmul
https://github.com/zk-ml/tachikoma
python/tvm/topi/nn/bitserial_util.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=invalid-name, too-many-locals, too-many-arguments """Utility functions for bitserial operators""" import numpy as np import tvm from tvm import te from tvm.topi.transform import concatenate from ..utils import get_const_int def bitpack(data, bits, pack_axis, bit_axis, pack_type, name="QuantizeInput"): """Packs data into format necessary for bitserial computation Parameters ---------- pack_axis : int index of the axis to pack in data bit_axis : int index of axis to place bit axis in resulting packed data """ ishape = data.shape n = len(ishape) if pack_type == "uint8": data_width = 8 elif pack_type == "uint16": data_width = 16 elif pack_type == "uint32": data_width = 32 elif pack_type == "uint64": data_width = 64 # Data must be in multiples of the data_width assert get_const_int(ishape[pack_axis]) % data_width == 0, "Not a multiple of word size" shape_vec = list(ishape) shape_vec[pack_axis] = shape_vec[pack_axis] // data_width shape_vec.insert(bit_axis, 1) bitserial_oshape = tuple(shape_vec) masks = np.array([0x1, 0x2, 0x4, 0x8, 0x10, 0x20, 0x40, 0x80]) # pack axis shifts if bit axis comes before if bit_axis <= pack_axis: pack_axis += 1 def _bitpack(*indices): packed_data = [tvm.tir.const(0, pack_type)] * bits for k in range(data_width): # Translate indices for packed data back to original idx = [0] * n j = 0 for i in range(n + 1): if i == bit_axis: continue if i == pack_axis: idx[j] = indices[i] * data_width + k else: idx[j] = indices[i] j += 1 element = data(*idx) for b in range(bits): extracted_bit = ((element & tvm.tir.const(masks[b], "int32")) >> b).astype( pack_type ) packed_data[b] = packed_data[b] | extracted_bit if k < data_width - 1: packed_data[b] = packed_data[b] << 1 if k == data_width - 1: return tuple(packed_data) return tuple(packed_data) output_tuple = te.compute(bitserial_oshape, _bitpack, name=name, tag="bitpack") if bits > 1: return concatenate(output_tuple, axis=bit_axis) return output_tuple def binary_op_multiplier(pack_dtype): """ "Returns number of bits packed into pack_dtype: string pack type for the operator (must be a uint)""" return int(pack_dtype[4:])
https://github.com/zk-ml/tachikoma
python/tvm/topi/nn/bnn.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """Binary Neural Network (BNN) Operators""" from __future__ import absolute_import as _abs import tvm from tvm import te from .. import tag from ..utils import simplify, get_const_int def binarize_pack(data, axis=None, name="PackedInput"): """Binarization and bit-packing along a certain axis. Parameters ---------- data : tvm.te.Tensor n-D input, can be any layout. axis : None or int The axis along which to do binarization and bit-packing, default is the last axis. name : str, optional The name prefix operators generate. Returns ------- output : tvm.te.Tensor n-D, the same layout as input, dtype is uint32. """ ishape = data.shape if axis is None: axis = len(ishape) - 1 assert get_const_int(ishape[axis]) % 32 == 0 n = len(ishape) oshape = tuple(simplify(ishape[i] // 32) if i == axis else ishape[i] for i in range(n)) def _binarize_pack(*indices): start_idx = [indices[i] * 32 if i == axis else indices[i] for i in range(n)] packed = tvm.tir.const(0, "uint32") for j in range(32): idx = [start_idx[i] + j if i == axis else start_idx[i] for i in range(n)] sign = (data(*idx) >= 0).astype("uint32") packed = packed | sign if j == 31: return packed packed = packed << 1 raise RuntimeError("not resach") return te.compute(oshape, _binarize_pack, name=name, tag="binarize_pack") def binary_dense(data, weight): """Binary matrix multiplication using xor and bit-count. Parameters ---------- data : tvm.te.Tensor 2-D with shape [batch, in_dim], dtype is uint32. weight : tvm.te.Tensor 2-D with shape [out_dim, in_dim], dtype is uint32. Returns ------- output : tvm.te.Tensor 2-D with shape [batch, out_dim], dtype is float32. """ assert ( data.dtype == "uint32" and weight.dtype == "uint32" ), "dtype of data and weight should be uint32" assert len(data.shape) == 2 and len(weight.shape) == 2, "only support 2-dim binary dense" batch, in_dim = data.shape out_dim, _ = weight.shape k = te.reduce_axis((0, in_dim), name="k") matmul = te.compute( (batch, out_dim), lambda i, j: te.sum(tvm.tir.popcount(data[i, k] ^ weight[j, k]), axis=k), tag="binary_dense", ) return te.compute( (batch, out_dim), lambda i, j: 32 * in_dim - 2.0 * matmul(i, j), tag=tag.ELEMWISE )
https://github.com/zk-ml/tachikoma
python/tvm/topi/nn/conv1d.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=invalid-name, unused-variable, unused-argument """1D convolution operators.""" from .conv2d import conv def conv1d( data, kernel, strides=1, padding="VALID", dilation=1, data_layout="NCW", kernel_layout="", out_dtype=None, ): """1D convolution forward operator. Parameters ---------- data : tvm.te.Tensor 3-D input shape [batch, in_channel, in_width] for data_layout == 'NCW' and [batch, in_width, in_channel] for data_layout == 'NWC' kernel : tvm.te.Tensor 3-D kernel with shape [num_filter, in_channel, filter_size] for kernel_layout == 'OIW' and [filter_size, in_channel, num_filter] for kernel_layout == 'WIO' strides : int or tuple The spatial stride along width padding : int or str Padding size, or ['VALID', 'SAME'] dilation : int or tuple Dilation rate if convolution should be dilated. data_layout : str How input data is laid out, must be one of ['NCW', 'NWC'] kernel_layout: Optiona[str] The layout of the kernel. If unspecified, use default layout. "OIW" if data_layout == "NCW", "WIO" if data_layout == "NWC". out_dtype : str The output data type. If None then output is same type as input. """ return conv(data, kernel, strides, padding, dilation, 1, data_layout, kernel_layout, out_dtype) def conv1d_nwc(data, kernel, strides=1, padding="VALID", dilation=1, out_dtype=None): """1D convolution in NWC layout. See :py:func:`conv` for details on parameters""" return conv(data, kernel, strides, padding, dilation, 1, "NWC", "WIO", out_dtype=out_dtype) def conv1d_ncw(data, kernel, strides=1, padding="VALID", dilation=1, out_dtype=None): """1D convolution in NCW layout. See :py:func:`conv` for details on parameters""" return conv(data, kernel, strides, padding, dilation, 1, "NCW", "OIW", out_dtype=out_dtype) def group_conv1d_nwc( data, kernel, strides=1, padding="VALID", dilation=1, groups=1, out_dtype=None ): """1D convolution forward operator for NWC layout. Parameters ---------- data : tvm.te.Tensor 3-D with shape [batch, in_width, in_channel] kernel : tvm.te.Tensor 3-D with shape [filter_size, in_channel, num_filter] strides : int or tuple The spatial stride along width padding : int, tuple, or str Padding size can be an integer for equal padding, a tuple of (left, right) or a string in ['VALID', 'SAME']. dilation : int or tuple Dilation rate if convolution should be dilated. groups : int Number of groups out_dtype : str The output data type. If None then output is same type as input. """ return conv(data, kernel, strides, padding, dilation, groups, "NWC", "WIO", out_dtype=out_dtype) def group_conv1d_ncw( data, kernel, strides=1, padding="VALID", dilation=1, groups=1, out_dtype=None ): """1D convolution forward operator for NCW layout. Parameters ---------- data : tvm.te.Tensor 3-D with shape [batch, in_channel, in_width] kernel : tvm.te.Tensor 3-D with shape [num_filter, in_channel, filter_size] strides : int or tuple The spatial stride along width padding : int, tuple, or str Padding size can be an integer for equal padding, a tuple of (left, right) or a string in ['VALID', 'SAME']. dilation : int or tuple Dilation rate if convolution should be dilated. groups : int Number of groups out_dtype : str The output data type. If None then output is same type as input. """ return conv(data, kernel, strides, padding, dilation, groups, "NCW", "OIW", out_dtype=out_dtype)
https://github.com/zk-ml/tachikoma
python/tvm/topi/nn/conv1d_transpose.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=invalid-name, unused-variable, unused-argument """Transposed 1D convolution operators (sometimes called Deconvolution).""" from tvm import te from .dilate import dilate from .pad import pad from ..utils import simplify from .utils import get_pad_tuple1d def conv1d_transpose_ncw(data, kernel, stride, padding, out_dtype, output_padding): """Transposed 1D convolution ncw forward operator. Parameters ---------- data : tvm.te.Tensor 3-D with shape [batch, in_channel, in_width] kernel : tvm.te.Tensor 3-D with shape [in_channel, num_filter, filter_width] stride : ints The spatial stride along width padding : int or str Padding size, or ['VALID', 'SAME'] out_dtype : str The output data type. This is used for mixed precision. output_padding : ints Used to recover the actual output shape in case there are more than one possible shape. Must be smaller than stride. Returns ------- output : tvm.te.Tensor 3-D with shape [batch, out_channel, out_width] """ # dilate and pad if isinstance(stride, (tuple, list)): stride = stride[0] if isinstance(output_padding, (tuple, list)): output_padding = output_padding[0] batch, channels_in, data_width = data.shape _, channels_out, kernel_width = kernel.shape assert output_padding < stride channels_out = simplify(channels_out) data = dilate(data, [1, 1, stride], name="data_dilate") pad_left, pad_right = get_pad_tuple1d(padding, (kernel_width,)) pad_left = kernel_width - 1 - pad_left pad_right = kernel_width - 1 - pad_right + output_padding data = pad(data, [0, 0, pad_left], [0, 0, pad_right], name="data_pad") # transpose kernel, switch kernel layout to IOW kernel = te.compute( (channels_out, channels_in, kernel_width), lambda o, i, w: kernel[i][o][kernel_width - 1 - w], name="kernel", ) # convolution _, _, data_width = data.shape out_w = simplify(data_width - kernel_width + 1) dc = te.reduce_axis((0, channels_in), name="dc") dw = te.reduce_axis((0, kernel_width), name="dw") output = te.compute( (batch, channels_out, out_w), lambda b, c, w: te.sum( data[b, dc, w + dw].astype(out_dtype) * kernel[c, dc, dw].astype(out_dtype), axis=[dc, dw], ), tag="conv1d_transpose_ncw", ) return output
https://github.com/zk-ml/tachikoma
python/tvm/topi/nn/conv2d.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=invalid-name, unused-variable, too-many-locals # pylint: disable=unused-argument, redefined-builtin """Conv2D operators""" from __future__ import absolute_import as _abs import re from collections import namedtuple from typing import Optional, Sequence, Union import numpy as np import tvm from tvm import auto_scheduler, te from ..utils import get_const_int, get_const_tuple, simplify, tag from .pad import pad from .utils import get_pad_tuple, get_pad_tuple_generic from .winograd_util import winograd_transform_matrices # workload description of conv2d Workload = namedtuple( "Workload", [ "in_dtype", "out_dtype", "height", "width", "in_filter", "groups", "out_filter", "kernel_h", "kernel_w", "padt", "padl", "padb", "padr", "dilation_h", "dilation_w", "stride_h", "stride_w", ], ) def conv2d( input, filter, strides, padding, dilation, data_layout="NCHW", kernel_layout="", out_dtype=None ): """Conv2D operator. Parameters ---------- input : tvm.te.Tensor 4-D with shape [batch, in_channel, in_height, in_width] in data_layout filter : tvm.te.Tensor 4-D with shape [num_filter, in_channel, filter_height, filter_width] in kernel_layout strides : int or a list/tuple of two ints stride size, or [stride_height, stride_width] padding : int or a list/tuple of 2 or 4 ints padding size, or [pad_height, pad_width] for 2 ints, or [pad_top, pad_left, pad_bottom, pad_right] for 4 ints dilation: int or a list/tuple of two ints dilation size, or [dilation_height, dilation_width] data_layout : str layout of data kernel_layout : Optional[str] layout of kernel. If unspecified, use default layout inferred from data_layout. "OIHW" if data_layout == "NCHW", "HWIO" if data_layout == "NHWC". Returns ------- output : tvm.te.Tensor 4-D with shape [batch, out_channel, out_height, out_width] """ # search platform specific declaration first # default declaration return conv(input, filter, strides, padding, dilation, 1, data_layout, kernel_layout, out_dtype) @tvm.target.generic_func def conv2d_legalize(attrs, inputs, types): """Legalizes Conv2D op. Parameters ---------- attrs : tvm.ir.Attrs Attributes of current convolution inputs : list of tvm.relay.Expr The args of the Relay expr to be legalized types : list of types List of input and output types Returns ------- result : tvm.relay.Expr The legalized expr """ # not to change by default return None @tvm.target.generic_func def conv2d_alter_layout(attrs, inputs, tinfos, out_type): """Change Conv2D layout. Parameters ---------- attrs : tvm.ir.Attrs Attributes of current convolution inputs : tvm.relay.Expr Grouped input symbols tinfos : list Input shape and dtype out_type: type The output type Note ---- Unlike other TOPI functions, this function operates on both graph level and operator level. """ # not to change by default return None @tvm.target.generic_func def conv2d_infer_layout(workload, cfg): """Infer input/output shapes and layouts from a workload and cfg. Parameters ---------- workload : tuple conv2d workload cfg : tuple tvm.autotvm config Returns ------- Output : [tuple of tuple and str, tuple of tuple and str] Input shapes and layouts, and output shapes and layouts """ raise ValueError("missing register for topi.nn.conv2d_infer_layout") def _get_workload(data, kernel, stride, padding, dilation, out_dtype, data_layout="NCHW"): """Get the workload structure.""" if data_layout == "NCHW": _, CI, IH, IW = get_const_tuple(data.shape) elif data_layout == "NHWC": _, IH, IW, CI = get_const_tuple(data.shape) elif data_layout == "HWCN": IH, IW, CI, _ = get_const_tuple(data.shape) else: raise ValueError("not support this layout {} yet".format(data_layout)) if data_layout == "NCHW": CO, CIG, KH, KW = get_const_tuple(kernel.shape) else: KH, KW, CIG, CO = get_const_tuple(kernel.shape) dilation_h, dilation_w = ( dilation if isinstance(dilation, (tuple, list)) else (dilation, dilation) ) pt, pl, pb, pr = get_pad_tuple( padding, (get_const_int((KH - 1) * dilation_h + 1), get_const_int((KW - 1) * dilation_w + 1)), ) GRPS = CI // CIG if isinstance(stride, (tuple, list)): HSTR, WSTR = stride else: HSTR, WSTR = stride, stride assert (data.dtype == kernel.dtype) or ( data.dtype == "uint8" and kernel.dtype == "int8" ), "Do not support inputs with different data types now. ' \ '{} vs. {}".format( data.dtype, kernel.dtype ) return Workload( data.dtype, out_dtype, IH, IW, CI, GRPS, CO, KH, KW, pt, pl, pb, pr, dilation_h, dilation_w, HSTR, WSTR, ) def conv2d_nchw(Input, Filter, stride, padding, dilation, out_dtype=None): """Convolution operator in NCHW layout. Parameters ---------- Input : tvm.te.Tensor 4-D with shape [batch, in_channel, in_height, in_width] Filter : tvm.te.Tensor 4-D with shape [num_filter, in_channel, filter_height, filter_width] stride : int or a list/tuple of two ints Stride size, or [stride_height, stride_width] padding : int or a list/tuple of 2 or 4 ints padding size, or [pad_height, pad_width] for 2 ints, or [pad_top, pad_left, pad_bottom, pad_right] for 4 ints dilation: int or a list/tuple of two ints dilation size, or [dilation_height, dilation_width] Returns ------- Output : tvm.te.Tensor 4-D with shape [batch, out_channel, out_height, out_width] """ return conv(Input, Filter, stride, padding, dilation, 1, "NCHW", "OIHW", out_dtype=out_dtype) def conv2d_hwcn(Input, Filter, stride, padding, dilation, out_dtype=None): """Convolution operator in HWCN layout. Parameters ---------- Input : tvm.te.Tensor 4-D with shape [in_height, in_width, in_channel, batch] Filter : tvm.te.Tensor 4-D with shape [filter_height, filter_width, in_channel, num_filter] stride : int or a list/tuple of two ints Stride size, or [stride_height, stride_width] padding : int or a list/tuple of 2 or 4 ints padding size, or [pad_height, pad_width] for 2 ints, or [pad_top, pad_left, pad_bottom, pad_right] for 4 ints dilation: int or a list/tuple of two ints dilation size, or [dilation_height, dilation_width] Returns ------- output : tvm.te.Tensor 4-D with shape [out_height, out_width, out_channel, batch] """ return conv(Input, Filter, stride, padding, dilation, 1, "HWCN", "HWIO", out_dtype=out_dtype) def conv2d_nhwc( Input, Filter, stride, padding, dilation, out_dtype="float32", auto_scheduler_rewritten_layout="", meta_schedule_original_shape=None, ): """Convolution operator in NHWC layout. Parameters ---------- Input : tvm.te.Tensor 4-D with shape [batch, in_height, in_width, in_channel] Filter : tvm.te.Tensor 4-D with shape [filter_height, filter_width, in_channel, num_filter] stride : int or a list/tuple of two ints Stride size, or [stride_height, stride_width] padding : int or a list/tuple of 2 or 4 ints padding size, or [pad_height, pad_width] for 2 ints, or [pad_top, pad_left, pad_bottom, pad_right] for 4 ints dilation: int or a list/tuple of two ints dilation size, or [dilation_height, dilation_width] out_dtype: str = "float32", The type of output tensor auto_scheduler_rewritten_layout: str = "" The layout after auto-scheduler's layout rewrite pass. meta_schedule_original_shape: Optional[List[PrimExpr]] = None The original shape of the input tensor. Returns ------- output : tvm.te.Tensor 4-D with shape [batch, out_height, out_width, out_channel] """ return conv( Input, Filter, stride, padding, dilation, 1, "NHWC", "HWIO", out_dtype, auto_scheduler_rewritten_layout, meta_schedule_original_shape, auto_scheduler_should_rewrite_layout=True, ) def conv2d_NCHWc(data, kernel, stride, padding, dilation, layout, out_layout, out_dtype="float32"): """Conv2D operator for nChw[x]c layout. Parameters ---------- data : tvm.te.Tensor 5-D with shape [batch, in_channel_chunk, in_height, in_width, in_channel_block] kernel : tvm.te.Tensor 6-D with shape [num_filter_chunk, in_channel_chunk, filter_height, filter_width, in_channel_block, num_filter_block] stride : int or a list/tuple of two ints stride size, or [stride_height, stride_width] padding : int or a list/tuple of 2 or 4 ints padding size, or [pad_height, pad_width] for 2 ints, or [pad_top, pad_left, pad_bottom, pad_right] for 4 ints dilation: int or a list/tuple of two ints dilation size, or [dilation_height, dilation_width] layout : str Input data layout out_layout : str Output data layout out_dtype : str output data type Returns ------- output : tvm.te.Tensor 5-D with shape [batch, out_channel_chunk, out_height, out_width, out_channel_block] """ # layout and out_layout are not used here, # we keep them for debug convenience when dumping autotvm workload HSTR, WSTR = stride if isinstance(stride, (tuple, list)) else (stride, stride) dilation_h, dilation_w = ( dilation if isinstance(dilation, (tuple, list)) else (dilation, dilation) ) n, ic_chunk, ih, iw, ic_bn = get_const_tuple(data.shape) in_channel = ic_chunk * ic_bn target = tvm.target.Target.current(allow_none=False) oc_chunk, ic_chunk_group, kernel_height, kernel_width, _, oc_bn = get_const_tuple(kernel.shape) num_filter = oc_chunk * oc_bn groups = ic_chunk // ic_chunk_group dilated_kernel_h = (kernel_height - 1) * dilation_h + 1 dilated_kernel_w = (kernel_width - 1) * dilation_w + 1 pad_top, pad_left, pad_down, pad_right = get_pad_tuple( padding, (dilated_kernel_h, dilated_kernel_w) ) HPAD = pad_top + pad_down WPAD = pad_left + pad_right # output shape out_height = (ih + HPAD - dilated_kernel_h) // HSTR + 1 out_width = (iw + WPAD - dilated_kernel_w) // WSTR + 1 oshape = (n, oc_chunk, out_height, out_width, oc_bn) pad_before = (0, 0, pad_top, pad_left, 0) pad_after = (0, 0, pad_down, pad_right, 0) # DOPAD DOPAD = HPAD != 0 or WPAD != 0 if DOPAD: data_pad = pad(data, pad_before, pad_after, name="data_pad") else: data_pad = data ic = te.reduce_axis((0, in_channel), name="ic") kh = te.reduce_axis((0, kernel_height), name="kh") kw = te.reduce_axis((0, kernel_width), name="kw") idxdiv = tvm.tir.indexdiv idxmod = tvm.tir.indexmod return te.compute( oshape, lambda n, oc_chunk, oh, ow, oc_block: te.sum( data_pad[ n, idxdiv(ic, ic_bn), oh * HSTR + kh * dilation_h, ow * WSTR + kw * dilation_w, idxmod(ic, ic_bn), ].astype(out_dtype) * kernel[oc_chunk, idxdiv(ic, ic_bn), kh, kw, idxmod(ic, ic_bn), oc_block].astype( out_dtype ), axis=[ic, kh, kw], ), name="conv2d_NCHWc", tag="conv2d_NCHWc", ) def conv2d_NCHWc_int8( data, kernel, stride, padding, dilation, layout, out_layout, out_dtype="int32", n_elems=4 ): """Conv2D operator for nChw[x]c layout. Parameters ---------- data : tvm.te.Tensor 5-D with shape [batch, in_channel_chunk, in_height, in_width, in_channel_block] kernel : tvm.te.Tensor 7-D with shape [num_filter_chunk, in_channel_chunk, filter_height, filter_width, in_channel_block/4, num_filter_block, 4] stride : int or a list/tuple of two ints stride size, or [stride_height, stride_width] padding : int or a list/tuple of 2 or 4 ints padding size, or [pad_height, pad_width] for 2 ints, or [pad_top, pad_left, pad_bottom, pad_right] for 4 ints dilation: int or a list/tuple of two ints dilation size, or [dilation_height, dilation_width] layout : str Input data layout out_layout : str Output data layout out_dtype : str output data type n_elems : int numer of int8 elements accumulated Returns ------- output : tvm.te.Tensor 5-D with shape [batch, out_channel_chunk, out_height, out_width, out_channel_block] """ # layout and out_layout are not used here, # we keep them for debug convenience when dumping autotvm workload HSTR, WSTR = stride if isinstance(stride, (tuple, list)) else (stride, stride) dilation_h, dilation_w = ( dilation if isinstance(dilation, (tuple, list)) else (dilation, dilation) ) n, ic_chunk, ih, iw, ic_bn = get_const_tuple(data.shape) in_channel = ic_chunk * ic_bn oc_chunk, ic_chunk_group, kernel_height, kernel_width, _, oc_bn, _ = get_const_tuple( kernel.shape ) groups = ic_chunk // ic_chunk_group dilated_kernel_h = (kernel_height - 1) * dilation_h + 1 dilated_kernel_w = (kernel_width - 1) * dilation_w + 1 pad_top, pad_left, pad_down, pad_right = get_pad_tuple( padding, (dilated_kernel_h, dilated_kernel_w) ) HPAD = pad_top + pad_down WPAD = pad_left + pad_right # output shape out_height = (ih + HPAD - dilated_kernel_h) // HSTR + 1 out_width = (iw + WPAD - dilated_kernel_w) // WSTR + 1 oshape = (n, oc_chunk, out_height, out_width, oc_bn) pad_before = (0, 0, pad_top, pad_left, 0) pad_after = (0, 0, pad_down, pad_right, 0) # DOPAD DOPAD = HPAD != 0 or WPAD != 0 if DOPAD: data_pad = pad(data, pad_before, pad_after, name="data_pad") else: data_pad = data ic = te.reduce_axis((0, in_channel), name="ic") kh = te.reduce_axis((0, kernel_height), name="kh") kw = te.reduce_axis((0, kernel_width), name="kw") if groups == 1: ic_outer = te.reduce_axis((0, in_channel // ic_bn), name="ic_outer") ic_f_inner = te.reduce_axis((0, ic_bn // n_elems), name="ic_f_inner") ic_s_inner = te.reduce_axis((0, n_elems), name="ic_s_inner") return te.compute( oshape, lambda n, oc_chunk, oh, ow, oc_block: te.sum( data_pad[ n, ic_outer, oh * HSTR + kh * dilation_h, ow * WSTR + kw * dilation_w, ic_f_inner * n_elems + ic_s_inner, ].astype(out_dtype) * kernel[oc_chunk, ic_outer, kh, kw, ic_f_inner, oc_block, ic_s_inner].astype( out_dtype ), axis=[kh, kw, ic_outer, ic_f_inner, ic_s_inner], ), name="conv2d_NCHWc_int8", tag="conv2d_NCHWc_int8", attrs={"schedule_rule": "conv2d_NCHWc_int8"}, ) # for int8 group conv support ic_chunk = in_channel // ic_bn ic_outer = te.reduce_axis((0, ic_chunk // groups), name="ic_outer") ic_f_inner = te.reduce_axis((0, ic_bn // n_elems), name="ic_f_inner") ic_s_inner = te.reduce_axis((0, n_elems), name="ic_s_inner") oshape = (n, oc_chunk, out_height, out_width, oc_bn) return te.compute( oshape, lambda n, occ, oh, ow, oc_block: te.sum( data_pad[ n, (occ * oc_bn // (oc_chunk * oc_bn // groups)) * (ic_chunk // groups) + ic_outer, oh * HSTR + kh, ow * WSTR + kw, ic_f_inner * n_elems + ic_s_inner, ].astype(out_dtype) * kernel[occ, ic_outer, kh, kw, ic_f_inner, oc_block, ic_s_inner].astype(out_dtype), axis=[kh, kw, ic_outer, ic_f_inner, ic_s_inner], ), name="conv2d_NCHWc_int8", tag="conv2d_NCHWc_int8", attrs={"schedule_rule": "conv2d_NCHWc_int8"}, ) def conv2d_gemm_weight_transform(kernel, tile_rows, tile_cols): """Weight transformation for winograd Parameters ---------- kernel: Tensor The raw kernel tensor with layout "NHWC". tile_rows: int Tile rows of the weight transformation for ConvGemm. tile_cols: int Tile columns of the weight transformation for ConvGemm. Returns ------- output : tvm.te.Tensor 2-D with shape [CI*KH*KW,CO] """ KH, KW, IC, OC = get_const_tuple(kernel.shape) K = KH * KW * IC N = OC kernel_flat = te.compute( (K, N), lambda x, y: kernel[(x // IC) // KW, (x // IC) % KW, x % IC, y], "weight_flatten" ) pad_K = 0 pad_N = 0 if N % tile_rows != 0: pad_N = tile_rows - (N % tile_rows) if K % tile_cols != 0: pad_K = tile_cols - (K % tile_cols) N_padded = N + pad_N K_padded = K + pad_K if pad_K != 0 or pad_N != 0: kernel_flat = pad( kernel_flat, pad_before=(0, 0), pad_after=(pad_K, pad_N), name="weight_padding" ) return te.compute( (N_padded // tile_rows, K_padded // tile_cols, tile_rows, tile_cols), lambda x, y, z, w: kernel_flat[w + tile_cols * y, z + tile_rows * x], name="weight_block_reshape", ) def conv2d_winograd_weight_transform(kernel, tile_size): """Weight transformation for winograd Parameters ---------- kernel: Tensor The raw kernel tensor with layout "NCHW". tile_size: int Tile size of winograd transform. e.g. 2 for F(2x2, 3x3) and 4 for F(4x4, 3x3) Returns ------- output : tvm.te.Tensor 4-D with shape [alpha, alpha, CO, CI] """ shape = get_const_tuple(kernel.shape) assert shape[2] == shape[3], "Only support NxN kernel" K = shape[3] r = tile_size + K - 1 shape = (r, r) + shape[:2] _, _, G = winograd_transform_matrices(tile_size, K, kernel.dtype) r_kh = te.reduce_axis((0, K), name="r_kh") r_kw = te.reduce_axis((0, K), name="r_kw") return te.compute( shape, lambda eps, nu, co, ci: te.sum( kernel[co][ci][r_kh][r_kw] * G[eps][r_kh] * G[nu][r_kw], axis=[r_kh, r_kw] ), name="transform_weight", ) def conv2d_winograd_nnpack_weight_transform(kernel, convolution_algorithm, out_dtype): """Weight transformation for winograd Parameters ---------- kernel: Tensor The raw kernel tensor with layout "NCHW". Only 3x3 kernel is supported for now. convolution_algorithm: int The convolution algorithm for Winograd NNPACK. Returns ------- output : tvm.te.Tensor 4-D with shape [alpha, alpha, CO, CI] """ # pylint: disable=import-outside-toplevel from tvm.contrib import nnpack return nnpack.convolution_inference_weight_transform( kernel, algorithm=convolution_algorithm, dtype=out_dtype ) def group_conv2d_nchw(Input, Filter, stride, padding, dilation, groups, out_dtype=None): """Group convolution operator in NCHW layout. Parameters ---------- Input : tvm.te.Tensor 4-D with shape [batch, in_channel, in_height, in_width] Filter : tvm.te.Tensor 4-D with shape [num_filter, in_channel // groups, filter_height, filter_width] stride : int or a list/tuple of two ints Stride size, or [stride_height, stride_width] padding : int or a list/tuple of 2 or 4 ints padding size, or [pad_height, pad_width] for 2 ints, or [pad_top, pad_left, pad_bottom, pad_right] for 4 ints dilation : int or a list/tuple of two ints dilation size, or [dilation_height, dilation_width] groups : int number of groups out_dtype : str The output type. This is used for mixed precision. Returns ------- Output : tvm.te.Tensor 4-D with shape [batch, out_channel, out_height, out_width] """ return conv( Input, Filter, stride, padding, dilation, groups, "NCHW", "OIHW", out_dtype=out_dtype ) def conv( inp: te.Tensor, filt: te.Tensor, stride: Union[int, Sequence[int]], padding: Union[int, Sequence[int]], dilation: Union[int, Sequence[int]], groups: int, data_layout: str, kernel_layout: str = "", out_dtype: Union[str, None] = None, auto_scheduler_rewritten_layout: Optional[str] = None, meta_schedule_original_shape=None, auto_scheduler_should_rewrite_layout: bool = False, ): """Convolution operator in NCHW or NHWC layout. Supports 1D, 2D, 3D, ... and grouping. Parameters ---------- inp : tvm.te.Tensor N-D with shape [batch, in_channel, in_height, in_width, ...] in `data_layout` filt : tvm.te.Tensor N-D with shape [num_filter, in_channel // groups, filter_height, filter_width, ...] in `kernel_layout` stride : int or a list/tuple of dim ints (where dim=2 for NCHW, dim=1 for NCH, etc.) Stride size, or [stride_height, stride_width, ...] padding : int or a list/tuple of dim or 2*dim ints (where dim=2 for NCHW, dim=1 for NCH, etc.) padding size, or [pad_height, pad_width, ...] for dim ints, or [pad_top, pad_left, pad_bottom, pad_right] for 2*dim ints dilation : int or a list/tuple of two ints dilation size, or [dilation_height, dilation_width] groups : int number of groups data_layout : str Layout of the input. N indicates batch dimension, C indicates channels, any other character indicates HW (or H or HWD for 1D and 3D). kernel_layout: Optional[str] Layout of the filter. I indicates input channels, O indicates output channels, any other character indicates HW dimension of the filter (or H or HWD for 1D and 3D). If kernel_layout is empty, use data_layout to infer the default kernel_layout. Default kernel_layout is OIHW for NCHW data layout, HWIO for NHWC data layout. out_dtype : str Elements are converted to this type before elementwise multiplication and summation. auto_scheduler_rewritten_layout: str Layout from autoscheduler's layout rewritting. meta_schedule_original_shape : Optional[List[PrimExpr]] The original shape of the input tensor. auto_scheduler_should_rewrite_layout : bool Should auto scheduler be allowed to rewrite the layout of the filter tensor. Defaults to false. This can cause errors if used with grouped convs. Returns ------- Output : tvm.te.Tensor N-D with shape [batch, out_channel, out_height, out_width, ...] in `data_layout` """ dim = len(inp.shape) - 2 if out_dtype is None: out_dtype = inp.dtype assert isinstance(stride, int) or len(stride) == dim assert isinstance(dilation, int) or len(dilation) == dim if isinstance(stride, int): strides = [stride for _ in range(dim)] else: strides = stride if isinstance(dilation, int): dilations = [dilation for _ in range(dim)] else: dilations = list(dilation) # transform from data_layout to NCHW data_permutation_to = [data_layout.find("N"), data_layout.find("C")] + [ x.span()[0] for x in re.finditer("[^NC]", data_layout) ] # transform from NCHW to data_layout data_permutation_from = np.argsort(data_permutation_to) # transform from CHW to data_layout data_permutation_from_reductions = data_permutation_from[1:].copy() data_permutation_from_reductions[ data_permutation_from_reductions > data_permutation_from[0] ] -= 1 if kernel_layout == "": # kernel permutation, if C appears before HW then num_filter is first, otherwise it is last # tkonolige: I don't really understand kernel ordering for NHWC, it seems # like num_filters should match the N dimension if data_layout.find("C") < re.search("[^NC]", data_layout).span()[0]: kernel_permutation_to = [0, 1] + list(range(2, dim + 2)) else: kernel_permutation_to = [dim + 1, dim] + list(range(dim)) else: # transform from kernel_layout to OIHW kernel_permutation_to = [kernel_layout.find("O"), kernel_layout.find("I")] + [ x.span()[0] for x in re.finditer("[^OI]", kernel_layout) ] # transform from OIHW to kernel_layout kernel_permutation_from = np.argsort(kernel_permutation_to) if meta_schedule_original_shape: auto_scheduler.rewrite_tensor_shape(filt, meta_schedule_original_shape) batch, in_channel, *dimensions = np.array(get_const_tuple(inp.shape))[ data_permutation_to ].tolist() num_filter, _, *kernel_dimensions = np.array(get_const_tuple(filt.shape))[ kernel_permutation_to ].tolist() # Autoscheduler may have messed with the input layout, so we extract the # dimensions that it gives us if auto_scheduler_rewritten_layout: num_filter, _, *kernel_dimensions = auto_scheduler.get_shape_from_rewritten_layout( auto_scheduler_rewritten_layout, ["ff", "rc"] + [f"r{i}" for i in ["y", "x", "z"][: len(kernel_dimensions)]], ) auto_scheduler.remove_index_check(filt) assert in_channel % groups == 0, "input channels must divide group size" assert num_filter % groups == 0, "output channels must divide group size" dilated_kernel_dimensions = [(k - 1) * dil + 1 for k, dil in zip(kernel_dimensions, dilations)] pad_begin, pad_end = get_pad_tuple_generic(padding, dilated_kernel_dimensions) # compute the output shape out_channel = num_filter out_dimensions = [ simplify(d - (k - 1) * dil - 1 + pb + pe) // stride + 1 for d, k, dil, pb, pe, stride in zip( dimensions, kernel_dimensions, dilations, pad_begin, pad_end, strides ) ] # compute graph pad_before = list(np.array([0, 0] + pad_begin)[data_permutation_from]) pad_after = list(np.array([0, 0] + pad_end)[data_permutation_from]) temp = pad(inp, pad_before, pad_after, name="pad_temp") rc = te.reduce_axis((0, in_channel // groups), name="rc") rs = [te.reduce_axis((0, k), name=f"r{i}") for i, k in zip(["y", "x", "z"], kernel_dimensions)] def compute(*args): nn, ff, *dim_indices = list(np.array(args)[data_permutation_to]) if groups == 1: simplified_channel_index = rc else: simplified_channel_index = ff // (num_filter // groups) * (in_channel // groups) + rc return te.sum( temp.__getitem__( tuple( np.array( [nn, simplified_channel_index] + [ di * stride + r * dil for di, stride, r, dil in zip(dim_indices, strides, rs, dilations) ] )[data_permutation_from] ) ).astype(out_dtype) * filt.__getitem__(tuple(np.array([ff, rc] + rs)[kernel_permutation_from])).astype( out_dtype ), # Schedules depend on reduction axes being in the same order as the # layout, so we reorder here. axis=np.array([rc, *rs])[data_permutation_from_reductions].tolist(), ) out = te.compute( list(np.array([batch, out_channel] + out_dimensions)[data_permutation_from]), compute, # tag is expected to be lowercase tag=f"{'group_' if groups > 1 else ''}conv{dim}d_{data_layout.lower()}", name=f"{'group_' if groups > 1 else ''}conv{dim}d_{data_layout.lower()}", attrs={"layout_free_placeholders": [filt]} if auto_scheduler_should_rewrite_layout else {}, varargs_names=list(np.array(["nn", "ff", "yy", "xx", "zz"])[data_permutation_from]), ) # if we used autoscheduler's changed layout we need to rewrite the ordering # of the output dimensions if auto_scheduler_rewritten_layout: out = auto_scheduler.rewrite_compute_body(out, auto_scheduler_rewritten_layout) return out def group_conv2d_nhwc(Input, Filter, stride, padding, dilation, groups, out_dtype=None): """Group convolution operator in NHWC layout. Parameters ---------- Input : tvm.te.Tensor 4-D with shape [batch, in_height, in_width, in_channel, ...] Filter : tvm.te.Tensor 4-D with shape [filter_height, filter_width, in_channel // groups, num_filter] stride : int or a list/tuple of two ints Stride size, or [stride_height, stride_width] padding : int or a list/tuple of 2 or 4 ints padding size, or [pad_height, pad_width] for 2 ints, or [pad_top, pad_left, pad_bottom, pad_right] for 4 ints dilation : int or a list/tuple of two ints dilation size, or [dilation_height, dilation_width] groups : int number of groups out_dtype : str The output type. This is used for mixed precision. Returns ------- Output : tvm.te.Tensor 4-D with shape [batch, out_height, out_width, out_channel] """ return conv( Input, Filter, stride, padding, dilation, groups, "NHWC", "HWIO", out_dtype=out_dtype ) def unpack_NCHWc_to_nchw(packed_out, out_dtype): """Unpack conv2d_NCHWc output from layout NCHWc to NCHW Parameters ---------- packed_out : tvm.te.Tensor The output tensor of conv2d_NCHWc. out_dtype : str The output dtype. Returns ------- unpacked_out : tvm.te.Tensor The unpacked output tensor in NCHW layout. """ n, oc_chunk, oh, ow, oc_bn = get_const_tuple(packed_out.shape) idxmod = tvm.tir.indexmod idxdiv = tvm.tir.indexdiv oshape = (n, oc_chunk * oc_bn, oh, ow) unpacked_out = te.compute( oshape, lambda n, c, h, w: packed_out[n, idxdiv(c, oc_bn), h, w, idxmod(c, oc_bn)].astype( out_dtype ), name="output_unpack", tag=tag.INJECTIVE + ",unpack_nchwc", ) return unpacked_out @tvm.target.generic_func def conv2d_winograd_nhwc( data, weight, strides, padding, dilation, out_dtype, pre_computed=False, auto_scheduler_rewritten_layout="", meta_schedule_original_shape=None, ): """Conv2D Winograd in NHWC layout. This is a clean version to be used by the auto-scheduler for both CPU and GPU. Parameters ---------- data : tvm.te.Tensor 4-D with shape [batch, in_height, in_width, in_channel] weight : tvm.te.Tensor 4-D with shape [filter_height, filter_width, in_channel, num_filter] strides : int or a list/tuple of two ints stride size, or [stride_height, stride_width] padding : int or a list/tuple of two ints padding size, or [pad_height, pad_width] dilation: int or a list/tuple of two ints dilation size, or [dilation_height, dilation_width] out_dtype : str, optional Specifies the output data type. pre_computed: bool Whether the kernel is precomputed auto_scheduler_rewritten_layout: str = "" The layout after auto-scheduler's layout rewrite pass. meta_schedule_original_shape: Optional[List[PrimExpr]] = None The original shape of the input tensor. Returns ------- output : tvm.te.Tensor 4-D with shape [batch, out_height, out_width, out_channel] """ tile_size = 4 return _conv2d_winograd_nhwc_impl( data, weight, strides, padding, dilation, out_dtype, tile_size, pre_computed=pre_computed, write_cache_level=2, auto_scheduler_rewritten_layout=auto_scheduler_rewritten_layout, meta_schedule_original_shape=meta_schedule_original_shape, ) @tvm.target.generic_func def conv2d_winograd_nchw( data, weight, strides, padding, dilation, out_dtype, pre_computed=False, auto_scheduler_rewritten_layout="", meta_schedule_original_shape=None, ): """Conv2D Winograd in NCHW layout. This is a clean version to be used by the auto-scheduler for both CPU and GPU. Parameters ---------- data : tvm.te.Tensor 4-D with shape [batch, in_channel, in_height, in_width] weight : tvm.te.Tensor 4-D with shape [filter_height, filter_width, in_channel, num_filter] strides : int or a list/tuple of two ints stride size, or [stride_height, stride_width] padding : int or a list/tuple of two ints padding size, or [pad_height, pad_width] dilation: int or a list/tuple of two ints dilation size, or [dilation_height, dilation_width] out_dtype : str, optional Specifies the output data type. pre_computed: bool Whether the kernel is precomputed auto_scheduler_rewritten_layout: str = "" The layout after auto-scheduler's layout rewrite pass. meta_schedule_original_shape: Optional[List[PrimExpr]] = None The original shape of the input tensor. Returns ------- output : tvm.te.Tensor 4-D with shape [batch, out_height, out_width, out_channel] """ tile_size = 4 return _conv2d_winograd_nchw_impl( data, weight, strides, padding, dilation, out_dtype, tile_size, pre_computed, auto_scheduler_rewritten_layout, meta_schedule_original_shape, ) def _conv2d_winograd_nhwc_impl( data, weight, strides, padding, dilation, out_dtype, tile_size, pre_computed=False, write_cache_level=None, auto_scheduler_rewritten_layout="", meta_schedule_original_shape=None, ): """Conv2D Winograd implementation in NHWC layout. This is a clean version to be used by the auto-scheduler for both CPU and GPU. Parameters ---------- data : tvm.te.Tensor 4-D with shape [batch, in_height, in_width, in_channel] weight : tvm.te.Tensor 4-D with shape [filter_height, filter_width, in_channel, num_filter] strides : int or a list/tuple of two ints stride size, or [stride_height, stride_width] padding : int or a list/tuple of two ints padding size, or [pad_height, pad_width] dilation: int or a list/tuple of two ints dilation size, or [dilation_height, dilation_width] out_dtype : str, optional Specifies the output data type. tile_size : int The size of the tile to use for the Winograd filter pre_computed: bool = False Whether the kernel is precomputed write_cache_level: Optional[int] = None The cache level to write to in multi-level tiling rule in MetaSchedule. auto_scheduler_rewritten_layout: str = "" The layout after auto-scheduler's layout rewrite pass. meta_schedule_original_shape: Optional[List[PrimExpr]] = None The original shape of the input tensor. Returns ------- output : tvm.te.Tensor 4-D with shape [batch, out_height, out_width, out_channel] """ N, H, W, CI = get_const_tuple(data.shape) if isinstance(dilation, int): dilation_h = dilation_w = dilation else: dilation_h, dilation_w = dilation if meta_schedule_original_shape: auto_scheduler.rewrite_tensor_shape(weight, meta_schedule_original_shape) assert (dilation_h, dilation_w) == (1, 1), "Does not support dilation" if not pre_computed: KH, KW, CI, CO = get_const_tuple(weight.shape) else: if auto_scheduler_rewritten_layout: H_CAT, W_CAT, CO, CI = get_const_tuple( auto_scheduler.get_shape_from_rewritten_layout( auto_scheduler_rewritten_layout, ["eps", "nu", "co", "ci"] ) ) auto_scheduler.remove_index_check(weight) else: H_CAT, W_CAT, CO, CI = get_const_tuple(weight.shape) KH, KW = H_CAT - tile_size + 1, W_CAT - tile_size + 1 pad_t, pad_l, pad_b, pad_r = get_pad_tuple(padding, (KH, KW)) HSTR, WSTR = (strides, strides) if isinstance(strides, int) else strides assert HSTR == 1 and WSTR == 1 and KH == 3 and KW == 3 r = KW m = tile_size alpha = m + r - 1 A, B, G = winograd_transform_matrices(m, r, out_dtype) H = (H + pad_t + pad_b - KH) // HSTR + 1 W = (W + pad_l + pad_r - KW) // WSTR + 1 nH, nW = (H + m - 1) // m, (W + m - 1) // m P = N * nH * nW pad_extra = (nW - 1) * m + alpha - (H + pad_t + pad_b) data_pad = pad( data, (0, pad_t, pad_l, 0), (0, pad_b + pad_extra, pad_r + pad_extra, 0), name="data_pad", attrs={"schedule_rule": "None"}, ) if not pre_computed: r_kh = te.reduce_axis((0, KH), name="r_kh") r_kw = te.reduce_axis((0, KW), name="r_kw") kernel_pack = te.compute( (alpha, alpha, CO, CI), lambda eps, nu, co, ci: te.sum( weight[r_kh, r_kw, ci, co] * G[eps, r_kh] * G[nu, r_kw], axis=[r_kh, r_kw], ), name="kernel_pack", ) bgemm_attrs = {} else: kernel_pack = weight bgemm_attrs = {"layout_free_placeholders": [kernel_pack]} if write_cache_level is not None: if not isinstance(write_cache_level, int): bgemm_attrs["meta_schedule.write_cache_level"] = write_cache_level else: bgemm_attrs["meta_schedule.write_cache_level"] = [write_cache_level] # pack data tile input_tile = te.compute( (alpha, alpha, P, CI), lambda eps, nu, p, ci: data_pad[ p // (nH * nW), ((p // nW) % nH) * m + eps, (p % nW) * m + nu, ci, ], name="input_tile", attrs={"schedule_rule": "None"}, ) # transform data r_a = te.reduce_axis((0, alpha), "r_a") r_b = te.reduce_axis((0, alpha), "r_b") data_pack = te.compute( (alpha, alpha, P, CI), lambda eps, nu, p, ci: te.sum( input_tile[r_a, r_b, p, ci] * B[r_a, eps] * B[r_b, nu], axis=[r_a, r_b], ), name="data_pack", attrs={ "auto_scheduler_simplify_const_tensor_indices": ["eps", "nu", "r_a", "r_b"], "schedule_rule": "conv2d_nhwc_winograd_data_pack", }, ) # do batch gemm ci = te.reduce_axis((0, CI), name="ci") bgemm = te.compute( (alpha, alpha, P, CO), lambda eps, nu, p, co: te.sum( data_pack[eps, nu, p, ci] * kernel_pack[eps, nu, co, ci], axis=[ci], ), name="bgemm", attrs=bgemm_attrs, ) if auto_scheduler_rewritten_layout: bgemm = auto_scheduler.rewrite_compute_body(bgemm, auto_scheduler_rewritten_layout) # inverse transform r_a = te.reduce_axis((0, alpha), "r_a") r_b = te.reduce_axis((0, alpha), "r_b") inverse = te.compute( (m, m, P, CO), lambda vh, vw, p, co: te.sum( bgemm[r_a, r_b, p, co] * A[r_a, vh] * A[r_b, vw], axis=[r_a, r_b], ), name="inverse", attrs={ "auto_scheduler_simplify_const_tensor_indices": ["vh", "vw", "r_a", "r_b"], "schedule_rule": "conv2d_nhwc_winograd_inverse", }, ) # output output = te.compute( (N, H, W, CO), lambda n, h, w, co: inverse[ h % m, w % m, n * nH * nW + (h // m) * nW + (w // m), co, ], name="conv2d_winograd", ) return output def _conv2d_winograd_nchw_impl( data, weight, strides, padding, dilation, out_dtype, tile_size, pre_computed=False, write_cache_level=None, auto_scheduler_rewritten_layout="", meta_schedule_original_shape=None, ): """ write_cache_level: Optional[int] = None The cache level to write to in multi-level tiling rule in MetaSchedule. """ del auto_scheduler_rewritten_layout N, CI, H, W = get_const_tuple(data.shape) if isinstance(dilation, int): dilation_h = dilation_w = dilation else: dilation_h, dilation_w = dilation if meta_schedule_original_shape: auto_scheduler.rewrite_tensor_shape(weight, meta_schedule_original_shape) assert (dilation_h, dilation_w) == (1, 1), "Does not support dilation" HSTR, WSTR = (strides, strides) if isinstance(strides, int) else strides if not pre_computed: # kernel tensor is raw tensor, do strict check CO, CI, KH, KW = get_const_tuple(weight.shape) alpha = KW + tile_size - 1 assert HSTR == 1 and WSTR == 1 and KH == KW else: alpha, _, CI, CO = get_const_tuple(weight.shape) KH = KW = alpha + 1 - tile_size assert HSTR == 1 and WSTR == 1 and dilation_h == 1 and dilation_w == 1 pad_t, pad_l, pad_b, pad_r = get_pad_tuple(padding, (KH, KW)) assert HSTR == 1 and WSTR == 1 and KH == 3 and KW == 3 pt, pl, pb, pr = get_pad_tuple(padding, (KH, KW)) data_pad = pad( data, (0, 0, pt, pl), (0, 0, pb, pr), name="data_pad", ) r = KW m = tile_size A, B, G = winograd_transform_matrices(m, r, out_dtype) H = (H + pt + pb - KH) // HSTR + 1 W = (W + pl + pr - KW) // WSTR + 1 nH, nW = (H + m - 1) // m, (W + m - 1) // m P = N * nH * nW if isinstance(N, int) else nH * nW # transform kernel if not pre_computed: r_kh = te.reduce_axis((0, KH), name="r_kh") r_kw = te.reduce_axis((0, KW), name="r_kw") kernel_pack = te.compute( (alpha, alpha, CI, CO), lambda eps, nu, ci, co: te.sum( weight[co, ci, r_kh, r_kw] * G[eps, r_kh] * G[nu, r_kw], axis=[r_kh, r_kw], ), name="kernel_pack", ) bgemm_attrs = {} else: kernel_pack = weight bgemm_attrs = {"layout_free_placeholders": [kernel_pack]} if write_cache_level is not None: if not isinstance(write_cache_level, int): bgemm_attrs["meta_schedule.write_cache_level"] = write_cache_level else: bgemm_attrs["meta_schedule.write_cache_level"] = [write_cache_level] # pack data tile input_tile = te.compute( (CI, P, alpha, alpha), lambda ci, p, eps, nu: data_pad[ p // (nH * nW), ci, ((p // nW) % nH) * m + eps, (p % nW) * m + nu, ], name="input_tile", attrs={"schedule_rule": "None"}, ) # transform data r_a = te.reduce_axis((0, alpha), "r_a") r_b = te.reduce_axis((0, alpha), "r_b") data_pack = te.compute( (alpha, alpha, CI, P), lambda eps, nu, ci, p: te.sum( input_tile[ci, p, r_a, r_b] * B[r_a, eps] * B[r_b, nu], axis=[r_a, r_b], ), name="data_pack", attrs={ "schedule_rule": "conv2d_nchw_winograd_data_pack", }, ) # do batch gemm ci = te.reduce_axis((0, CI), name="ci") bgemm = te.compute( (alpha, alpha, CO, P), lambda eps, nu, co, p: te.sum( data_pack[eps, nu, ci, p] * kernel_pack[eps, nu, ci, co], axis=[ci], ), name="bgemm", attrs=bgemm_attrs, ) # inverse transform r_a = te.reduce_axis((0, alpha), "r_a") r_b = te.reduce_axis((0, alpha), "r_b") inverse = te.compute( (CO, P, m, m), lambda co, p, vh, vw: te.sum( bgemm[r_a, r_b, co, p] * A[r_a, vh] * A[r_b, vw], axis=[r_a, r_b], ), name="inverse", attrs={ "schedule_rule": "conv2d_nchw_winograd_inverse", }, ) # output output = te.compute( (N, CO, H, W), lambda n, co, h, w: inverse[ co, n * nH * nW + (h // m) * nW + (w // m), h % m, w % m, ], name="conv2d_winograd", ) return output def conv2d_winograd_nhwc_without_weight_transform( data, weight, strides, padding, dilation, out_dtype, auto_scheduler_rewritten_layout="", meta_schedule_original_shape=None, ): """Conv2D Winograd without layout transform in NHWC layout. This is a clean version to be used by the auto-scheduler for both CPU and GPU. Parameters ---------- data : tvm.te.Tensor 4-D with shape [batch, in_height, in_width, in_channel] weight : tvm.te.Tensor 4-D with shape [filter_height, filter_width, in_channel, num_filter] strides : int or a list/tuple of two ints stride size, or [stride_height, stride_width] padding : int or a list/tuple of two ints padding size, or [pad_height, pad_width] dilation: int or a list/tuple of two ints dilation size, or [dilation_height, dilation_width] out_dtype : str, optional Specifies the output data type. auto_scheduler_rewritten_layout: str = "" The layout after auto-scheduler's layout rewrite pass. meta_schedule_original_shape: Optional[List[PrimExpr]] = None The original shape of the input tensor. Returns ------- output : tvm.te.Tensor 4-D with shape [batch, out_height, out_width, out_channel] """ return conv2d_winograd_nhwc( data, weight, strides, padding, dilation, out_dtype, pre_computed=True, auto_scheduler_rewritten_layout=auto_scheduler_rewritten_layout, meta_schedule_original_shape=meta_schedule_original_shape, ) def conv2d_winograd_nchw_without_weight_transform( data, weight, strides, padding, dilation, out_dtype, auto_scheduler_rewritten_layout="", meta_schedule_original_shape=None, ): """Conv2D Winograd without layout transform in NCHW layout. This is a clean version to be used by meta-schedule for both CPU and GPU. Parameters ---------- data : tvm.te.Tensor 4-D with shape [batch, in_height, in_width, in_channel] weight : tvm.te.Tensor 4-D with shape [filter_height, filter_width, in_channel, num_filter] strides : int or a list/tuple of two ints stride size, or [stride_height, stride_width] padding : int or a list/tuple of two ints padding size, or [pad_height, pad_width] dilation: int or a list/tuple of two ints dilation size, or [dilation_height, dilation_width] out_dtype : str, optional Specifies the output data type. auto_scheduler_rewritten_layout: str = "" The layout after auto-scheduler's layout rewrite pass. meta_schedule_original_shape: Optional[List[PrimExpr]] = None The original shape of the input tensor. Returns ------- output : tvm.te.Tensor 4-D with shape [batch, out_height, out_width, out_channel] """ return conv2d_winograd_nchw( data, weight, strides, padding, dilation, out_dtype, pre_computed=True, auto_scheduler_rewritten_layout=auto_scheduler_rewritten_layout, meta_schedule_original_shape=meta_schedule_original_shape, )
https://github.com/zk-ml/tachikoma
python/tvm/topi/nn/conv2d_transpose.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=invalid-name, unused-variable, unused-argument """Transposed 2D convolution operators (sometimes called Deconvolution).""" import collections import tvm from tvm import relay, te from ..utils import simplify from .dilate import dilate from .pad import pad from .utils import get_pad_tuple def _ntuple(n): def parse(x): if isinstance(x, collections.abc.Iterable): assert len(x) == n, f"Input can only have {n} elements, but got {len(x)} instead: {x}." return x return tuple(repeat(x, n)) return parse _single = _ntuple(1) _pair = _ntuple(2) _triple = _ntuple(3) _quadruple = _ntuple(4) def conv2d_transpose_nchw(Input, Filter, strides, padding, out_dtype, output_padding): """Transposed 2D convolution nchw forward operator. Parameters ---------- Input : tvm.te.Tensor 4-D with shape [batch, in_channel, in_height, in_width] Filter : tvm.te.Tensor 4-D with shape [in_channel, num_filter, filter_height, filter_width] strides : tuple of two ints The spatial stride along height and width padding : int or str Padding size, or ['VALID', 'SAME'] out_dtype : str The output data type. This is used for mixed precision. output_padding : tuple of ints Used to get the right output shape for gradients Returns ------- Output : tvm.te.Tensor 4-D with shape [batch, out_channel, out_height, out_width] """ return declaration_conv2d_transpose_impl( Input, Filter, strides, padding, out_dtype, output_padding=output_padding ) def conv2d_transpose_nchw_preprocess(data, kernel, strides, padding, out_dtype, output_padding): """Preprocess data and kernel to make the compute pattern of conv2d_transpose the same as conv2d""" batch, in_c, in_h, in_w = data.shape _, out_c, filter_h, filter_w = kernel.shape stride_h, stride_w = strides opad_h, opad_w = output_padding assert opad_h < stride_h and opad_w < stride_w # dilate data data_dilate = dilate(data, [1, 1, stride_h, stride_w], name="data_dilate") # pad data fpad_top, fpad_left, fpad_bottom, fpad_right = get_pad_tuple(padding, (filter_h, filter_w)) bpad_top = filter_h - 1 - fpad_top bpad_bottom = filter_h - 1 - fpad_bottom + opad_h bpad_left = filter_w - 1 - fpad_left bpad_right = filter_w - 1 - fpad_right + opad_w data_pad = pad( data_dilate, [0, 0, bpad_top, bpad_left], [0, 0, bpad_bottom, bpad_right], name="data_pad" ) # transform kernel layout from IOHW to OIHW, and rotate kernel by 180 degrees kernel_transform = te.compute( (out_c, in_c, filter_h, filter_w), lambda o, i, h, w: kernel[i][o][filter_h - 1 - h][filter_w - 1 - w], name="kernel_transform", ) return data_pad, kernel_transform def declaration_conv2d_transpose_impl(data, kernel, strides, padding, out_dtype, output_padding): """Implementation of conv2d transpose""" data_pad, kernel_transform = conv2d_transpose_nchw_preprocess( data, kernel, strides, padding, out_dtype, output_padding ) batch, in_c, in_h, in_w = data_pad.shape out_c, _, filter_h, filter_w = kernel_transform.shape # convolution stage out_c = simplify(out_c) out_h = simplify(in_h - filter_h + 1) out_w = simplify(in_w - filter_w + 1) dc = te.reduce_axis((0, in_c), name="dc") dh = te.reduce_axis((0, filter_h), name="dh") dw = te.reduce_axis((0, filter_w), name="dw") Output = te.compute( (batch, out_c, out_h, out_w), lambda b, c, h, w: te.sum( data_pad[b, dc, h + dh, w + dw].astype(out_dtype) * kernel_transform[c, dc, dh, dw].astype(out_dtype), axis=[dc, dh, dw], ), tag="conv2d_transpose_nchw", ) return Output def group_conv2d_transpose_nchw(data, kernel, stride, padding, out_dtype, output_padding, groups): """Group convolution operator in NCHW layout. Parameters ---------- data : tvm.te.Tensor 4-D with shape [batch, in_channel, in_height, in_width] kernel : tvm.te.Tensor 4-D with shape [in_channel, out_channel // groups, filter_height, filter_width] stride : int or a list/tuple of two ints Stride size, or [stride_height, stride_width] padding : int or a list/tuple of 2 or 4 ints padding size, or [pad_height, pad_width] for 2 ints, or [pad_top, pad_left, pad_bottom, pad_right] for 4 ints out_dtype : str The output data type. This is used for mixed precision. output_padding : tuple of ints Used to get the right output shape for gradients groups : int number of groups out_dtype : str The output type. This is used for mixed precision. Returns ------- Output : tvm.te.Tensor 4-D with shape [batch, out_channel, out_height, out_width] """ if groups == 1: return conv2d_transpose_nchw(data, kernel, stride, padding, out_dtype, output_padding) # some pre-processing and prelimnary checks if out_dtype is None: out_dtype = data.dtype batch, in_channels, in_h, in_w = data.shape _, out_c, filter_h, filter_w = kernel.shape assert ( in_channels % groups == 0 ), f"input channels {in_channels} must divide group size {groups}" # assert out_c % groups == 0, f"output channels {in_c} must divide group size {groups}" strides = _pair(stride) # padding = _pair(padding) # output_padding = _pair(output_padding) # dilation = _pair(dilation) stride_h, stride_w = strides opad_h, opad_w = output_padding assert ( opad_h < stride_h and opad_w < stride_w ), f"[{output_padding}] opad_h:{opad_h} < stride_h:{stride_h} \ and opad_w:{opad_w} < stride_w:{stride_w} does not satisfy." # dilate data data_dilate = dilate(data, [1, 1, stride_h, stride_w], name="data_dilate") # pad data fpad_top, fpad_left, fpad_bottom, fpad_right = get_pad_tuple(padding, (filter_h, filter_w)) bpad_top = filter_h - 1 - fpad_top bpad_bottom = filter_h - 1 - fpad_bottom + opad_h bpad_left = filter_w - 1 - fpad_left bpad_right = filter_w - 1 - fpad_right + opad_w data_pad = pad( data_dilate, [0, 0, bpad_top, bpad_left], [0, 0, bpad_bottom, bpad_right], name="data_pad" ) # transform kernel layout from IOHW to OIHW, and rotate kernel by 180 degrees kernel_transform = te.compute( (out_c, in_channels, filter_h, filter_w), lambda i, o, h, w: kernel[o][i][filter_h - 1 - h][filter_w - 1 - w], name="kernel_transform", ) batch, in_channels, in_h, in_w = data_pad.shape out_c, _, filter_h, filter_w = kernel_transform.shape # convolution stage out_channels = simplify(out_c * groups) out_h = simplify(in_h - filter_h + 1) out_w = simplify(in_w - filter_w + 1) dc = te.reduce_axis((0, in_channels // groups), name="dc") dh = te.reduce_axis((0, filter_h), name="dh") dw = te.reduce_axis((0, filter_w), name="dw") # data: batch, in_channels, out_h, out_w # weight: out_channels // G, in_channels, out_h, out_w return te.compute( (batch, out_channels, out_h, out_w), lambda b, c, h, w: te.sum( data_pad[ b, c // (out_channels // groups) * (in_channels // groups) + dc, h + dh, w + dw ].astype(out_dtype) * kernel_transform[ c % (out_channels // groups), c // (out_channels // groups) * (in_channels // groups) + dc, dh, dw, ].astype(out_dtype), axis=[dc, dh, dw], ), tag="group_conv2d_transpose_nchw", ) def layout_transform(tensor: "relay.Expr", current_layout: str, desired_layout: str): """Transform a tensor with the current layout to the desired layout. E.g. layout_transform(t, "NCHW", "CNHW") --> relay.transpose(t, [1, 0, 2, 3]) Parameters ---------- tensor: relay.Expr The Tensor to transpose current_layout: str The current layout e.g. NCHW or OIHW desired_layout: str The desired layout, must be compatible with current_layout Returns ------- The layout_transformed tensor. """ if sorted(current_layout) != sorted(desired_layout): raise ValueError(f"Incompatible layouts: {current_layout} vs {desired_layout}") if current_layout == desired_layout: return tensor current_layout_map = {c: i for i, c in enumerate(current_layout)} desired_layout_map = {c: i for i, c in enumerate(desired_layout)} axes = [None] * len(current_layout) for c, i in desired_layout_map.items(): axes[i] = current_layout_map[c] return relay.transpose(tensor, axes=axes) @tvm.target.generic_func def conv2d_transpose_legalize(attrs, inputs, types): """Legalizes Transposed 2D convolution op. Parameters ---------- attrs : tvm.ir.Attrs Attributes of current Transposed 2D convolution inputs : list of tvm.relay.Expr The args of the Relay expr to be legalized types : list of types List of input and output types Returns ------- result : tvm.relay.Expr The legalized expr """ data, kernel = inputs kernel_layout = attrs["kernel_layout"] target = tvm.target.Target.current(allow_none=True) if target and "cudnn" in target.libs: # cuDNN backend can directly operate on NHWC layout. return None if attrs["data_layout"] == "NHWC": kernel = layout_transform(kernel, kernel_layout, "IOHW") # Set new attrs for conv2d_transpose. new_attrs = {k: attrs[k] for k in attrs.keys()} new_attrs["data_layout"] = "NCHW" # layout of kernel should be IOHW, but kernel_layout will be swapped - OIHW new_attrs["kernel_layout"] = "IOHW" # Convert data to NCHW. data = relay.transpose(data, axes=(0, 3, 1, 2)) deconv = relay.nn.conv2d_transpose(data, kernel, **new_attrs) # Convert back to original NHWC layout. out = relay.transpose(deconv, axes=(0, 2, 3, 1)) return out if attrs["data_layout"] == "NCHW": kernel = layout_transform(kernel, kernel_layout, "IOHW") new_attrs = {k: attrs[k] for k in attrs.keys()} # layout of kernel should be IOHW, but kernel_layout will be swapped - OIHW new_attrs["kernel_layout"] = "IOHW" return relay.nn.conv2d_transpose(data, kernel, **new_attrs) return None
https://github.com/zk-ml/tachikoma
python/tvm/topi/nn/conv3d.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=invalid-name, unused-variable, too-many-locals # pylint: disable=unused-argument, redefined-builtin, no-else-return """Conv3D operators""" import tvm from tvm import te from ..utils import get_const_tuple from .conv2d import conv from .winograd_util import winograd_transform_matrices def conv3d_ncdhw(Input, Filter, stride, padding, dilation, groups, out_dtype=None): """Conv3D operator in NCDHW layout. Parameters ---------- Input : tvm.te.Tensor 5-D with shape [batch, in_channel, in_depth, in_height, in_width] Filter : tvm.te.Tensor 5-D with shape [num_filter, in_channel, filter_depth, filter_height, filter_width] stride : int or a list/tuple of three ints Stride size, or [strid_depth, stride_height, stride_width] padding : int or str Padding size, or ['VALID', 'SAME'] dilation: int or a list/tuple of three ints dilation size, or [dilation_depth, dilation_height, dilation_width] groups: int Number of groups. Returns ------- Output : tvm.te.Tensor 5-D with shape [batch, out_channel, out_depth, out_height, out_width] """ return conv(Input, Filter, stride, padding, dilation, groups, "NCDHW", "OIDHW", out_dtype) def conv3d_ndhwc( Input, Filter, stride, padding, dilation, groups, out_dtype="float32", auto_scheduler_rewritten_layout="", meta_schedule_origin_shape=None, ): """Convolution operator in NDHWC layout. Parameters ---------- Input : tvm.te.Tensor 5-D with shape [batch, in_depth, in_height, in_width, in_channel] Filter : tvm.te.Tensor 5-D with shape [filter_depth, filter_height, filter_width, in_channel, num_filter] stride : int or a list/tuple of three ints Stride size, or [stride_depth, stride_height, stride_width] padding : int or str Padding size, or ['VALID', 'SAME'] dilation: int or a list/tuple of three ints dilation size, or [dilation_depth, dilation_height, dilation_width] groups: int Number of groups. out_dtype: str = "float32", The type of output tensor auto_scheduler_rewritten_layout: str = "" The layout after auto-scheduler's layout rewrite pass. meta_schedule_origin_shape: Optional[List[PrimExpr]] = None The original shape of the input tensor. Returns ------- Output : tvm.te.Tensor 5-D with shape [batch, out_depth, out_height, out_width, out_channel] """ return conv( Input, Filter, stride, padding, dilation, groups, "NDHWC", "DHWIO", out_dtype, auto_scheduler_rewritten_layout, meta_schedule_origin_shape, ) def conv3d_winograd_weight_transform(kernel, tile_size): """Weight transformation for 3D winograd Parameters ---------- kernel: Tensor The raw kernel tensor with layout "NCDHW". tile_size: int Tile size of winograd transform. e.g. 2 for F(2x2, 3x3) and 4 for F(4x4, 3x3) Returns ------- output : tvm.te.Tensor 5-D with shape [alpha, alpha, alpha, CO, CI] """ CO, CI, KD, KH, KW = get_const_tuple(kernel.shape) depth_transform = 2 < KD < 8 and KD == KH if depth_transform: assert KD == KH == KW, "Only support NxNxN kernel" else: assert KH == KW, "Only supports DxNxN kernel" r = tile_size + KH - 1 r_kh = te.reduce_axis((0, KH), name="r_kh") r_kw = te.reduce_axis((0, KW), name="r_kw") _, _, G = winograd_transform_matrices(tile_size, KH, kernel.dtype) if depth_transform: shape = (r, r, r, CO, CI) r_kd = te.reduce_axis((0, KD), name="r_kd") return te.compute( shape, lambda omg, eps, nu, co, ci: te.sum( kernel[co][ci][r_kd][r_kh][r_kw] * G[omg][r_kd] * G[eps][r_kh] * G[nu][r_kw], axis=[r_kd, r_kh, r_kw], ), name="transform_weight", ) else: shape = (r, r, KD, CO, CI) return te.compute( shape, lambda eps, nu, d, co, ci: te.sum( kernel[co][ci][d][r_kh][r_kw] * G[eps][r_kh] * G[nu][r_kw], axis=[r_kh, r_kw] ), name="transform_weight", ) @tvm.target.generic_func def conv3d_alter_layout(attrs, inputs, tinfos, out_type): """Change Conv3D layout. Parameters ---------- attrs : tvm.ir.Attrs Attributes of current convolution inputs : tvm.relay.Expr Grouped input symbols tinfos : list Input shape and dtype out_type: type The output type Note ---- Unlike other TOPI functions, this function operates on both graph level and operator level. """ # not to change by default return None
https://github.com/zk-ml/tachikoma
python/tvm/topi/nn/conv3d_transpose.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=invalid-name, unused-variable, unused-argument """Transposed 3D convolution operators (sometimes called Deconvolution).""" import tvm from tvm import te from tvm import relay from .dilate import dilate from .pad import pad from .utils import get_pad_tuple3d from ..utils import simplify def conv3d_transpose_ncdhw(Input, Filter, strides, padding, out_dtype, output_padding): """Transposed 3D convolution ncdhw forward operator. Parameters ---------- Input : tvm.te.Tensor 5-D with shape [batch, in_channel, in_depth, in_height, in_width] Filter : tvm.te.Tensor 5-D with shape [in_channel, num_filter, filter_depth, filter_height, filter_width] strides : int or a list/tuple of three ints The spatial stride along depth,height and width padding : int or str Padding size, or ['VALID', 'SAME'] out_dtype : str The output data type. This is used for mixed precision. output_padding : tuple of ints Used to get the right output shape for gradients Returns ------- Output : tvm.te.Tensor 5-D with shape [batch, out_channel, out_depth, out_height, out_width] """ return declaration_conv3d_transpose_impl( Input, Filter, strides, padding, out_dtype, output_padding ) def conv3d_transpose_ncdhw_preprocess(data, kernel, strides, padding, out_dtype, output_padding): """Preprocess data and kernel to make the compute pattern of conv3d_transpose the same as conv3d""" batch, in_c, in_d, in_h, in_w = data.shape _, out_c, filter_d, filter_h, filter_w = kernel.shape stride_d, stride_h, stride_w = strides opad_d, opad_h, opad_w = output_padding assert opad_d < stride_d and opad_h < stride_h and opad_w < stride_w # dilate data data_dilate = dilate(data, [1, 1, stride_d, stride_h, stride_w], name="data_dilate") # pad data fpad_front, fpad_top, fpad_left, fpad_back, fpad_bottom, fpad_right = get_pad_tuple3d( padding, (filter_d, filter_h, filter_w) ) bpad_front = filter_d - 1 - fpad_front bpad_back = filter_d - 1 - fpad_back + opad_d bpad_top = filter_h - 1 - fpad_top bpad_bottom = filter_h - 1 - fpad_bottom + opad_h bpad_left = filter_w - 1 - fpad_left bpad_right = filter_w - 1 - fpad_right + opad_w data_pad = pad( data_dilate, [0, 0, bpad_front, bpad_top, bpad_left], [0, 0, bpad_back, bpad_bottom, bpad_right], name="data_pad", ) # transform kernel layout from IODHW to OIDHW, and rotate kernel by 180 degrees kernel_transform = te.compute( (out_c, in_c, filter_d, filter_h, filter_w), lambda o, i, d, h, w: kernel[i][o][filter_d - 1 - d][filter_h - 1 - h][filter_w - 1 - w], name="kernel_transform", ) return data_pad, kernel_transform def declaration_conv3d_transpose_impl(data, kernel, strides, padding, out_dtype, output_padding): """Implementation of conv3d transpose""" data_pad, kernel_transform = conv3d_transpose_ncdhw_preprocess( data, kernel, strides, padding, out_dtype, output_padding ) batch, in_c, in_d, in_h, in_w = data_pad.shape out_c, _, filter_d, filter_h, filter_w = kernel_transform.shape stride_d, stride_h, stride_w = strides # convolution stage out_c = simplify(out_c) out_d = simplify(in_d - filter_d + 1) out_h = simplify(in_h - filter_h + 1) out_w = simplify(in_w - filter_w + 1) dc = te.reduce_axis((0, in_c), name="dc") dd = te.reduce_axis((0, filter_d), name="dd") dh = te.reduce_axis((0, filter_h), name="dh") dw = te.reduce_axis((0, filter_w), name="dw") Output = te.compute( (batch, out_c, out_d, out_h, out_w), lambda b, c, d, h, w: te.sum( data_pad[b, dc, d + dd, h + dh, w + dw].astype(out_dtype) * kernel_transform[c, dc, dd, dh, dw].astype(out_dtype), axis=[dc, dd, dh, dw], ), tag="conv3d_transpose_ncdhw", ) return Output @tvm.target.generic_func def conv3d_transpose_legalize(attrs, inputs, types): """Legalizes Transposed 3D convolution op. Parameters ---------- attrs : tvm.ir.Attrs Attributes of current Transposed 3D convolution inputs : list of tvm.relay.Expr The args of the Relay expr to be legalized types : list of types List of input and output types Returns ------- result : tvm.relay.Expr The legalized expr """ if attrs["data_layout"] == "NDHWC": data, kernel = inputs kernel_layout = attrs["kernel_layout"] # Convert Kernel layout to IODHW # kernel_layout is different from input kernel layout - IO is swapped if kernel_layout == "DHWIO": # input kernel layout is swapped to DHWOI # output kernel layout will be IODHW kernel = relay.transpose(kernel, axes=(4, 3, 0, 1, 2)) elif kernel_layout == "DHWOI": # input kernel layout is swapped to DHWIO # output kernel layout will be IODHW kernel = relay.transpose(kernel, axes=(3, 4, 0, 1, 2)) elif kernel_layout == "IODHW": # input kernel layout is swapped to OIDHW # output kernel layout will be IODHW kernel = relay.transpose(kernel, axes=(1, 0, 2, 3, 4)) elif kernel_layout == "OIDHW": # input kernel layout is swapped to IODHW # output kernel layout will be IODHW pass else: # Skip legalize. Let relay.nn.conv2d_transpose to handle the case return None # Set new attrs for conv3d_transpose. new_attrs = {k: attrs[k] for k in attrs.keys()} new_attrs["data_layout"] = "NCDHW" # layout of kernel should be IODHW, but kernel_layout should be swapped - OIDHW new_attrs["kernel_layout"] = "OIDHW" # Convert data to NCDHW. data = relay.transpose(data, axes=(0, 4, 1, 2, 3)) deconv = relay.nn.conv3d_transpose(data, kernel, **new_attrs) # Convert back to original NDHWC layout. out = relay.transpose(deconv, axes=(0, 2, 3, 4, 1)) return out return None
https://github.com/zk-ml/tachikoma
python/tvm/topi/nn/correlation.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """Correlation operators""" from tvm import te from .pad import pad from ..utils import get_const_tuple def correlation_nchw( data1, data2, kernel_size, max_displacement, stride1, stride2, padding, is_multiply ): """Correlation operator in NCHW layout. Parameters ---------- data1 : tvm.te.Tensor 4-D with shape [batch, channel, height, width] data2 : tvm.te.Tensor 4-D with shape [batch, channel, height, width] kernel_size: int Kernel size for correlation, must be an odd number max_displacement: int Max displacement of Correlation stride1: int Stride for data1 stride2: int Stride for data2 within the neightborhood centered around data1 padding : int or a list/tuple of 2 or 4 ints Padding size, or [pad_height, pad_width] for 2 ints, or [pad_top, pad_left, pad_bottom, pad_right] for 4 ints is_multiply: bool operation type is either multiplication or substraction Returns ------- Output : tvm.te.Tensor 4-D with shape [batch, out_channel, out_height, out_width] """ # pylint: disable=unnecessary-lambda, invalid-name data_shape = get_const_tuple(data1.shape) assert get_const_tuple(data2.shape) == data_shape, "data1 and data2 should have the same shape" assert kernel_size > 0 and kernel_size % 2, "kernel_size should be non-negative odd number" if isinstance(padding, (tuple, list)): if len(padding) == 2: pad_before_h = pad_after_h = padding[0] pad_before_w = pad_after_w = padding[1] elif len(padding) == 4: pad_before_h, pad_before_w, pad_after_h, pad_after_w = padding else: raise ValueError("invalid padding") elif isinstance(padding, int): pad_before_h = pad_after_h = pad_before_w = pad_after_w = padding else: raise ValueError("invalid padding") pad_before = [0, 0, pad_before_h, pad_before_w] pad_after = [0, 0, pad_after_h, pad_after_w] padded_data1 = pad(data1, pad_before, pad_after) padded_data2 = pad(data2, pad_before, pad_after) batch, channel, height, width = data_shape kernel_radius = (kernel_size - 1) // 2 border_size = max_displacement + kernel_radius displacement_radius = max_displacement // stride2 displacement_size = 2 * displacement_radius + 1 padded_width = width + pad_before_w + pad_after_w padded_height = height + pad_before_h + pad_after_h out_channel = displacement_size * displacement_size out_height = (padded_height - 2 * border_size + stride1 - 1) // stride1 out_width = (padded_width - 2 * border_size + stride1 - 1) // stride1 rc = te.reduce_axis((0, channel), name="rc") ry = te.reduce_axis((0, kernel_size), name="ry") rx = te.reduce_axis((0, kernel_size), name="rx") if is_multiply: corr_func = lambda x, y: x * y else: corr_func = lambda x, y: te.abs(x - y) def _compute_correlation(n, q, i, j): # location in data1 y1 = i * stride1 + max_displacement x1 = j * stride1 + max_displacement # location in data2 y2 = y1 + (te.indexdiv(q, displacement_size) - displacement_radius) * stride2 x2 = x1 + (te.indexmod(q, displacement_size) - displacement_radius) * stride2 return te.sum( corr_func(padded_data1[n, rc, y1 + ry, x1 + rx], padded_data2[n, rc, y2 + ry, x2 + rx]), axis=[rc, ry, rx], ) correlation = te.compute( (batch, out_channel, out_height, out_width), lambda n, q, i, j: _compute_correlation(n, q, i, j), tag="correlation_nchw", ) return correlation / (kernel_size * kernel_size * channel)
https://github.com/zk-ml/tachikoma
python/tvm/topi/nn/deformable_conv2d.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=invalid-name, too-many-locals, too-many-arguments """Deformable Conv2D operators""" import tvm from tvm import te from .utils import get_pad_tuple from ..utils import get_const_tuple from ..cpp.utils import bilinear_sample_nchw, bilinear_sample_nhwc def deformable_conv2d_nchw( data, offset, kernel, strides, padding, dilation, deformable_groups, groups, out_dtype ): """Deformable conv2D operator in NCHW layout. The deformable convolution operation is described in https://arxiv.org/abs/1703.06211 Parameters ---------- data : tvm.te.Tensor 4-D with shape [batch, in_channel, in_height, in_width] offset : tvm.te.Tensor 4-D with shape [batch, deformable_groups * filter_height * filter_width * 2, out_height, out_width]. kernel : tvm.te.Tensor 4-D with shape [num_filter, in_channel, filter_height, filter_width] strides : int or a list/tuple of two ints stride size, or [stride_height, stride_width] padding : int or a list/tuple of two ints padding size, or [pad_height, pad_width] dilation : int or a list/tuple of two ints dilation size, or [dilation_height, dilation_width] deformable_groups : int number of deformable groups groups : int number of groups Returns ------- output : tvm.te.Tensor 4-D with shape [batch, out_channel, out_height, out_width] """ if out_dtype is None: out_dtype = data.dtype if isinstance(strides, int): stride_h = stride_w = strides else: stride_h, stride_w = strides if isinstance(dilation, int): dilation_h = dilation_w = dilation else: dilation_h, dilation_w = dilation batch, in_channel, in_height, in_width = get_const_tuple(data.shape) out_channel, channel, kernel_h, kernel_w = get_const_tuple(kernel.shape) _, _, out_height, out_width = get_const_tuple(offset.shape) assert in_channel % deformable_groups == 0, "Input cahnnels must divide deformable group size" assert groups == 1, "deformable_conv2d_nchw does not support groups > 1" ic_per_dgroup = channel // deformable_groups dilated_kernel_h = (kernel_h - 1) * dilation_h + 1 dilated_kernel_w = (kernel_w - 1) * dilation_w + 1 pad_top, pad_left, _, _ = get_pad_tuple(padding, (dilated_kernel_h, dilated_kernel_w)) rc = te.reduce_axis((0, in_channel), name="rc") ry = te.reduce_axis((0, kernel_h), name="ry") rx = te.reduce_axis((0, kernel_w), name="rx") zero = tvm.tir.const(0.0, data.dtype) def _bilinear(n, c, h, w): outside = tvm.tir.any(h < 0, w < 0, h >= in_height, w >= in_width) val = bilinear_sample_nchw(data, (n, c, h, w), in_height - 1, in_width - 1) return tvm.tir.if_then_else(outside, zero, val) data_deform = te.compute( (batch, in_channel, kernel_h, kernel_w, out_height, out_width), lambda n, c, kh, kw, y, x: _bilinear( n, c, y * stride_h - pad_top + kh * dilation_h + offset[ n, c // ic_per_dgroup * (kernel_w * kernel_h * 2) + (kh * kernel_w + kw) * 2, y, x ], x * stride_w - pad_left + kw * dilation_w + offset[ n, c // ic_per_dgroup * (kernel_w * kernel_h * 2) + (kh * kernel_w + kw) * 2 + 1, y, x, ], ), tag="data_deform", ) return te.compute( (batch, out_channel, out_height, out_width), lambda n, f, y, x: te.sum( data_deform[n, rc, ry, rx, y, x].astype(out_dtype) * kernel[f, rc, ry, rx].astype(out_dtype), axis=[rc, ry, rx], ), tag="deformable_conv2d_nchw", ) def deformable_conv2d_nhwc( data, offset, kernel, strides, padding, dilation, deformable_groups, groups, out_dtype ): """Deformable conv2D operator in NHWC layout. The deformable convolution operation is described in https://arxiv.org/abs/1703.06211 Parameters ---------- data : tvm.te.Tensor 4-D with shape [batch, in_height, in_width, in_channel] offset : tvm.te.Tensor 4-D with shape [batch, out_height, out_width, deformable_groups * filter_height * filter_width * 2]. kernel : tvm.te.Tensor 4-D with shape [filter_height, filter_width, in_channel, num_filter] strides : int or a list/tuple of two ints stride size, or [stride_height, stride_width] padding : int or a list/tuple of two ints padding size, or [pad_height, pad_width] dilation : int or a list/tuple of two ints dilation size, or [dilation_height, dilation_width] deformable_groups : int number of deformable groups groups : int number of groups Returns ------- output : tvm.te.Tensor 4-D with shape [batch, out_height, out_width, out_channel] """ if out_dtype is None: out_dtype = data.dtype if isinstance(strides, int): stride_h = stride_w = strides else: stride_h, stride_w = strides if isinstance(dilation, int): dilation_h = dilation_w = dilation else: dilation_h, dilation_w = dilation batch, in_height, in_width, in_channel = get_const_tuple(data.shape) kernel_h, kernel_w, channel, out_channel = get_const_tuple(kernel.shape) _, out_height, out_width, _ = get_const_tuple(offset.shape) assert in_channel % deformable_groups == 0, "Input cahnnels must divide deformable group size" assert groups == 1, "deformable_conv2d_nchw does not support groups > 1" ic_per_dgroup = channel // deformable_groups dilated_kernel_h = (kernel_h - 1) * dilation_h + 1 dilated_kernel_w = (kernel_w - 1) * dilation_w + 1 pad_top, pad_left, _, _ = get_pad_tuple(padding, (dilated_kernel_h, dilated_kernel_w)) rc = te.reduce_axis((0, in_channel), name="rc") ry = te.reduce_axis((0, kernel_h), name="ry") rx = te.reduce_axis((0, kernel_w), name="rx") zero = tvm.tir.const(0.0, data.dtype) def _bilinear(n, h, w, c): outside = tvm.tir.any(h < 0, w < 0, h >= in_height, w >= in_width) val = bilinear_sample_nhwc(data, (n, h, w, c), in_height - 1, in_width - 1) return tvm.tir.if_then_else(outside, zero, val) data_deform = te.compute( (batch, kernel_h, kernel_w, in_channel, out_height, out_width), lambda n, kh, kw, c, y, x: _bilinear( n, y * stride_h - pad_top + kh * dilation_h + offset[ n, y, x, c // ic_per_dgroup * (kernel_w * kernel_h * 2) + (kh * kernel_w + kw) * 2 ], x * stride_w - pad_left + kw * dilation_w + offset[ n, y, x, c // ic_per_dgroup * (kernel_w * kernel_h * 2) + (kh * kernel_w + kw) * 2 + 1, ], c, ), tag="data_deform", ) return te.compute( (batch, out_height, out_width, out_channel), lambda n, y, x, f: te.sum( data_deform[n, ry, rx, rc, y, x].astype(out_dtype) * kernel[ry, rx, rc, f].astype(out_dtype), axis=[ry, rx, rc], ), tag="deformable_conv2d_nhwc", )
https://github.com/zk-ml/tachikoma
python/tvm/topi/nn/dense.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=invalid-name,unused-argument """TVM operator fully connected compute.""" import tvm from tvm import auto_scheduler, te from .. import tag def matmul( tensor_a, tensor_b, bias=None, out_dtype=None, transpose_a=False, transpose_b=False, auto_scheduler_rewritten_layout="", meta_schedule_original_shape=None, ): """The default implementation of matmul in topi. Parameters ---------- tensor_a : tvm.te.Tensor 2-D with shape [batch, in_dim] tensor_b : tvm.te.Tensor 2-D with shape [out_dim, in_dim] bias : Optional[tvm.te.Tensor] 1-D with shape [out_dim] out_dtype : Optional[str] The output type. This is used for mixed precision. transpose_a : Optional[bool] = False Whether the tensor_a is in transposed format. transpose_b : Optional[bool] = False Whether the tensor_b is in transposed format. auto_scheduler_rewritten_layout: Optional[str] = "" The layout after auto-scheduler's layout rewrite pass. meta_schedule_original_shape: Optional[List[PrimExpr]] = None The original shape of the input tensor. Returns ------- output : tvm.te.Tensor 2-D with shape [batch, out_dim] """ # TODO(jcf94): Add multi-dim support for tensor_a assert len(tensor_a.shape) == 2, "only support 2-dim matmul" if bias is not None: assert len(bias.shape) == 1 if out_dtype is None: out_dtype = tensor_a.dtype if transpose_a: in_dim, batch = tensor_a.shape else: batch, in_dim = tensor_a.shape if auto_scheduler_rewritten_layout: # Infer shape for the rewritten layout out_dim, red_dim = auto_scheduler.get_shape_from_rewritten_layout( auto_scheduler_rewritten_layout, ["j", "k"] ) auto_scheduler.remove_index_check(tensor_b) elif meta_schedule_original_shape: auto_scheduler.rewrite_tensor_shape(tensor_b, meta_schedule_original_shape) if transpose_b: out_dim, red_dim = tensor_b.shape else: red_dim, out_dim = tensor_b.shape elif transpose_b: out_dim, red_dim = tensor_b.shape else: red_dim, out_dim = tensor_b.shape # cmp should be done by values assert int(in_dim) == int( red_dim ), "Inner dimensions of dense do not match. {in_dim} vs {red_dim}." k = te.reduce_axis((0, in_dim), name="k") if (transpose_a, transpose_b) == (True, True): compute_lambda = lambda i, j: te.sum( tensor_a[k, i].astype(out_dtype) * tensor_b[j, k].astype(out_dtype), axis=k ) compute_name = "T_matmul_TT" compute_tag = "matmul" elif (transpose_a, transpose_b) == (True, False): compute_lambda = lambda i, j: te.sum( tensor_a[k, i].astype(out_dtype) * tensor_b[k, j].astype(out_dtype), axis=k ) compute_name = "T_matmul_TN" compute_tag = "matmul" elif (transpose_a, transpose_b) == (False, True): compute_lambda = lambda i, j: te.sum( tensor_a[i, k].astype(out_dtype) * tensor_b[j, k].astype(out_dtype), axis=k ) compute_name = "T_matmul_NT" # TODO(jcf94): Remove `dense` when `matmul` is finally ready compute_tag = "dense" else: # (transpose_a, transpose_b) == (False, False): compute_lambda = lambda i, j: te.sum( tensor_a[i, k].astype(out_dtype) * tensor_b[k, j].astype(out_dtype), axis=k ) compute_name = "T_matmul_NN" compute_tag = "matmul" mat = te.compute( (batch, out_dim), compute_lambda, name=compute_name, tag=compute_tag, attrs={"layout_free_placeholders": [tensor_b]}, ) if bias is not None: mat = te.compute( (batch, out_dim), lambda i, j: mat[i, j] + bias[j].astype(out_dtype), tag=tag.BROADCAST, ) if auto_scheduler_rewritten_layout: mat = auto_scheduler.rewrite_compute_body(mat, auto_scheduler_rewritten_layout) return mat @tvm.target.generic_func def matmul_legalize(attrs, inputs, types): """Legalizes matmul op. Parameters ---------- attrs : tvm.ir.Attrs Attributes of current matmul inputs : list of tvm.relay.Expr The args of the Relay expr to be legalized types : list of types List of input and output types Returns ------- result : tvm.relay.Expr The legalized expr """ # not to change by default # pylint: disable=unused-argument return None def dense( data, weight, bias=None, out_dtype=None, auto_scheduler_rewritten_layout="", meta_schedule_original_shape=None, ): """The default implementation of dense in topi. This is an alias of matmul_nt operator for data tensor in non-transposed format and weight tensor in transposed format. Parameters ---------- data : tvm.te.Tensor 2-D with shape [batch, in_dim] weight : tvm.te.Tensor 2-D with shape [out_dim, in_dim] bias : Optional[tvm.te.Tensor] 1-D with shape [out_dim] out_dtype : Optional[str] The output type. This is used for mixed precision. auto_scheduler_rewritten_layout: str = "" The layout after auto-scheduler's layout rewrite pass. meta_schedule_original_shape: Optional[List[PrimExpr]] = None The original shape of the input tensor. Returns ------- output : tvm.te.Tensor 2-D with shape [batch, out_dim] """ return matmul( data, weight, bias, out_dtype, False, True, auto_scheduler_rewritten_layout, meta_schedule_original_shape, ) @tvm.target.generic_func def dense_legalize(attrs, inputs, types): """Legalizes dense op. Parameters ---------- attrs : tvm.ir.Attrs Attributes of current dense inputs : list of tvm.relay.Expr The args of the Relay expr to be legalized types : list of types List of input and output types Returns ------- result : tvm.relay.Expr The legalized expr """ # not to change by default # pylint: disable=unused-argument return None def dense_pack(data, weight, bias=None, out_dtype=None): """The default implementation of dense_pack in topi. Parameters ---------- data : tvm.te.Tensor 2-D with shape [batch, in_dim] weight : tvm.te.Tensor 2-D with shape [out_dim, in_dim] bias : Optional[tvm.te.Tensor] 1-D with shape [out_dim] out_dtype : Optional[str] The output type. This is used for mixed precision. Returns ------- output : tvm.te.Tensor 2-D with shape [batch, out_dim] """ if out_dtype is None: out_dtype = data.dtype M, K = get_const_tuple(data.shape) # batch, in_dim N, _, packw_bn = get_const_tuple(weight.shape) # out_dim N = N * packw_bn idxdiv = tvm.tir.indexdiv idxmod = tvm.tir.indexmod k = te.reduce_axis((0, K), name="k") C = te.compute( (M, N), lambda y, x: te.sum( data[y, k].astype(out_dtype) * weight[idxdiv(x, packw_bn), k, idxmod(x, packw_bn)].astype(out_dtype), axis=k, ), name="T_dense_pack", tag="dense_pack", ) if bias is not None: C = te.compute((M, N), lambda i, j: C[i, j] + bias[j].astype(out_dtype), tag=tag.BROADCAST) return C @tvm.target.generic_func def dense_alter_layout(attrs, inputs, tinfos, out_type): """Change dense layout. Parameters ---------- attrs : tvm.ir.Attrs Attributes of current convolution inputs : tvm.relay.Expr Grouped input symbols tinfos : list Input shape and dtype out_type: type The output type Note ---- Unlike other TOPI functions, this function operates on both graph level and operator level. """ # not to change by default return None @tvm.target.generic_func def batch_matmul_legalize(attrs, inputs, types): """Legalizes batch_matmul op. Parameters ---------- attrs : tvm.ir.Attrs Attributes of current batch_matmul inputs : list of tvm.relay.Expr The args of the Relay expr to be legalized types : list of types List of input and output types Returns ------- result : tvm.relay.Expr The legalized expr """ return None
https://github.com/zk-ml/tachikoma
python/tvm/topi/nn/depth_to_space.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=invalid-name """TVM operator depth_to_space compute.""" from __future__ import absolute_import import tvm from tvm import te from .. import tag def depth_to_space(data, block_size, layout="NCHW", mode="DCR"): """Perform depth to space transformation on the data Parameters ---------- data : tvm.te.Tensor 4-D tensor in either NCHW or NHWC layout. block_size : int Size of blocks to compose from channel dimension. layout : string Either NCHW or NHWC, indicating data layout. mode : string Either DCR or CDR, indicates how channels should be accessed. In DCR, channels are interwoven in the Tensorflow style while in CDR channels are accessed sequentially as in Pytorch. Returns ------- output : tvm.te.Tensor Output of shape [N, C / block_size**2, H * block_size, W * block_size] """ if layout == "NCHW": in_n, in_c, in_h, in_w = data.shape channel_factor = tvm.tir.truncdiv(in_c, (block_size * block_size)) output_shape = [in_n, channel_factor, in_h * block_size, in_w * block_size] elif layout == "NHWC": in_n, in_h, in_w, in_c = data.shape channel_factor = tvm.tir.truncdiv(in_c, (block_size * block_size)) output_shape = [in_n, in_h * block_size, in_w * block_size, channel_factor] else: raise ValueError("Only NCHW and NHWC layouts are currently supported.") def _get_indices(*indices): if layout == "NCHW": n, c, y, x = indices elif layout == "NHWC": n, y, x, c = indices return n, c, y, x def _get_pixel(n, c, y, x): block_x = tvm.tir.truncdiv(x, block_size) block_y = tvm.tir.truncdiv(y, block_size) idx_x = tvm.tir.truncmod(x, block_size) idx_y = tvm.tir.truncmod(y, block_size) if mode == "DCR": channel_idx = channel_factor * ((block_size * idx_y) + idx_x) + c else: channel_idx = (c * block_size * block_size) + ((block_size * idx_y) + idx_x) if layout == "NCHW": output = data(n, channel_idx, block_y, block_x) else: output = data(n, block_y, block_x, channel_idx) return output def _compute(*indices): n, c, y, x = _get_indices(*indices) return _get_pixel(n, c, y, x) return te.compute(output_shape, _compute, name="depth_to_space", tag=tag.INJECTIVE)
https://github.com/zk-ml/tachikoma
python/tvm/topi/nn/depthwise_conv2d.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=invalid-name, unused-variable, too-many-locals, unused-argument """Depthwise convolution operators""" from __future__ import absolute_import as _abs from collections import namedtuple import tvm from tvm import te from .dilate import dilate from .pad import pad from .utils import get_pad_tuple from ..utils import simplify, get_const_tuple # workload description of depthwise-conv2d Workload = namedtuple( "Workload", [ "in_dtype", "out_dtype", "height", "width", "in_filter", "out_filter", "kernel_h", "kernel_w", "padt", "padl", "padb", "padr", "dilation_h", "dilation_w", "stride_h", "stride_w", ], ) def _get_workload(data, kernel, stride, padding, dilation, out_dtype, data_layout="NCHW"): """Get the workload structure for a depthwise conv2d. Input data and filter should use NCHW layout. """ if data_layout == "NCHW": _, in_channel, height, width = get_const_tuple(data.shape) filter_channel, channel_multiplier, kh, kw = get_const_tuple(kernel.shape) elif data_layout == "NHWC": _, height, width, in_channel = get_const_tuple(data.shape) kh, kw, filter_channel, channel_multiplier = get_const_tuple(kernel.shape) elif data_layout == "NCHWc": _, in_channel_chunk, height, width, in_channel_block = get_const_tuple(data.shape) in_channel = in_channel_chunk * in_channel_block ( filter_channel_chunk, cm_chunk, kh, kw, cm_block, filter_channel_block, ) = get_const_tuple(kernel.shape) filter_channel = filter_channel_chunk * filter_channel_block channel_multiplier = cm_chunk * cm_block assert ( in_channel_block == filter_channel_block ), "Incorrect dimensions, data has block size {}, but filter has block size {}".format( in_channel_block, filter_channel_block ) else: raise ValueError("Data layout {} not supported".format(data_layout)) assert ( in_channel == filter_channel ), "Incorrect dimensions, data has {} channels but filter expects {} channels".format( in_channel, filter_channel ) out_channel = filter_channel * channel_multiplier dilation_h, dilation_w = ( dilation if isinstance(dilation, (tuple, list)) else (dilation, dilation) ) if isinstance(stride, (tuple, list)): HSTR, WSTR = stride else: HSTR, WSTR = stride, stride assert (data.dtype == kernel.dtype) or ( data.dtype == "uint8" and kernel.dtype == "int8" ), "Do not support inputs with different data types now. ' \ '{} vs. {}".format( data.dtype, kernel.dtype ) dilated_kernel_h = (kh - 1) * dilation_h + 1 dilated_kernel_w = (kw - 1) * dilation_w + 1 pt, pl, pb, pr = get_pad_tuple(padding, (dilated_kernel_h, dilated_kernel_w)) return Workload( data.dtype, out_dtype, height, width, in_channel, out_channel, kh, kw, pt, pl, pb, pr, dilation_h, dilation_w, HSTR, WSTR, ) def depthwise_conv2d_nchw(Input, Filter, stride, padding, dilation, out_dtype=None): """Depthwise convolution nchw forward operator. Parameters ---------- Input : tvm.te.Tensor 4-D with shape [batch, in_channel, in_height, in_width] Filter : tvm.te.Tensor 4-D with shape [in_channel, channel_multiplier, filter_height, filter_width] stride : int or a list/tuple of two ints The spatial stride, or (stride_height, stride_width). padding : int or str Padding size, or ['VALID', 'SAME'] dilation: int or a list/tuple of two ints dilation size, or [dilation_height, dilation_width] out_dtype: str, optional Output data type Returns ------- Output : tvm.te.Tensor 4-D with shape [batch, out_channel, out_height, out_width] """ out_dtype = Input.dtype if out_dtype is None else out_dtype if isinstance(stride, int): stride_h = stride_w = stride else: stride_h, stride_w = stride if isinstance(dilation, int): dilation_h = dilation_w = dilation else: dilation_h, dilation_w = dilation batch, in_channel, in_height, in_width = Input.shape # shape of dilated kernel filter_channel, channel_multiplier, filter_height, filter_width = Filter.shape dilated_kernel_h = (filter_height - 1) * dilation_h + 1 dilated_kernel_w = (filter_width - 1) * dilation_w + 1 pad_top, pad_left, pad_down, pad_right = get_pad_tuple( padding, (dilated_kernel_h, dilated_kernel_w) ) out_channel = simplify(in_channel * channel_multiplier) out_height = simplify((in_height - dilated_kernel_h + pad_top + pad_down) // stride_h + 1) out_width = simplify((in_width - dilated_kernel_w + pad_left + pad_right) // stride_w + 1) # padding stage pad_before = [0, 0, pad_top, pad_left] pad_after = [0, 0, pad_down, pad_right] PaddedInput = pad(Input, pad_before, pad_after, name="PaddedInput") # depthconv stage idxdiv = tvm.tir.indexdiv idxmod = tvm.tir.indexmod di = te.reduce_axis((0, filter_height), name="di") dj = te.reduce_axis((0, filter_width), name="dj") Output = te.compute( (batch, out_channel, out_height, out_width), lambda b, c, i, j: te.sum( ( PaddedInput[ b, idxdiv(c, channel_multiplier), i * stride_h + di * dilation_h, j * stride_w + dj * dilation_w, ].astype(out_dtype) * Filter[ idxdiv(c, channel_multiplier), idxmod(c, channel_multiplier), di, dj ].astype(out_dtype) ), axis=[di, dj], ), name="DepthwiseConv2d", tag="depthwise_conv2d_nchw", ) return Output def depthwise_conv2d_nhwc(Input, Filter, stride, padding, dilation, out_dtype=None): """Depthwise convolution nhwc forward operator. Parameters ---------- Input : tvm.te.Tensor 4-D with shape [batch, in_height, in_width, in_channel] Filter : tvm.te.Tensor 4-D with shape [filter_height, filter_width, in_channel, channel_multiplier] stride : tuple of two ints The spatial stride along height and width padding : int or str Padding size, or ['VALID', 'SAME'] dilation: int or a list/tuple of two ints dilation size, or [dilation_height, dilation_width] out_dtype: str, optional Output data type Returns ------- Output : tvm.te.Tensor 4-D with shape [batch, out_height, out_width, out_channel] """ out_dtype = Input.dtype if out_dtype is None else out_dtype if isinstance(stride, int): stride_h = stride_w = stride else: stride_h, stride_w = stride if isinstance(dilation, int): dilation_h = dilation_w = dilation else: dilation_h, dilation_w = dilation batch, in_height, in_width, in_channel = Input.shape # shape of dilated kernel filter_height, filter_width, filter_channel, channel_multiplier = Filter.shape dilated_kernel_h = (filter_height - 1) * dilation_h + 1 dilated_kernel_w = (filter_width - 1) * dilation_w + 1 pad_top, pad_left, pad_down, pad_right = get_pad_tuple( padding, (dilated_kernel_h, dilated_kernel_w) ) out_channel = simplify(in_channel * channel_multiplier) out_height = simplify((in_height - dilated_kernel_h + pad_top + pad_down) // stride_h + 1) out_width = simplify((in_width - dilated_kernel_w + pad_left + pad_right) // stride_w + 1) # padding stage pad_before = [0, pad_top, pad_left, 0] pad_after = [0, pad_down, pad_right, 0] PaddedInput = pad(Input, pad_before, pad_after, name="PaddedInput") # depthconv stage idxdiv = tvm.tir.indexdiv idxmod = tvm.tir.indexmod di = te.reduce_axis((0, filter_height), name="di") dj = te.reduce_axis((0, filter_width), name="dj") Output = te.compute( (batch, out_height, out_width, out_channel), lambda b, i, j, c: te.sum( ( PaddedInput[ b, i * stride_h + di * dilation_h, j * stride_w + dj * dilation_w, idxdiv(c, channel_multiplier), ].astype(out_dtype) * Filter[ di, dj, idxdiv(c, channel_multiplier), idxmod(c, channel_multiplier) ].astype(out_dtype) ), axis=[di, dj], ), name="DepthwiseConv2d", tag="depthwise_conv2d_nhwc", ) return Output def depthwise_conv2d_backward_input_nhwc(Filter, Out_grad, oshape, ishape, stride, padding): """Depthwise convolution nhwc backward wrt input operator. Parameters ---------- Filter : tvm.te.Tensor 4-D with shape [filter_height, filter_width, in_channel, channel_multiplier] Out_grad : tvm.te.Tensor 4-D with shape [batch, out_height, out_width, out_channel] stride : tuple of two ints The spatial stride along height and width padding : int or str Padding size, or ['VALID', 'SAME'] Returns ------- Output : tvm.te.Tensor 4-D with shape [batch, in_height, in_width, in_channel] """ batch, in_h, in_w, in_c = ishape _, out_h, out_w, out_c = oshape filter_h, filter_w, _, channel_multiplier = Filter.shape if isinstance(stride, int): stride_h = stride_w = stride else: stride_h, stride_w = stride dilated_out_grad = dilate(Out_grad, [1, stride_h, stride_w, 1], name="dilated_out_grad") # padding params in forward propagation fpad_top, fpad_left, fpad_bottom, fpad_right = get_pad_tuple(padding, (filter_h, filter_w)) # padding params in backward propagation bpad_top = filter_h - 1 - fpad_top bpad_bottom = (filter_h - 1 - fpad_bottom) + (stride_h - 1) bpad_left = filter_w - 1 - fpad_left bpad_right = (filter_w - 1 - fpad_right) + (stride_w - 1) padded_out_grad = pad( dilated_out_grad, [0, bpad_top, bpad_left, 0], [0, bpad_bottom, bpad_right, 0], name="padded_out_grad", ) dh = te.reduce_axis((0, filter_h), name="dh") dw = te.reduce_axis((0, filter_w), name="dw") dc = te.reduce_axis((0, channel_multiplier), name="dc") In_grad = te.compute( (batch, in_h, in_w, in_c), lambda b, h, w, c: te.sum( padded_out_grad[b, h + dh, w + dw, c * channel_multiplier + dc] * Filter[filter_h - 1 - dh, filter_w - 1 - dw, c, dc], axis=[dh, dw, dc], ), tag="depthwise_conv2d_backward_input_nhwc", ) return In_grad def depthwise_conv2d_backward_weight_nhwc(Input, Out_grad, oshape, fshape, stride, padding): """Depthwise convolution nhwc backward wrt weight operator. Parameters ---------- Input : tvm.te.Tensor 4-D with shape [batch, in_height, in_width, in_channel] Out_grad : tvm.te.Tensor 4-D with shape [batch, out_height, out_width, out_channel] stride : tuple of two ints The spatial stride along height and width padding : int or str Padding size, or ['VALID', 'SAME'] Returns ------- Output : tvm.te.Tensor 4-D with shape [filter_height, filter_width, in_channel, channel_multiplier] """ batch, out_h, out_w, out_c = oshape filter_h, filter_w, _, channel_multiplier = fshape in_c = Input.shape[3].value if isinstance(stride, int): stride_h = stride_w = stride else: stride_h, stride_w = stride pad_top, pad_left, pad_bottom, pad_right = get_pad_tuple(padding, (filter_h, filter_w)) padded_in = pad( Input, [0, pad_top, pad_left, 0], [0, pad_bottom, pad_right, 0], name="padded_in" ) dh = te.reduce_axis((0, Out_grad.shape[1].value), name="dh") dw = te.reduce_axis((0, Out_grad.shape[2].value), name="dw") db = te.reduce_axis((0, batch), name="db") idxdiv = tvm.tir.indexdiv idxmod = tvm.tir.indexmod Weight_grad = te.compute( (filter_h, filter_w, in_c, channel_multiplier), lambda fh, fw, c, m: te.sum( Out_grad[db, dh, dw, c * channel_multiplier + idxmod(m, channel_multiplier)] * padded_in[db, fh + dh * stride_h, fw + dw * stride_w, c], axis=[db, dh, dw], ), tag="depthwise_conv2d_backward_weight_nhwc", ) return Weight_grad def depthwise_conv2d_NCHWc( Input, Filter, stride, padding, dilation, layout, out_layout, out_dtype=None ): """Depthwise convolution NCHW[x]c forward operator. Parameters ---------- Input : tvm.te.Tensor 5-D with shape [batch, in_channel_chunk, in_height, in_width, in_channel_block] Filter : tvm.te.Tensor 6-D with shape [out_channel_chunk, 1, filter_height, filter_width, 1, out_channel_block] In NCHWc depthwise convolution, we group kernel's in_channel and channel_multiplier together then do the tiling. stride : tuple of two ints The spatial stride along height and width padding : int or str Padding size, or ['VALID', 'SAME'] dilation: int or a list/tuple of two ints dilation size, or [dilation_height, dilation_width] layout : str Input data layout out_layout : str Output data layout out_dtype: str, optional Output data type Returns ------- Output : tvm.te.Tensor 5-D with shape [batch, out_channel_chunk, out_height, out_width, out_channel_block] """ raise ValueError("missing register for topi.nn.depthwise_conv2d_NCHWc") @tvm.target.generic_func def depthwise_conv2d_infer_layout(workload, cfg): """Infer input/output shapes and layouts from a workload and cfg. Parameters ---------- workload : tuple conv2d workload cfg : tuple tvm.autotvm config Returns ------- Output : [tuple of tuple and str, tuple of tuple and str] Input shapes and layouts, and output shapes and layouts """ raise ValueError("missing register for topi.nn.depthwise_conv2d_infer_layout")
https://github.com/zk-ml/tachikoma
python/tvm/topi/nn/dilate.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=invalid-name """Dilation operators""" import tvm from tvm import te from .. import utils from .. import tag @te.tag_scope(tag=tag.INJECTIVE + ",dilate") def dilate(data, strides, dilation_value=0.0, name="DilatedInput"): """Dilate data with given dilation value (0 by default). Parameters ---------- data : tvm.te.Tensor n-D, can be any layout. strides : list / tuple of n ints Dilation stride on each dimension, 1 means no dilation. dilation_value : int/float, optional Value used to dilate the input. name : str, optional The name prefix operators generated Returns ------- Output : tvm.te.Tensor n-D, the same layout as data. """ n = len(data.shape) if len(strides) != n: raise ValueError("data dimension and strides size dismatch : %d vs %d" % (n, len(strides))) ana = tvm.arith.Analyzer() out_shape = tuple(ana.simplify((data.shape[i] - 1) * strides[i] + 1) for i in range(n)) def _dilate(*indices): not_zero = [] index_tuple = [] idxdiv = tvm.tir.indexdiv idxmod = tvm.tir.indexmod for i in range(n): if not utils.equal_const_int(strides[i], 1): index_tuple.append(idxdiv(indices[i], strides[i])) not_zero.append(idxmod(indices[i], strides[i]).equal(0)) else: index_tuple.append(indices[i]) if not_zero: not_zero = tvm.tir.all(*not_zero) return tvm.tir.if_then_else( not_zero, data(*index_tuple), tvm.tir.const(dilation_value, data.dtype) ) return data(*index_tuple) return te.compute(out_shape, _dilate, name=name)
https://github.com/zk-ml/tachikoma
python/tvm/topi/nn/elemwise.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """Elementwise operators""" from __future__ import absolute_import as _abs import tvm from tvm import te from .. import tag from ..utils import get_const_int @tvm.te.tag_scope(tag=tag.ELEMWISE) def relu(x): """Take relu of input x. Parameters ---------- x : tvm.te.Tensor Input argument. Returns ------- y : tvm.te.Tensor The result. """ return te.compute(x.shape, lambda *i: tvm.te.max(x(*i), tvm.tir.const(0, x.dtype))) @tvm.te.tag_scope(tag=tag.ELEMWISE) def leaky_relu(x, alpha): """Take leaky relu of input x. Parameters ---------- x : tvm.te.Tensor Input argument. alpha : float The slope for the small gradient when x < 0 Returns ------- y : tvm.te.Tensor The result. """ def _compute(*indices): value = x(*indices) calpha = tvm.tir.const(alpha, value.dtype) return tvm.tir.Select(value > 0, value, value * calpha) return te.compute(x.shape, _compute) @tvm.te.tag_scope(tag=tag.BROADCAST) def prelu(x, slope, axis=1): """PReLU. It accepts two arguments: an input ``x`` and a weight array ``W`` and computes the output as :math:`PReLU(x) y = x > 0 ? x : W * x`, where :math:`*` is an elementwise multiplication for each sample in the batch. Parameters ---------- x : tvm.te.Tensor Input argument. slope : tvm.te.Tensor Channelised slope tensor for prelu axis : int The axis where the channel data needs to be applied Returns ------- y : tvm.te.Tensor The result. Links ----- [http://arxiv.org/pdf/1502.01852v1.pdf] """ assert len(slope.shape) == 1 assert axis < len(x.shape) assert get_const_int(slope.shape[0]) == get_const_int(x.shape[axis]) def _compute_channelwise(*indices): xval = x(*indices) return tvm.tir.Select(xval > 0, xval, xval * slope(indices[axis])) return te.compute(x.shape, _compute_channelwise)
https://github.com/zk-ml/tachikoma
python/tvm/topi/nn/fifo_buffer.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """FIFO buffer op""" from __future__ import absolute_import as _abs import tvm from tvm import te from .. import tag from ..transform import concatenate, strided_slice @tvm.te.tag_scope(tag=tag.INJECTIVE + ",fifo_buffer") def fifo_buffer(data, buffer, axis): """ FIFO buffer to enable computation reuse in CNNs with sliding indow input Compute equivalent of .. code-block:: python concat(buffer, data, axis=axis) .slice_axis(axis=axis, begin=data.shape[axis], end=data.shape[axis]+buffer.shape[axis]) Useful for * Encoding explicit re-use of computation in convolution ops operated on a sliding window input * Implementing a FIFO queue to cache intermediate results, e.g. as in Fast WaveNet. Parameters ---------- data : tvm.te.Tensor The input data buffer : tvm.te.Tensor Previous value of the FIFO buffer axis : int Specify which axis should be used for buffering Returns ------- result : tvm.te.Tensor Updated value for the buffer """ assert len(data.shape) == len(buffer.shape), ( "buffer and data must have same number of dimensions, " + "buffer.shape = {}, data.shape = {}".format(buffer.shape, data.shape) ) assert len(buffer.shape) >= 1, "Zero-dimension tensor not supported" assert 0 <= axis < len(buffer.shape), "buffer axis out of range" for i in range(len(data.shape)): if i == axis: assert int(str(data.shape[i])) <= int(str(buffer.shape[i])) else: assert int(str(data.shape[i])) == int(str(buffer.shape[i])) buflen = buffer.shape[axis] data_size = data.shape[axis] # Explicitly write out formula up to 4D, and then use concat+slice combo for 5D and higher if len(buffer.shape) == 1: return te.compute( buffer.shape, lambda i: tvm.tir.if_then_else( i < buflen - data_size, buffer[i + data_size], data[i - buflen + data_size] ), name="new_buffer", ) if len(buffer.shape) == 2: if axis == 0: return te.compute( buffer.shape, lambda i, j: tvm.tir.if_then_else( i < buflen - data_size, buffer[i + data_size, j], data[i - buflen + data_size, j], ), name="new_buffer", ) if axis == 1: return te.compute( buffer.shape, lambda i, j: tvm.tir.if_then_else( j < buflen - data_size, buffer[i, j + data_size], data[i, j - buflen + data_size], ), name="new_buffer", ) assert False, "Invalid value for axis; it should be at most {}".format(len(buffer.shape)) elif len(buffer.shape) == 3: if axis == 0: return te.compute( buffer.shape, lambda i, j, k: tvm.tir.if_then_else( i < buflen - data_size, buffer[i + data_size, j, k], data[i - buflen + data_size, j, k], ), name="new_buffer", ) if axis == 1: return te.compute( buffer.shape, lambda i, j, k: tvm.tir.if_then_else( j < buflen - data_size, buffer[i, j + data_size, k], data[i, j - buflen + data_size, k], ), name="new_buffer", ) if axis == 2: return te.compute( buffer.shape, lambda i, j, k: tvm.tir.if_then_else( k < buflen - data_size, buffer[i, j, k + data_size], data[i, j, k - buflen + data_size], ), name="new_buffer", ) assert False, "Invalid value for axis; it should be at most {}".format(len(buffer.shape)) elif len(buffer.shape) == 4: if axis == 0: return te.compute( buffer.shape, lambda i, j, k, l: tvm.tir.if_then_else( i < buflen - data_size, buffer[i + data_size, j, k, l], data[i - buflen + data_size, j, k, l], ), name="new_buffer", ) if axis == 1: return te.compute( buffer.shape, lambda i, j, k, l: tvm.tir.if_then_else( j < buflen - data_size, buffer[i, j + data_size, k, l], data[i, j - buflen + data_size, k, l], ), name="new_buffer", ) if axis == 2: return te.compute( buffer.shape, lambda i, j, k, l: tvm.tir.if_then_else( k < buflen - data_size, buffer[i, j, k + data_size, l], data[i, j, k - buflen + data_size, l], ), name="new_buffer", ) if axis == 3: return te.compute( buffer.shape, lambda i, j, k, l: tvm.tir.if_then_else( l < buflen - data_size, buffer[i, j, k, l + data_size], data[i, j, k, l - buflen + data_size], ), name="new_buffer", ) assert False, "Invalid value for axis; it should be at most {}".format(len(buffer.shape)) else: # Implement FIFO buffer as combination of concat and slice begin = [0] * len(buffer.shape) begin[axis] = data.shape[axis] end = list(buffer.shape[:]) end[axis] += data.shape[axis] return strided_slice(concatenate((buffer, data), axis=axis), begin=begin, end=end) return None
https://github.com/zk-ml/tachikoma
python/tvm/topi/nn/flatten.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """TVM operator flatten compute.""" from __future__ import absolute_import import tvm from tvm import te from .. import tag @tvm.te.tag_scope(tag=tag.INJECTIVE) def flatten(data): """Flattens the input array into a 2-D array by collapsing the higher dimensions. Parameters ---------- data : tvm.te.Tensor Input array. Returns ------- output : tvm.te.Tensor 2-D array with collapsed higher dimensions. """ ishape = data.shape dim = 1 for i in range(1, len(ishape)): dim = dim * ishape[i] oshape = [ishape[0], dim] idxdiv = tvm.tir.indexdiv idxmod = tvm.tir.indexmod def unwrap(idx, shape): index = [] for s in reversed(shape): index.append(idxmod(idx, s)) idx = idxdiv(idx, s) return list(reversed(index)) return te.compute(oshape, lambda i, j: data(i, *unwrap(j, ishape[1:])))
https://github.com/zk-ml/tachikoma
python/tvm/topi/nn/layer_norm.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """Layer normalization operator.""" from .. import cpp def layer_norm(data, gamma, beta, axis, epsilon=1e-5): """Layer normalization operator. Parameters ---------- data : tvm.te.Tensor N-D with shape (d_0, d_1, ..., d_{N-1}) gamma: tvm.te.Tensor K-D with shape (r_0, r_1, ..., r_{K-1}) where K == len(axis) and d_{axis_k} == r_k beta: tvm.te.Tensor Optional, K-D with shape (r_0, r_1, ..., r_{K-1}) where K == len(axis) and d_{axis_k} == r_k axis : list of int Axis over the normalization applied epsilon : float The epsilon value to avoid division by zero. Returns ------- result : tvm.te.Tensor N-D with shape (d_0, d_1, ..., d_{N-1}) """ return cpp.nn.layer_norm(data, gamma, beta, axis, epsilon)
https://github.com/zk-ml/tachikoma
python/tvm/topi/nn/local_response_norm.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=invalid-name """TVM operator for local response norm compute.""" from __future__ import absolute_import from .. import cpp def lrn(data, size, axis=1, alpha=0.0001, beta=0.75, bias=2): """Perform the across channels local response normalisation on the input data. sum_sqr_up^i{x, y} = (bias+((alpha/size)* \ {sum_{j=max(0, i-size/2)}^{min(N-1,i+size/2)} \ (data^j{x,y})^2}))^beta output^i{x, y} = data^i{x, y}/sum_sqr_up^i{x, y} N is the number for input channels Parameters ---------- data : tvm.te.Tensor 4-D with shape [batch, channel, height, width] size : int normalisation window size axis : int input data layout channel axis default value is 1 for NCHW format bias : float offset to avoid dividing by 0 alpha : float to be divided beta : float exponent Returns ------- output : tvm.te.Tensor 4-D output with same shape """ return cpp.nn.lrn(data, size, axis, alpha, beta, bias)
https://github.com/zk-ml/tachikoma
python/tvm/topi/nn/loss.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=invalid-name,unused-argument """Loss functions definitions.""" from __future__ import absolute_import from . import cpp def nll_loss(predictions, targets, weights, reduction, ignore_index): """Negative log likelihood loss on the input data. output{n, i_1, i_2, ..., i_k} = -p * w where t = target{n, i_1, i_2, ..., i_k} p = predictions{n, t, i_1, i_2, i_k} w = weights{n, i_1, i_2, ..., i_k} if t != ignore_index else 0 result = reduction(output) Parameters ---------- predictions : tvm.te.Tensor (k+2)-D with shape (N, C, d_1, d_2, ..., d_k), where C is the number of target classes targets : tvm.te.Tensor (k+1)-D with shape (N, d_1, d_2, ..., d_k) The target value of the input. weights : tvm.te.Tensor 1-D with shape (C,) The weight of each target value. reduction : string The reduction method to apply to output. Can be "mean", "sum" or "none". ignore_index : int The target value to ignore. Returns ------- output : tvm.te.Tensor a scalar if the reduction type is "mean" or "sum", otherwise the same shape as `target`. """ return cpp.nn.nll_loss(predictions, targets, weights, reduction, ignore_index)
https://github.com/zk-ml/tachikoma
python/tvm/topi/nn/lstm.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=invalid-name """General LSTM implementation using TE scan.""" from tvm import te, tir from tvm.topi import tag def lstm( Xs, Wi, Wh, Bi=None, Bh=None, h_init=None, c_init=None, proj=None, p_i=None, p_f=None, p_o=None, f_act=tir.sigmoid, g_act=tir.tanh, h_act=tir.tanh, reverse=False, weight_layout: str = "IFGO", ): """General LSTM implemented using TE scan. Parameters ---------- Xs : te.Tensor Input sequence with shape `(seq_len, batch_size, in_dim)` Wi : te.Tensor Input weight matrix with shape `(4 * hidden_dim, in_dim)`. The weights are packed according to `weight_layout`. Wh : te.Tensor Hidden weight matrix with shape `(4 * hidden_dim, hidden_dim or proj_dim)`. Packed as `Wh`. Bi : te.Tensor, optional Input bias with shape `(4 * hidden_dim,)`, by default None. Packed as `Wh`. Bh : te.Tensor, optional Hidden bias with shape as `Bi`, by default None. Packed as `Wh`. h_init : te.Tensor, optional Initial hidden state with shape `(batch_size, hidden_dim or proj_dim)`, zero if None c_init : te.Tensor, optional Initial cell state with same shape as `h_init`, zero if None proj : te.Tensor, optional Projection matrix with shape `(proj_dim, hidden_dim)`, by default None p_i, p_f, p_o : te.Tensor, optional Peephole LSTM matrices with shape `(batch_size, hidden_dim)`, by default None f_act, g_act, h_act : F, optional Gate activation functions reverse : bool, optional Whether to process `Xs` in reverse, by default False weight_layout : str, optional The packed weight layout for gates, by default "IFGO". Note: I = input, F = forget, G = cell, O = output. Returns ------- result : te.Tensor, te.Tensor Tuple of hidden states (with shape `(seq_len, batch_size, hidden_dim or proj_dim)`), and cell states (with shape `(seq_len, batch_size, hidden_dim)`). """ assert len(weight_layout) == 4 and sorted(weight_layout) == sorted( "IFGO" ), f'given weight layout "{weight_layout}" is not a permutation of "IFGO"' i_gate_idx = weight_layout.find("I") f_gate_idx = weight_layout.find("F") g_gate_idx = weight_layout.find("G") o_gate_idx = weight_layout.find("O") seq_len, batch_size, in_dim = Xs.shape assert ( Wi.shape[0] % 4 == 0 ), f"dim 0 of input weight should be 4 * hidden_dim, but {Wi.shape[0]} is not divisible by 4" hidden_dim = Wi.shape[0] // 4 proj_dim = hidden_dim if proj is not None: proj_dim = proj.shape[0] # te.scan uses up 1 element for the initial value scan_len = seq_len + 1 # precompute input-hidden matmul outside the scan ki = te.reduce_axis((0, in_dim), name="ki2h") Xi2h = te.compute( (seq_len * batch_size, 4 * hidden_dim), lambda tb, ij: te.sum(Xs[(tb // batch_size), tb % batch_size, ki] * Wi[ij, ki], axis=ki), name="Xi2h", ) if Bi is not None: Xi2h = te.compute( Xi2h.shape, lambda tb, ij: Xi2h[tb, ij] + Bi[ij], name="Xi2h_bias", tag=tag.INJECTIVE ) h_state = te.placeholder((scan_len, batch_size, proj_dim), name="h_state") c_state = te.placeholder((scan_len, batch_size, hidden_dim), name="c_state") h_init = te.compute( (1, batch_size, proj_dim), lambda _, b, i: h_init[b, i] if h_init is not None else 0.0, name="h_init", ) c_init = te.compute( (1, batch_size, hidden_dim), lambda _, b, i: c_init[b, i] if c_init is not None else 0.0, name="c_init", ) # begin scan computations, first the (batched) hidden-hidden dense kh = te.reduce_axis((0, proj_dim), name="kh2h") s_h2h = te.compute( (scan_len, batch_size, 4, hidden_dim), lambda t, b, i, j: te.sum(h_state[t - 1, b, kh] * Wh[i * hidden_dim + j, kh], axis=kh), name="s_h2h", ) if Bh is not None: s_h2h = te.compute( s_h2h.shape, lambda t, b, i, j: s_h2h[t, b, i, j] + Bh[i * hidden_dim + j], name="s_h2h_bias", tag=tag.INJECTIVE, ) # helper to reverse time if scanning backwards get_x_t = lambda t: seq_len - t if reverse else t - 1 gates = te.compute( (scan_len, batch_size, 4, hidden_dim), lambda t, b, i, j: Xi2h[get_x_t(t) * batch_size + b, i * hidden_dim + j] + s_h2h[t, b, i, j], name="gates", tag=tag.INJECTIVE, ) # helper to correctly read each gate dense from the batched output read_gate = lambda t, b, j, idx: gates[t, b, idx, j] gate_shape = (scan_len, batch_size, hidden_dim) # compute the activated gates (and do some extra stuff if peephole weights are present) if p_i is not None and p_f is not None: i_gate = te.compute( gate_shape, lambda t, b, j: f_act( read_gate(t, b, j, i_gate_idx) + p_i[b, j] * c_state[t - 1, b, j] ), name="i_gate_p", tag=tag.INJECTIVE, ) f_gate = te.compute( gate_shape, lambda t, b, j: f_act( read_gate(t, b, j, f_gate_idx) + p_f[b, j] * c_state[t - 1, b, j] ), name="f_gate_p", tag=tag.INJECTIVE, ) else: i_gate = te.compute( gate_shape, lambda *i: f_act(read_gate(*i, i_gate_idx)), name="i_gate", tag=tag.INJECTIVE, ) f_gate = te.compute( gate_shape, lambda *i: f_act(read_gate(*i, f_gate_idx)), name="f_gate", tag=tag.INJECTIVE, ) g_gate = te.compute( gate_shape, lambda *i: g_act(read_gate(*i, g_gate_idx)), name="g_gate", tag=tag.INJECTIVE ) next_c = te.compute( gate_shape, lambda t, b, j: f_gate[t, b, j] * c_state[t - 1, b, j] + i_gate[t, b, j] * g_gate[t, b, j], name="next_c", ) if p_o is not None: o_gate = te.compute( gate_shape, lambda t, b, j: f_act(read_gate(t, b, j, o_gate_idx) + p_o[b, j] * next_c[t, b, j]), name="o_gate_p", tag=tag.INJECTIVE, ) else: o_gate = te.compute( gate_shape, lambda *i: f_act(read_gate(*i, o_gate_idx)), name="o_gate", tag=tag.INJECTIVE, ) next_h = te.compute(gate_shape, lambda *i: o_gate(*i) * h_act(next_c(*i)), name="next_h") # project hidden state back to proj_dim if projection matrix is present if proj is not None: kr = te.reduce_axis((0, hidden_dim), name="kh2p") next_h = te.compute( (scan_len, batch_size, proj_dim), lambda t, b, j: te.sum(next_h[t, b, kr] * proj[j, kr], axis=kr), name="next_h_proj", ) scan_h, scan_c = te.scan( [h_init, c_init], [next_h, next_c], [h_state, c_state], name="lstm_scan" ) # drop the initial values, TODO(@altanh): is there a better way? scan_h = te.compute( (seq_len, batch_size, proj_dim), lambda t, b, j: scan_h[t + 1, b, j], name="hidden_states" ) scan_c = te.compute( (seq_len, batch_size, hidden_dim), lambda t, b, j: scan_c[t + 1, b, j], name="cell_states" ) return scan_h, scan_c
https://github.com/zk-ml/tachikoma
python/tvm/topi/nn/mapping.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=invalid-name, line-too-long """Operators of one-to-one-mapping on the first input""" from __future__ import absolute_import as _abs import tvm from tvm import te from .. import tag @tvm.te.tag_scope(tag=tag.BROADCAST) def scale_shift_nchw(Input, Scale, Shift): """Batch normalization operator in inference. Parameters ---------- Input : tvm.te.Tensor 4-D input tensor, NCHW layout [batch, channel, height, width] Scale : tvm.te.Tensor Scale tensor, 1-D of size channel number Shift : tvm.te.Tensor Shift tensor, 1-D of size channel number Returns ------- Output : tvm.te.Tensor Output tensor, layout is NCHW """ return te.compute( Input.shape, lambda b, c, i, j: Input[b, c, i, j] * Scale[c] + Shift[c], name="ScaleShift" ) @tvm.te.tag_scope(tag=tag.BROADCAST) def scale_shift_nhwc(Input, Scale, Shift): """Batch normalization operator in inference. Parameters ---------- Input : tvm.te.Tensor 4-D input tensor, NHWC layout [batch, height, width, channel] Scale : tvm.te.Tensor Scale tensor, 1-D of size channel number Shift : tvm.te.Tensor Shift tensor, 1-D of size channel number Returns ------- Output : tvm.te.Tensor Output tensor, layout is NHWC """ return te.compute( Input.shape, lambda b, i, j, c: Input[b, i, j, c] * Scale[c] + Shift[c], name="ScaleShift" ) @tvm.te.tag_scope(tag=tag.BROADCAST) def scale_shift_nchwc(Input, Scale, Shift): """Batch normalization operator in inference. Parameters ---------- Input : tvm.te.Tensor 5-D input tensor, NCHWc layout [batch, channel_chunk, height, width, channel_block] Scale : tvm.te.Tensor Scale tensor, 2-D of size [channel_chunk, channel_block] Shift : tvm.te.Tensor Shift tensor, 2-D of size [channel_chunk, channel_block] Returns ------- Output : tvm.te.Tensor Output tensor, layout is NHWC """ return te.compute( Input.shape, lambda b, cc, i, j, cb: Input[b, cc, i, j, cb] * Scale[cc, cb] + Shift[cc, cb], name="ScaleShift", )
https://github.com/zk-ml/tachikoma
python/tvm/topi/nn/pad.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """Pad the data by constant value """ from __future__ import absolute_import as _abs import tvm from tvm import te from .. import tag from ..utils import equal_const_int @tvm.te.tag_scope(tag=tag.INJECTIVE + ",pad") def pad(data, pad_before, pad_after=None, pad_value=0.0, name="PadInput", attrs=None): """Pad Input with zeros. Parameters ---------- data : tvm.te.Tensor n-D input, can be any layout. pad_before : list / tuple of n ints Pad width on each dimension to pad the before the axis begin. pad_after : list / tuple of n ints, optional Pad width each dimension to pad the after the axis end. pad_value : float, optional The value to be padded. name : str, optional The name prefix operators generated Returns ------- Output : tvm.te.Tensor n-D, the same layout as Input. """ n = len(data.shape) pad_after = pad_after if pad_after else pad_before if len(pad_before) != n: raise ValueError( "Input dimension and pad_before dismatch : %d vs %d" % (n, len(pad_before)) ) if len(pad_after) != n: raise ValueError("Input dimension and pad_after dismatch : %d vs %d" % (n, len(pad_before))) ana = tvm.arith.Analyzer() dshape = [] for dim in data.shape: if isinstance(dim, tvm.tir.Any): dshape.append(tvm.te.size_var("dim")) else: dshape.append(dim) out_shape = tuple(ana.simplify(dshape[i] + pad_before[i] + pad_after[i]) for i in range(n)) pad_value = ( pad_value if isinstance(pad_value, tvm.tir.PrimExpr) else tvm.tir.const(pad_value, data.dtype) ) def _pad(*indices): not_zero = [] index_tuple = [] for i in range(n): if equal_const_int(pad_before[i], 0) and equal_const_int(pad_after[i], 0): index_tuple.append(indices[i]) else: index_tuple.append(indices[i] - pad_before[i]) not_zero.append(indices[i] >= pad_before[i]) not_zero.append(indices[i] < data.shape[i] + pad_before[i]) if not_zero: not_zero = tvm.tir.all(*not_zero) return tvm.tir.if_then_else(not_zero, data(*index_tuple), pad_value) return data(*index_tuple) return te.compute(out_shape, _pad, name=name, attrs=attrs) @tvm.te.tag_scope(tag=tag.INJECTIVE + ",pad") def mirror_pad(data, pad_before, pad_after=None, mode="SYMMETRIC", name="MirrorPadInput"): """Pad Input with mirroring either symmetric or reflected. Parameters ---------- data : tvm.te.Tensor n-D input, can be any layout. pad_before : list / tuple of n ints Pad width on each dimension to pad the before the axis begin. pad_after : list / tuple of n ints, optional Pad width each dimension to pad the after the axis end. mode: str, optional Type of mirror padding to apply. Must be SYMMETRIC or REFLECT name : str, optional The name prefix operators generated Returns ------- Output : tvm.te.Tensor n-D, the same layout as Input. """ n = len(data.shape) pad_after = pad_after if pad_after else pad_before if len(pad_before) != n: raise ValueError( "Input dimension and pad_before dismatch : %d vs %d" % (n, len(pad_before)) ) if len(pad_after) != n: raise ValueError("Input dimension and pad_after dismatch : %d vs %d" % (n, len(pad_before))) ana = tvm.arith.Analyzer() out_shape = tuple(ana.simplify(data.shape[i] + pad_before[i] + pad_after[i]) for i in range(n)) assert mode in ("SYMMETRIC", "REFLECT") mode = int(mode == "SYMMETRIC") def _pad(*indices): index_tuple = [] above = [] below = [] for i in range(n): if equal_const_int(pad_before[i], 0) and equal_const_int(pad_after[i], 0): index_tuple.append(indices[i]) above.append(False) below.append(False) else: index_tuple.append(indices[i] - pad_before[i]) above.append(indices[i] >= data.shape[i] + pad_before[i]) below.append(indices[i] < pad_before[i]) mapped_tuple = [] for i, axis in enumerate(index_tuple): mapped_axis = tvm.tir.if_then_else(below[i], -axis - mode, axis) mapped_axis = tvm.tir.if_then_else( above[i], (2 * (data.shape[i] - 1)) - axis + mode, mapped_axis ) mapped_tuple.append(mapped_axis) return data(*mapped_tuple) return te.compute(out_shape, _pad, name=name)
https://github.com/zk-ml/tachikoma
python/tvm/topi/nn/pooling.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """TVM operator pooling compute.""" from __future__ import absolute_import from .. import cpp POOL_TYPE_CODE = {"avg": 0, "max": 1} def global_pool(data, pool_type, layout="NCHW"): """Perform global pooling on height and width dimension of data. It decides the height and width dimension according to the layout string, in which 'W' and 'H' means width and height respectively. Width and height dimension cannot be split. For example, NCHW, NCHW16c, etc. are valid for pool, while NCHW16w, NCHW16h are not. See parameter `layout` for more information of the layout string convention. Parameters ---------- data : tvm.te.Tensor n-D with shape of layout pool_type : str Pool type, 'max' or 'avg' layout : str Layout of the input data. The layout is supposed to be composed of upper cases, lower cases and numbers, where upper case indicates a dimension and the corresponding lower case with factor size indicates the split dimension. For example, NCHW16c can describe a 5-D tensor of [batch_size, channel, height, width, channel_block], in which channel_block=16 is a split of dimension channel. Returns ------- output : tvm.te.Tensor n-D in same layout with height and width dimension size of 1. e.g., for NCHW, the output shape will be [batch, channel, 1, 1] """ return cpp.nn.global_pool(data, POOL_TYPE_CODE[pool_type], layout) def pool_grad( grads, data, kernel, stride, padding, pool_type, ceil_mode=False, layout="NCHW", count_include_pad=True, ): """Gradient of pooling on height and width dimension of data. It decides the height and width dimension according to the layout string, in which 'W' and 'H' means width and height respectively. Width and height dimension cannot be split. For example, NCHW, NCHW16c, etc. are valid for pool, while NCHW16w, NCHW16h are not. See parameter `layout` for more information of the layout string convention. Parameters ---------- grads : tvm.te.Tensor n-D with shape of layout data : tvm.te.Tensor n-D with shape of layout kernel : list/tuple of two ints Kernel size, [kernel_height, kernel_width] stride : list/tuple of two ints Stride size, [stride_height, stride_width] padding : list/tuple of four ints Pad size, [pad_top, pad_left, pad_bottom, pad_right]] pool_type : str Pool type, 'max' or 'avg' ceil_mode : bool Whether to use ceil when calculating output size. layout: string Layout of the input data. The layout is supposed to be composed of upper cases, lower cases and numbers, where upper case indicates a dimension and the corresponding lower case with factor size indicates the split dimension. For example, NCHW16c can describe a 5-D tensor of [batch_size, channel, height, width, channel_block], in which channel_block=16 is a split of dimension channel. count_include_pad: bool Whether include padding in the calculation when pool_type is 'avg' Returns ------- output : tvm.te.Tensor n-D in the same layout """ return cpp.nn.pool_grad( grads, data, kernel, stride, padding, POOL_TYPE_CODE[pool_type], ceil_mode, layout, count_include_pad, ) def adaptive_pool(data, output_size, pool_type, layout="NCHW"): """Perform pooling on height and width dimension of data. The pooling kernel and stride sizes are automatically chosen for desired output sizes. It decides the height and width dimension according to the layout string, in which 'W' and 'H' means width and height respectively. Width and height dimension cannot be split. For example, NCHW, NCHW16c, etc. are valid for pool, while NCHW16w, NCHW16h are not. See parameter `layout` for more information of the layout string convention. Parameters ---------- data : tvm.te.Tensor n-D with shape of layout output_size : tuple of int output height and width. pool_type : str Pool type, 'max' or 'avg' layout: string Layout of the input data. The layout is supposed to be composed of upper cases, lower cases and numbers, where upper case indicates a dimension and the corresponding lower case with factor size indicates the split dimension. For example, NCHW16c can describe a 5-D tensor of [batch_size, channel, height, width, channel_block], in which channel_block=16 is a split of dimension channel. Returns ------- output : tvm.te.Tensor n-D in the same layout """ return cpp.nn.adaptive_pool(data, output_size, POOL_TYPE_CODE[pool_type], layout) def adaptive_pool3d(data, output_size, pool_type, layout="NCDHW"): """Perform pooling on three dimensional data. See the two dimensional version above for details. """ return cpp.nn.adaptive_pool3d(data, output_size, POOL_TYPE_CODE[pool_type], layout) def pool1d( data, kernel, stride, dilation, padding, pool_type, ceil_mode=False, layout="NCW", count_include_pad=True, ): """Perform pooling on width dimension of data. Width axis is determined according to the layout string. in which 'w' means width. Width dimension cannot be split. For example, NCW, NCW16c, etc. are valid for pool, while NCW16w is not. See parameter `layout` for more information of the layout string convention. Parameters ---------- data : tvm.te.Tensor n-D with shape of layout kernel : list/tuple of one int or int Kernel size, [kernel_width] stride : list/tuple of one int or int Stride size, [stride_width] dilation: list/tuple of two ints Dilation size, [dilation_height, dilation_width] padding : list/tuple of two ints Pad size, [pad_left, pad_right] pool_type : str Pool type, 'max' or 'avg' ceil_mode : bool Whether to use ceil when calculating output size. layout: string Layout of the input data. The layout is supposed to be composed of upper cases, lower cases and numbers, where upper case indicates a dimension and the corresponding lower case with factor size indicates the split dimension. For example, NCW16c can describe a 4-D tensor of [batch_size, channel, width, channel_block], in which channel_block=16 is a split of dimension channel. count_include_pad: bool Whether include padding in the calculation when pool_type is 'avg' Returns ------- output : tvm.te.Tensor n-D in the same layout """ if isinstance(kernel, int): kernel = [ kernel, ] if isinstance(stride, int): stride = [ stride, ] return cpp.nn.pool1d( data, kernel, stride, dilation, padding, POOL_TYPE_CODE[pool_type], ceil_mode, layout, count_include_pad, ) def pool2d( data, kernel, stride, dilation, padding, pool_type, ceil_mode=False, layout="NCHW", count_include_pad=True, ): """Perform pooling on height and width dimension of data. It decides the height and width dimension according to the layout string, in which 'W' and 'H' means width and height respectively. Width and height dimension cannot be split. For example, NCHW, NCHW16c, etc. are valid for pool, while NCHW16w, NCHW16h are not. See parameter `layout` for more information of the layout string convention. Parameters ---------- data : tvm.te.Tensor n-D with shape of layout kernel : list/tuple of two ints Kernel size, [kernel_height, kernel_width] stride : list/tuple of two ints Stride size, [stride_height, stride_width] dilation: list/tuple of two ints Dilation size, [dilation_height, dilation_width] padding : list/tuple of four ints Pad size, [pad_top, pad_left, pad_bottom, pad_right]] pool_type : str Pool type, 'max' or 'avg' ceil_mode : bool Whether to use ceil when calculating output size. layout: string Layout of the input data. The layout is supposed to be composed of upper cases, lower cases and numbers, where upper case indicates a dimension and the corresponding lower case with factor size indicates the split dimension. For example, NCHW16c can describe a 5-D tensor of [batch_size, channel, height, width, channel_block], in which channel_block=16 is a split of dimension channel. count_include_pad: bool Whether include padding in the calculation when pool_type is 'avg' Returns ------- output : tvm.te.Tensor n-D in the same layout """ return cpp.nn.pool2d( data, kernel, stride, dilation, padding, POOL_TYPE_CODE[pool_type], ceil_mode, layout, count_include_pad, ) def pool3d( data, kernel, stride, dilation, padding, pool_type, ceil_mode=False, layout="NCDHW", count_include_pad=True, ): """Perform pooling on depth, height and width dimension of data. It decides the depth, height and width dimension according to the layout string, in which 'D', 'W' and 'H' means depth, width and height respectively. Depth, width and height dimension cannot be split. For example, NCDHW, NCDHW16c, etc. are valid for pool, while NCDHW16d, NCDHW16w, NCDHW16h are not. See parameter `layout` for more information of the layout string convention. Parameters ---------- data : tvm.te.Tensor n-D with shape of layout kernel : list/tuple of three ints Kernel size, [kernel_depth, kernel_height, kernel_width] stride : list/tuple of three ints Stride size, [stride_depth, stride_height, stride_width] dilation: list/tuple of two ints Dilation size, [dilation_height, dilation_width] padding : list/tuple of six ints Pad size, [pad_front, pad_top, pad_left, pad_back, pad_bottom, pad_right] pool_type : str Pool type, 'max' or 'avg' ceil_mode : bool Whether to use ceil when calculating output size. layout: string Layout of the input data. The layout is supposed to be composed of upper cases, lower cases and numbers, where upper case indicates a dimension and the corresponding lower case with factor size indicates the split dimension. For example, NCDHW16c can describe a 6-D tensor of [batch_size, channel, depth, height, width, channel_block], in which channel_block=16 is a split of dimension channel. count_include_pad: bool Whether include padding in the calculation when pool_type is 'avg' Returns ------- output : tvm.te.Tensor n-D in the same layout """ return cpp.nn.pool3d( data, kernel, stride, dilation, padding, POOL_TYPE_CODE[pool_type], ceil_mode, layout, count_include_pad, )
https://github.com/zk-ml/tachikoma
python/tvm/topi/nn/qnn.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """Quantized Neural Network (QNN) Operators""" import tvm from tvm import te, tir, topi SQNN_DISABLE = 0 SQNN_INT8 = 1 SQNN_UINT8 = 2 SQNN_INT32 = 3 SQNN_DTYPE_TO_CODE = { "disable": SQNN_DISABLE, "int8": SQNN_INT8, "uint8": SQNN_UINT8, "int32": SQNN_INT32, } SQNN_CODE_TO_DTYPE = {v: k for k, v in SQNN_DTYPE_TO_CODE.items()} @tvm.te.tag_scope(tag=topi.tag.ELEMWISE) def simulated_quantize(data, out_dtype, output_scale=None, output_zero_point=None, axis=-1): """Simulated QNN quantize operator that mimics QNN outputs without changing datatype. The benefit of this operator over true QNN quantize is that this operator allows dynamic datatype selection and can operate on both per-channel and scalar scales and zero points while QNN quantize requires both of these to be fixed at compile time. Parameters ---------- data: tvm.te.Tensor An N-D input tensor to the operator. out_dtype: tvm.te.Tensor A scalar variable that indicates which datatype to simulate quantization with. Use SQNN_DTYPE_TO_CODE to convert a dtype string into the corresponding variable value. output_scale: tvm.te.Tensor, optional A scalar tensor representing the scale to use when quantizing to integer datatypes. When it contains more than a single value, N must match the number of channels in data. output_zero_point: tvm.te.Tensor, optional A 1-D tensor representing the zero point to use when quantizing to integer datatypes. When it contains more than a single value, N must match the number of channels in data. axis: int, optional The channel axis for quantization. Default value is -1 which corresponds to the last axis. """ # When disabled, just pass through the input values. def _compute_pass_through(value, *indices): return value[indices] # Simulate quantization for arbitrary integer datatypes. The computation for all datatypes is: # Q_output = clip((round(input_tensor/output_scale) + output_zero_point), # out_dtype::min, # out_dtype::max) def _compute_intn(dtype, value, *indices): assert output_scale is not None and output_zero_point is not None const_min = tvm.tir.min_value(dtype) const_max = tvm.tir.max_value(dtype) # Use indexmod to handle both scalar and per-channel QNN parameters. scale_idx = tir.indexmod(indices[axis], topi.shape(output_scale)[0]) zp_idx = tir.indexmod(indices[axis], topi.shape(output_zero_point)[0]) return te.max( te.min( te.round(value[indices] / output_scale[scale_idx]) + output_zero_point[zp_idx], const_max, ), const_min, ) # Use an if chain to dynamically return the proper quantization based on the input datatype. # This allows the op to compile once but apply different quantization approaches # using a variable datatype input. def _dispatch_sim_quantize(value): pass_through_value = te.compute( data.shape, lambda *indices: _compute_pass_through(value, *indices) ) int8_value = te.compute( data.shape, lambda *indices: tir.if_then_else( out_dtype.equal(SQNN_DTYPE_TO_CODE["int8"]), _compute_intn("int8", value, *indices), pass_through_value[indices], ), ) uint8_value = te.compute( data.shape, lambda *indices: tir.if_then_else( out_dtype.equal(SQNN_DTYPE_TO_CODE["uint8"]), _compute_intn("uint8", value, *indices), int8_value[indices], ), ) int32_value = te.compute( data.shape, lambda *indices: tir.if_then_else( out_dtype.equal(SQNN_DTYPE_TO_CODE["int32"]), _compute_intn("int32", value, *indices), uint8_value[indices], ), ) return int32_value return te.compute(data.shape, lambda *indices: _dispatch_sim_quantize(data)[indices]) @tvm.te.tag_scope(tag=topi.tag.ELEMWISE) def simulated_dequantize(data, in_dtype, input_scale=None, input_zero_point=None, axis=-1): """Simulated QNN dequantize operator that mimics QNN outputs without changing datatype. The benefit of this operator over true QNN dequantize is that this operator allows dynamic datatype selection and can operate on both per-channel and scalar scales and zero points while QNN dequantize requires both of these to be fixed at compile time. Parameters ---------- data: tvm.te.Tensor An N-D input tensor to the operator. in_dtype: tvm.te.Tensor A scalar variable that indicates which datatype to simulate dequantization with. Use SQNN_DTYPE_TO_CODE to convert a dtype string into the corresponding variable value. input_scale: tvm.te.Tensor, optional A scalar tensor representing the scale to use when dequantizing from integer datatypes. When it contains more than a single value, N must match the number of channels in data. input_zero_point: tvm.te.Tensor, optional A 1-D tensor representing the zero point to use when dequantizing from integer datatypes. When it contains more than a single value, N must match the number of channels in data. axis: int, optional The channel axis for quantization. Default value is -1 which corresponds to the last axis. """ # When disabled simply return the input tensor. def _compute_pass_through(value, *indices): return value[indices] # Simulate dequantization for arbitrary integer datatypes. The computation for all datatypes is: # DQ_output = (input - zero_point) * scale def _compute_intn(value, *indices): assert input_scale is not None and input_zero_point is not None # Use indexmod to handle both scalar and per-channel QNN parameters. scale_idx = tir.indexmod(indices[axis], topi.shape(input_scale)[0]) zp_idx = tir.indexmod(indices[axis], topi.shape(input_zero_point)[0]) return (value[indices] - input_zero_point[zp_idx]) * input_scale[scale_idx] # Use an if chain to dynamically return the proper dequantization based on the input datatype. # This allows the op to compile once but apply different quantization approaches # using a variable datatype input. def _dispatch_sim_dequantize(value): pass_through_value = te.compute( data.shape, lambda *indices: _compute_pass_through(value, *indices) ) intn_condition = tvm.te.any( in_dtype.equal(SQNN_DTYPE_TO_CODE["int8"]), in_dtype.equal(SQNN_DTYPE_TO_CODE["uint8"]), in_dtype.equal(SQNN_DTYPE_TO_CODE["int32"]), ) intn_value = te.compute( data.shape, lambda *indices: tir.if_then_else( intn_condition, _compute_intn(value, *indices), pass_through_value[indices], ), ) return intn_value return te.compute(data.shape, lambda *indices: _dispatch_sim_dequantize(data)[indices])
https://github.com/zk-ml/tachikoma
python/tvm/topi/nn/softmax.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=invalid-name """TVM operator for softmax and log_softmax compute.""" from __future__ import absolute_import import tvm from tvm import te, topi @tvm.te.tag_scope(tag="softmax_output") def softmax(x, axis=-1): """Perform softmax activation on the data. Parameters ---------- data : tvm.te.Tensor can be any dimension axis : int channel axis Returns ------- output : tvm.te.Tensor output shape is the same as input """ return softmax_common(x, axis, False) @tvm.te.tag_scope(tag="fast_softmax_output") def fast_softmax(x, axis=-1): """Perform softmax activation on the data. Use approximation to compute exponent for faster speed. Parameters ---------- data : tvm.te.Tensor can be any dimension axis : int channel axis Returns ------- output : tvm.te.Tensor output shape is the same as input """ return softmax_common(x, axis, True) def softmax_common(x, axis, use_fast_exp): """The common part of softmax and fast_softmax""" shape = x.shape if axis < 0: axis = len(shape) + axis if axis >= len(shape): ValueError("axis parameter should be less than input dim") k1 = te.reduce_axis((0, shape[axis]), name="k") k2 = te.reduce_axis((0, shape[axis]), name="k") def insert_reduce_index(indices, reduce_index): return indices[:axis] + (reduce_index,) + indices[axis:] def get_non_reduce_indices(indices): return tuple([var for (i, var) in enumerate(indices) if i != axis]) def _compute_max(*indices): eval_range = insert_reduce_index(indices, k1) return tvm.te.max(x[eval_range], axis=k1) def _compute_delta(max_elem, *indices): non_reduce_indices = get_non_reduce_indices(indices) return x[indices] - max_elem[non_reduce_indices] def _compute_exp(max_elem, *indices): non_reduce_indices = get_non_reduce_indices(indices) return te.exp(x[indices] - max_elem[non_reduce_indices]) def _compute_expsum(exp, *indices): eval_range = insert_reduce_index(indices, k2) return te.sum(exp[eval_range], axis=k2) def _normalize(exp, expsum, *indices): non_reduce_indices = get_non_reduce_indices(indices) return exp[indices] / expsum[non_reduce_indices] reduced_shape = tuple([dim for (i, dim) in enumerate(shape) if i != axis]) max_elem = te.compute(reduced_shape, _compute_max, name="T_softmax_maxelem") if use_fast_exp: delta = te.compute( shape, lambda *indices: _compute_delta(max_elem, *indices), name="T_softmax_delta" ) exp = topi.math.fast_exp(delta) else: exp = te.compute( shape, lambda *indices: _compute_exp(max_elem, *indices), name="T_softmax_exp" ) expsum = te.compute( reduced_shape, lambda *indices: _compute_expsum(exp, *indices), name="T_softmax_expsum" ) return te.compute( shape, lambda *indices: _normalize(exp, expsum, *indices), name="T_softmax_norm", attrs={"axis": axis}, ) @tvm.te.tag_scope(tag="log_softmax_output") def log_softmax(x, axis=-1): """Perform log softmax activation on the data Parameters ---------- data : tvm.te.Tensor N-D input data Returns ------- output : tvm.te.Tensor N-D output with same shape """ shape = x.shape if axis < 0: axis = len(shape) + axis if axis >= len(shape): ValueError("axis parameter should be less than input dim") k1 = te.reduce_axis((0, shape[axis]), name="k") k2 = te.reduce_axis((0, shape[axis]), name="k") def insert_reduce_index(indices, reduce_index): return indices[:axis] + (reduce_index,) + indices[axis:] def get_non_reduce_indices(indices): return tuple([var for (i, var) in enumerate(indices) if i != axis]) def _compute_max(*indices): eval_range = insert_reduce_index(indices, k1) return tvm.te.max(x[eval_range], axis=k1) def _compute_expsum(max_elem, *indices): eval_range = insert_reduce_index(indices, k2) return te.sum(te.exp(x[eval_range] - max_elem[indices]), axis=k2) def _normalize(max_elem, expsum, *indices): non_reduce_indices = get_non_reduce_indices(indices) return x[indices] - max_elem[non_reduce_indices] - te.log(expsum[non_reduce_indices]) reduced_shape = tuple([dim for (i, dim) in enumerate(shape) if i != axis]) max_elem = te.compute(reduced_shape, _compute_max, name="T_softmax_maxelem") expsum = te.compute(reduced_shape, lambda *indices: _compute_expsum(max_elem, *indices)) return te.compute( shape, lambda *indices: _normalize(max_elem, expsum, *indices), attrs={"axis": axis}, )
https://github.com/zk-ml/tachikoma
python/tvm/topi/nn/space_to_batch_nd.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=invalid-name """TVM operator space_to_batch_nd compute.""" from __future__ import absolute_import from . import cpp def space_to_batch_nd(data, block_shape, pad_before, pad_after, pad_value=0.0): """Perform batch to space transformation on the data Parameters ---------- data : tvm.te.Tensor N-D Tensor with shape [batch, spatial_shape, remaining_shapes], where spatial_shape has M dimensions. block_shape : list of ints list of size [M] where M is number of spatial dims, specifies block size for each spatial dimension. pad_before : list of ints list of shape [M] where M is number of spatial dims, specifies zero-padding size before each spatial dimension. pad_after : list of ints list of shape [M] where M is number of spatial dims, specifies zero-padding size after each spatial dimension. pad_value : float, optional The value used for padding. Returns ------- output : tvm.te.Tensor """ return cpp.nn.space_to_batch_nd(data, block_shape, pad_before, pad_after, pad_value)
https://github.com/zk-ml/tachikoma
python/tvm/topi/nn/space_to_depth.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=invalid-name """TVM operator space_to_depth compute.""" from __future__ import absolute_import import tvm from tvm import te from .. import tag def space_to_depth(data, block_size, layout="NCHW"): """Perform space to depth transformation on the data Parameters ---------- data : tvm.te.Tensor 4-D tensor in either NCHW or NHWC layout. block_size : int Size of blocks to decompose into channel dimension. layout : string Either NCHW or NHWC, indicating data layout. Returns ------- output : tvm.te.Tensor Output of shape [N, C * block_size**2, H / block_size, W / block_size] """ if layout == "NCHW": in_n, in_c, in_h, in_w = data.shape output_shape = [ in_n, in_c * block_size * block_size, tvm.tir.truncdiv(in_h, block_size), tvm.tir.truncdiv(in_w, block_size), ] elif layout == "NHWC": in_n, in_h, in_w, in_c = data.shape output_shape = [ in_n, tvm.tir.truncdiv(in_h, block_size), tvm.tir.truncdiv(in_w, block_size), in_c * block_size * block_size, ] else: raise ValueError("Only NCHW and NHWC layouts are currently supported.") def _get_indices(*indices): if layout == "NCHW": n, c, y, x = indices elif layout == "NHWC": n, y, x, c = indices return n, c, y, x def _get_pixel(n, c, y, x): block_offset = tvm.tir.truncdiv(c, in_c) channel_idx = tvm.tir.truncmod(c, in_c) x_idx = tvm.tir.truncmod(block_offset, block_size) y_idx = tvm.tir.truncdiv(block_offset, block_size) if layout == "NCHW": output = data(n, channel_idx, y_idx + (y * block_size), x_idx + (x * block_size)) else: output = data(n, y_idx + (y * block_size), x_idx + (x * block_size), channel_idx) return output def _compute(*indices): n, c, y, x = _get_indices(*indices) return _get_pixel(n, c, y, x) return te.compute(output_shape, _compute, name="space_to_depth", tag=tag.INJECTIVE)
https://github.com/zk-ml/tachikoma
python/tvm/topi/nn/sparse.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """Sparse operators""" from __future__ import absolute_import import tvm from tvm import te, auto_scheduler from ..utils import get_const_tuple def sparse_dense_sp_rhs(data, weight_data, weight_indices, weight_indptr): """ Computes sparse-dense matrix multiplication of `data` and `(weight_data, weight_indices, weight_indptr).T` Parameters ---------- data : tvm.te.Tensor 2-D with shape [M, K] weight_data : tvm.te.Tensor 1-D with shape [nnz] (CSR) or 3-D with shape [num_blocks, bs_r, bs_c] (BSR) weight_indices : tvm.te.Tensor 1-D with shape [nnz] (CSR) or 1-D with shape [num_blocks] (BSR) weight_indptr : tvm.te.Tensor 1-D with shape [N + 1] (CSR) or 1-D with shape [(N + 1) // bs_r] (BSR) Returns ------- output : tvm.te.Tensor 2-D with shape [M, N] """ assert len(weight_data.shape) in (1, 3) if len(weight_data.shape) == 1: func = _sparse_dense_sp_rhs_csrmm if len(weight_data.shape) == 3: func = _sparse_dense_sp_rhs_bsrmm return func(data, weight_data, weight_indices, weight_indptr) def sparse_dense_sp_lhs(data_data, data_indices, data_indptr, weight): """ Computes sparse-dense matrix multiplication of `(data_data, data_indices, data_indptr)` and `weight.T` Parameters ---------- data_data: 1-D with shape [nnz] (CSR) or 3-D with shape [num_blocks, bs_r, bs_c] (BSR) data_indices: 1-D with shape [nnz] (CSR) or 1-D with shape [num_blocks] (BSR) data_indptr: 1-D with shape [M + 1] (CSR) or 1-D with shape [(M + 1) // bs_r] (BSR) weight: 2-D with shape [N, K] Returns ------- output : tvm.te.Tensor 2-D with shape [M, N] """ assert len(data_data.shape) in (1, 3) if len(data_data.shape) == 1: func = _sparse_dense_sp_lhs_csrmm if len(data_data.shape) == 3: func = _sparse_dense_sp_lhs_bsrmm return func(data_data, data_indices, data_indptr, weight) # pylint: disable=no-else-return,inconsistent-return-statements def sparse_dense(dense_data, sparse_data, sparse_indices, sparse_indptr, sparse_lhs=False): """ Computes sparse-dense matrix multiplication of `data` and `(weight_data, weight_indices, weight_indptr).T`, if sparse_lhs=False or Computes sparse-dense matrix multiplication of `(data_data, data_indices, data_indptr)` and `weight.T`, if sparse_lhs=True Parameters ---------- dense_data : tvm.te.Tensor 2-D with shape [M, K] sparse_data : tvm.te.Tensor 1-D with shape [nnz] (CSR) or 3-D with shape [num_blocks, bs_r, bs_c] (BSR) sparse_indices : tvm.te.Tensor 1-D with shape [nnz] (CSR) or 1-D with shape [num_blocks] (BSR) sparse_indptr : tvm.te.Tensor 1-D with shape [N + 1] (CSR) or 1-D with shape [(N + 1) // bs_r] (BSR) sparse_lhs : bool, optional Indicates whether lhs or rhs matrix is sparse. Default value is False. Returns ------- output : tvm.te.Tensor 2-D with shape [M, N] """ if sparse_lhs: return sparse_dense_sp_lhs(sparse_data, sparse_indices, sparse_indptr, dense_data) else: return sparse_dense_sp_rhs(dense_data, sparse_data, sparse_indices, sparse_indptr) def _sparse_dense_sp_lhs_csrmm(data_data, data_indices, data_indptr, weight): oshape = (get_const_tuple(data_indptr.shape)[0] - 1, get_const_tuple(weight.shape)[0]) def f(row, i): row_start = data_indptr[row] row_end = data_indptr[row + 1] row_elems = row_end - row_start elem_idx = te.reduce_axis((0, row_elems), name="elem_idx") elem = row_start + elem_idx a_val = data_data[elem] weight_val = weight[i, data_indices[elem]] return te.sum(a_val * weight_val, axis=elem_idx) return te.compute(oshape, f, tag="sparse_dense_sp_lhs_csrmm") def _sparse_dense_sp_rhs_csrmm(data, weight_data, weight_indices, weight_indptr): oshape = (get_const_tuple(data.shape)[0], get_const_tuple(weight_indptr.shape)[0] - 1) def f(i, row): row_start = weight_indptr[row] row_end = weight_indptr[row + 1] row_elems = row_end - row_start elem_idx = te.reduce_axis((0, row_elems), name="elem_idx") elem = row_start + elem_idx a_val = weight_data[elem] weight_val = data[i, weight_indices[elem]] return te.sum(a_val * weight_val, axis=elem_idx) return te.compute(oshape, f, tag="sparse_dense_sp_rhs_csrmm") def _sparse_dense_sp_lhs_bsrmm(data_data, data_indices, data_indptr, weight): (m, _) = get_const_tuple(weight.shape) (_, bs_r, bs_c) = get_const_tuple(data_data.shape) (num_blocks_plus_1,) = get_const_tuple(data_indptr.shape) num_blocks = num_blocks_plus_1 - 1 def _compute_block(nb_j, j, i): row_start = data_indptr[nb_j] row_end = data_indptr[nb_j + 1] row_elems = row_end - row_start elem_idx = te.reduce_axis((0, row_elems), name="elem_idx") block_offset = row_start + elem_idx c = te.reduce_axis((0, bs_c), name="c") block_j = data_indices[block_offset] block_ij_val = data_data[block_offset][j][c] x_val = weight[i, bs_c * block_j + c] return te.sum(block_ij_val * x_val, axis=[elem_idx, c]) idxd = tvm.tir.indexdiv idxm = tvm.tir.indexmod bsrmm_block = te.compute( (num_blocks, bs_r, m), _compute_block, tag="sparse_dense_sp_lhs_bsrmm_block" ) return te.compute( (num_blocks * bs_r, m), lambda m, n: bsrmm_block[idxd(m, bs_r), idxm(m, bs_r), n], tag="sparse_dense_sp_lhs_bsrmm", ) def _sparse_dense_sp_rhs_bsrmm(data, weight_data, weight_indices, weight_indptr): (m, k) = get_const_tuple(data.shape) (_, bs_r, bs_c) = get_const_tuple(weight_data.shape) (num_blocks_plus_1,) = get_const_tuple(weight_indptr.shape) num_blocks = num_blocks_plus_1 - 1 def _compute_block(i, nb_j, j): row_start = weight_indptr[nb_j] row_end = weight_indptr[nb_j + 1] row_elems = row_end - row_start elem_idx = te.reduce_axis((0, row_elems), name="elem_idx") block_offset = row_start + elem_idx c = te.reduce_axis((0, bs_c), name="c") block_j = weight_indices[block_offset] block_ij_val = weight_data[block_offset][j][c] x_val = data[i, bs_c * block_j + c] return te.sum(block_ij_val * x_val, axis=[elem_idx, c]) idxd = tvm.tir.indexdiv idxm = tvm.tir.indexmod bsrmm_block = te.compute( (m, num_blocks, bs_r), _compute_block, tag="sparse_dense_sp_rhs_bsrmm_block", attrs={"FLOP": 2 * m * num_blocks * bs_r * k}, ) return te.compute( (m, num_blocks * bs_r), lambda m, n: bsrmm_block[m, idxd(n, bs_r), idxm(n, bs_r)], tag="sparse_dense_sp_rhs_bsrmm", ) def sparse_transpose(sparse_data, sparse_indices, sparse_indptr): """ Transpose a square sparse matrix, `A` is an n-by-n sparse matrix in the CSR format. ** Currently only support Square Matrices ** Parameters ---------- sparse_data : tvm.te.Tensor 1-D with shape [nonzeros] sparse_indices : tvm.te.Tensor 1-D with shape [nonzeros], dtype of 'int32' sparse_indptr : tvm.te.Tensor 1-D with shape [n+1], dtype of 'int32' Returns ------- out_data : tvm.te.Tensor 1-D with shape [nonzeros] out_indices : tvm.te.Tensor 1-D with shape [nonzeros], dtype of 'int32' out_indptr : tvm.te.Tensor 1-D with shape [n+1], dtype of 'int32' """ assert len(sparse_data.shape) == 1, "error in data dimension" assert len(sparse_indices.shape) == 1, "error in indices dimension" assert len(sparse_indptr.shape) == 1, "error in indptr dimension" nnz = get_const_tuple(sparse_data.shape)[0] n = get_const_tuple(sparse_indptr.shape)[0] - 1 output_shape = [(nnz,), (nnz,), (n + 1,)] # TODO: Add BSR transpose support output_data, output_indices, output_indptr = te.extern( shape=output_shape, inputs=[sparse_data, sparse_indices, sparse_indptr], fcompute=lambda ins, outs: _csr_transpose_ir( ins[0], ins[1], ins[2], outs[0], outs[1], outs[2] ), tag="sparse_transpose_csr", dtype=[sparse_data.dtype, "int32", "int32"], name="out", ) return [output_data, output_indices, output_indptr] def _csr_transpose_ir(data, indices, indptr, out_data, out_indices, out_indptr): """define ir for csr_transpose""" irb = tvm.tir.ir_builder.create() data_ptr = irb.buffer_ptr(data) indices_ptr = irb.buffer_ptr(indices) indptr_ptr = irb.buffer_ptr(indptr) out_data_ptr = irb.buffer_ptr(out_data) out_indices_ptr = irb.buffer_ptr(out_indices) out_indptr_ptr = irb.buffer_ptr(out_indptr) n = get_const_tuple(indptr.shape)[0] - 1 nnz = get_const_tuple(data.shape)[0] with irb.for_range(0, n, kind="parallel", name="col") as col: out_indptr_ptr[col] = 0 with irb.for_range(0, nnz, kind="serial", name="nz_idx") as nz_idx: out_indptr_ptr[indices_ptr[nz_idx]] += 1 cumsum = irb.allocate("int32", (1,), name="cumsum", scope="local") temp = irb.allocate("int32", (1,), name="temp", scope="local") cumsum[0] = 0 with irb.for_range(0, n, kind="serial", name="col") as col: temp[0] = out_indptr_ptr[col] out_indptr_ptr[col] = cumsum[0] cumsum[0] += temp[0] out_indptr_ptr[n] = nnz with irb.for_range(0, n, kind="serial", name="row") as row: offset = indptr_ptr[row] diff = indptr_ptr[row + 1] - indptr_ptr[row] with irb.for_range(0, diff, kind="serial", name="idx") as idx: real_idx = offset + idx col = indices_ptr[real_idx] dest = out_indptr_ptr[col] out_indices_ptr[dest] = row out_data_ptr[dest] = data_ptr[real_idx] out_indptr_ptr[col] += 1 last = irb.allocate("int32", (1,), name="last", scope="local") temp2 = irb.allocate("int32", (1,), name="temp2", scope="local") last[0] = 0 with irb.for_range(0, n, kind="serial", name="col") as col: temp2[0] = out_indptr_ptr[col] out_indptr_ptr[col] = last[0] last[0] = temp2[0] return irb.get() @tvm.target.generic_func def sparse_dense_alter_layout(_attrs, _inputs, _tinfos, _out_type): """Change Sparse Dense layout. This is used for modifying the inputs weights so they are more amenable for the target. Parameters ---------- attrs : tvm.ir.Attrs Attributes of current convolution inputs : tvm.relay.Expr Grouped input symbols tinfos : list Input shape and dtype out_type: type The output type Note ---- Unlike other TOPI functions, this function operates on both graph level and operator level. """ return None @auto_scheduler.register_task_input_check_func def try_get_sparse_input(args): """Analyze the input data from the given args. Parameters ---------- args : List[Tensor] Input/output Tensor of a TVM subgraph. Returns ------- Dict[Tensor, str] : Map from the input Tensor to its buffer name. Notes ----- The buffer name is specially designed, and these buffer should be provided in `SearchTask(..., task_inputs={...})`. """ sparse_prefix = sparse_data = sparse_indices = sparse_indptr = None def _process_inputs(input_tensors, m, n, prefix_init): nonlocal sparse_prefix nonlocal sparse_data nonlocal sparse_indices nonlocal sparse_indptr assert len(input_tensors) == 4 unsure_tensors = list(input_tensors) # Get the Dense data dense_data = None for tensor in unsure_tensors: if len(tensor.shape) == 2: assert dense_data is None dense_data = tensor assert m == dense_data.shape[0] k = dense_data.shape[1] unsure_tensors.remove(dense_data) # Get the Sparse data sparse_data = None for tensor in unsure_tensors: if len(tensor.shape) == 3: assert sparse_data is None sparse_data = tensor block_size, bs_r, bs_c = sparse_data.shape unsure_tensors.remove(sparse_data) # Get the Sparse indptr & indices sparse_indices = None for tensor in unsure_tensors: assert len(tensor.shape) == 1 if tensor.shape[0] == block_size: assert sparse_indices is None sparse_indices = tensor unsure_tensors.remove(sparse_indices) assert len(unsure_tensors) == 1 sparse_indptr = unsure_tensors[0] # Generate the sparse_prefix density = 1.0 for i in sparse_data.shape: density *= i density /= k * n density = density.value sparse_prefix = "%s_%d_%d_%d_%d_%d_%d_" % ( prefix_init, n, k, bs_r, bs_c, sparse_indices.shape[0], sparse_indptr.shape[0], ) visited = set() def _traverse(t): # We cannot directly add tensors to the set, because the comparison of # two tensors with ndim=0 is ambiguous. assert t.handle is not None if t.handle.value in visited: return if isinstance(t.op, te.ComputeOp): # TODO(jcf94): Currently only support to one sparse op, add more support here if t.op.tag == "sparse_dense_sp_rhs_bsrmm": m, n = t.shape assert len(t.op.input_tensors) == 1 block_tensor = t.op.input_tensors[0] _process_inputs(block_tensor.op.input_tensors, m, n, "sparse_dense_bsr") if sparse_prefix is not None: # Early stop if we find a sparse_prefix # Notice: If any workload has more than one sparse input, this may get problem return for x in t.op.input_tensors: _traverse(x) visited.add(t.handle.value) try: for arg in args: _traverse(arg) # pylint: disable=broad-except except Exception: return {} if sparse_data is None or sparse_indices is None or sparse_indptr is None: return {} sparse_input_map = {} sparse_input_map[sparse_data] = sparse_prefix + "W_data" sparse_input_map[sparse_indices] = sparse_prefix + "W_indices" sparse_input_map[sparse_indptr] = sparse_prefix + "W_indptr" return sparse_input_map def _sparse_conv2d_bsr_compute_nhwc(data, weight_data, weight_indices, weight_indptr): (m, h, w, k) = get_const_tuple(data.shape) # pylint: disable=C0103 if len(weight_data.shape) == 2: _, bs_r = get_const_tuple(weight_data.shape) elif len(weight_data.shape) == 3: _, bs_r, bs_c = get_const_tuple(weight_data.shape) (num_blocks_plus_1,) = get_const_tuple(weight_indptr.shape) num_blocks = num_blocks_plus_1 - 1 def _compute_block(i, h, w, nb_j, j): # pylint: disable=C0103 row_start = weight_indptr[nb_j] row_end = weight_indptr[nb_j + 1] row_elems = row_end - row_start elem_idx = te.reduce_axis((0, row_elems), name="elem_idx") block_offset = row_start + elem_idx block_j = weight_indices[block_offset] if len(weight_data.shape) == 3: c = te.reduce_axis((0, bs_c), name="c") block_ij_val = weight_data[block_offset][j][c] x_val = data[i, h, w, bs_c * block_j + c] return te.sum(block_ij_val * x_val, axis=[elem_idx, c]) else: block_ij_val = weight_data[block_offset][j] x_val = data[i, h, w, block_j] return te.sum(block_ij_val * x_val, axis=[elem_idx]) idxd = tvm.tir.indexdiv idxm = tvm.tir.indexmod bsrmm_block = te.compute( (m, h, w, num_blocks, bs_r), _compute_block, tag="sparse_conv2d_sp_bsrmm_block", attrs={"FLOP": 2 * m * num_blocks * bs_r * k * h * w}, ) return te.compute( (m, h, w, num_blocks * bs_r), lambda m, h, w, n: bsrmm_block[m, h, w, idxd(n, bs_r), idxm(n, bs_r)], tag="sparse_conv2d_sp_bsrmm", name="sparse_conv2d", attrs={"layout": "NHWC"}, ) def _sparse_conv2d_bsr_compute_nchw(data, weight_data, weight_indices, weight_indptr): (m, k, h, w) = get_const_tuple(data.shape) # pylint: disable=C0103 if len(weight_data.shape) == 2: _, bs_r = get_const_tuple(weight_data.shape) elif len(weight_data.shape) == 3: _, bs_r, bs_c = get_const_tuple(weight_data.shape) (num_blocks_plus_1,) = get_const_tuple(weight_indptr.shape) num_blocks = num_blocks_plus_1 - 1 def _compute_block(i, nb_j, j, h, w): # pylint: disable=C0103 row_start = weight_indptr[nb_j] row_end = weight_indptr[nb_j + 1] row_elems = row_end - row_start elem_idx = te.reduce_axis((0, row_elems), name="elem_idx") block_offset = row_start + elem_idx block_j = weight_indices[block_offset] if len(weight_data.shape) == 3: c = te.reduce_axis((0, bs_c), name="c") block_ij_val = weight_data[block_offset][j][c] x_val = data[i, bs_c * block_j + c, h, w] return te.sum(block_ij_val * x_val, axis=[elem_idx, c]) else: block_ij_val = weight_data[block_offset][j] x_val = data[i, block_j, h, w] return te.sum(block_ij_val * x_val, axis=[elem_idx]) idxd = tvm.tir.indexdiv idxm = tvm.tir.indexmod bsrmm_block = te.compute( (m, num_blocks, bs_r, h, w), _compute_block, tag="sparse_conv2d_sp_bsrmm_block", attrs={"FLOP": 2 * m * num_blocks * bs_r * k * h * w}, ) return te.compute( (m, num_blocks * bs_r, h, w), lambda m, n, h, w: bsrmm_block[m, idxd(n, bs_r), idxm(n, bs_r), h, w], tag="sparse_conv2d_sp_bsrmm", name="sparse_conv2d", attrs={"layout": "NCHW"}, ) def sparse_conv2d( dense_data, sparse_data, sparse_indices, sparse_indptr, layout="NHWC", kernel_size=1 ): """ Computes sparse-conv2d(1*1) of ``data`` and ``(weight_data, weight_indices, weight_indptr)`` Parameters ---------- dense_data : tvm.te.Tensor 4-D with shape ``[M, H, W, K]`` (layout=NHWC) 4-D with shape ``[M, K, H, W]`` (layout=NCHW) sparse_data : tvm.te.Tensor 2-D with shape ``[num_blocks, bs_r]`` (BSR) 3-D with shape ``[num_blocks, bs_r, bs_c]`` (BSR) sparse_indices : tvm.te.Tensor 1-D with shape ``[num_blocks]`` (BSR) sparse_indptr : tvm.te.Tensor 1-D with shape ``[(N + 1) // bs_r]`` (BSR) layout : str layout of data Returns ------- output : tvm.te.Tensor 4-D with shape [M, H, W, N] (layout=NHWC) 4-D with shape [M, N, H ,W] (layout=NCHW) """ if kernel_size == 1: if layout == "NHWC": return _sparse_conv2d_bsr_compute_nhwc( dense_data, sparse_data, sparse_indices, sparse_indptr ) elif layout == "NCHW": return _sparse_conv2d_bsr_compute_nchw( dense_data, sparse_data, sparse_indices, sparse_indptr ) else: raise ValueError("Unsupport Layout %s" % layout) @auto_scheduler.register_task_input_check_func def try_get_conv2d_sparse_input(args): """Analyze the input data from the given args. Parameters ---------- args : List[Tensor] Input/output Tensor of a TVM subgraph. Returns ------- Dict[Tensor, str] : Map from the input Tensor to its buffer name. Notes ----- The buffer name is specially designed, and these buffer should be provided in `SearchTask(..., task_inputs={...})`. """ sparse_prefix = sparse_data = sparse_indices = sparse_indptr = None def _process_inputs(input_tensors, m, h, w, n, prefix_init, layout): # pylint: disable=C0103 nonlocal sparse_prefix nonlocal sparse_data nonlocal sparse_indices nonlocal sparse_indptr assert len(input_tensors) == 4 unsure_tensors = list(input_tensors) # Get the Dense data dense_data = None for tensor in unsure_tensors: if len(tensor.shape) == 4: assert dense_data is None dense_data = tensor if layout == "NHWC": assert m == dense_data.shape[0] assert h == dense_data.shape[1] assert w == dense_data.shape[2] k = dense_data.shape[3] elif layout == "NCHW": assert m == dense_data.shape[0] assert h == dense_data.shape[2] assert w == dense_data.shape[3] k = dense_data.shape[1] unsure_tensors.remove(dense_data) # Get the Sparse data sparse_data = None for tensor in unsure_tensors: if len(tensor.shape) == 3: assert sparse_data is None sparse_data = tensor block_size, bs_r, bs_c = sparse_data.shape if len(tensor.shape) == 2: assert sparse_data is None sparse_data = tensor block_size, bs_r = sparse_data.shape bs_c = 1 unsure_tensors.remove(sparse_data) # Get the Sparse indptr & indices sparse_indices = None for tensor in unsure_tensors: assert len(tensor.shape) == 1 if tensor.shape[0] == block_size: assert sparse_indices is None sparse_indices = tensor unsure_tensors.remove(sparse_indices) assert len(unsure_tensors) == 1 sparse_indptr = unsure_tensors[0] # Generate the sparse_prefix density = 1.0 for i in sparse_data.shape: density *= i density /= k * n density = density.value sparse_prefix = "%s_%d_%d_%d_%d_%d_%d_" % ( prefix_init, n, k, bs_r, bs_c, sparse_indices.shape[0], sparse_indptr.shape[0], ) visited = set() def _traverse(t): # We cannot directly add tensors to the set, because the comparison of # two tensors with ndim=0 is ambiguous. assert t.handle is not None if t.handle.value in visited: return if isinstance(t.op, te.ComputeOp): if t.op.tag == "sparse_conv2d_sp_bsrmm": m, h, w, n = t.shape # pylint: disable=C0103 assert len(t.op.input_tensors) == 1 block_tensor = t.op.input_tensors[0] _process_inputs( block_tensor.op.input_tensors, m, h, w, n, "sparse_conv2d_bsr", t.op.attrs["layout"], ) if sparse_prefix is not None: # Early stop if we find a sparse_prefix # Notice: If any workload has more than one sparse input, this may get problem return for x in t.op.input_tensors: _traverse(x) visited.add(t.handle.value) try: for arg in args: _traverse(arg) # pylint: disable=broad-except except Exception: return {} if sparse_data is None or sparse_indices is None or sparse_indptr is None: return {} sparse_input_map = {} sparse_input_map[sparse_data] = sparse_prefix + "W_data" sparse_input_map[sparse_indices] = sparse_prefix + "W_indices" sparse_input_map[sparse_indptr] = sparse_prefix + "W_indptr" return sparse_input_map def sparse_add(dense_data, sparse_data, sparse_indices, sparse_indptr): """ Computes sparse-dense addition Parameters ---------- dense_data : tvm.te.Tensor 2-D with shape [M, N] sparse_data : tvm.te.Tensor 1-D with shape [nnz] (CSR) sparse_indices : tvm.te.Tensor 1-D with shape [nnz] (CSR) sparse_indptr : tvm.te.Tensor 1-D with shape [M + 1] (CSR) Returns ------- output : tvm.te.Tensor 2-D with shape [M, N] """ # TODO(ANSHUMAN87): support BSR format too assert len(sparse_data.shape) == 1, "only CSR format is supported" return _sparse_add_csr(dense_data, sparse_data, sparse_indices, sparse_indptr) def _sparse_add_csr(dense_data_inp, sparse_data_inp, sparse_indices_inp, sparse_indptr_inp): oshape = get_const_tuple(dense_data_inp.shape) def _csr_add_ir(dense_data, sparse_data, sparse_indices, sparse_indptr, out_data): irb = tvm.tir.ir_builder.create() dense_data_ptr = irb.buffer_ptr(dense_data) sparse_data_ptr = irb.buffer_ptr(sparse_data) sparse_indices_ptr = irb.buffer_ptr(sparse_indices) sparse_indptr_ptr = irb.buffer_ptr(sparse_indptr) out_data_ptr = irb.buffer_ptr(out_data) with irb.for_range(0, oshape[0], kind="vectorize", name="row") as row: with irb.for_range(0, oshape[1], kind="parallel", name="col") as col: out_data_ptr[row, col] = dense_data_ptr[row, col] with irb.for_range(0, oshape[0], kind="parallel", name="row") as row: offset = sparse_indptr_ptr[row] diff = sparse_indptr_ptr[row + 1] - sparse_indptr_ptr[row] with irb.for_range(0, diff, kind="serial", name="idx") as idx: real_idx = offset + idx col = sparse_indices_ptr[real_idx] out_data_ptr[row, col] = sparse_data_ptr[real_idx] + out_data_ptr[row, col] return irb.get() return te.extern( shape=oshape, inputs=[dense_data_inp, sparse_data_inp, sparse_indices_inp, sparse_indptr_inp], fcompute=lambda ins, outs: _csr_add_ir(ins[0], ins[1], ins[2], ins[3], outs[0]), tag="sparse_add_csr", dtype=[ dense_data_inp.dtype, sparse_data_inp.dtype, sparse_indices_inp.dtype, sparse_indptr_inp.dtype, ], name="sparse_add_csr_output", )
https://github.com/zk-ml/tachikoma
python/tvm/topi/nn/upsampling.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """TVM operator upsampling compute.""" from tvm import topi from tvm import te from ..utils import simplify def upsampling( data, scale_h, scale_w, layout="NCHW", method="nearest_neighbor", align_corners=False, output_shape=None, ): """Perform upsampling on the data. Nearest neighbor and bilinear upsampling are supported. Parameters ---------- inputs : tvm.te.Tensor inputs is a 4-D tensor with shape [batch, channel, in_height, in_width] or [batch, in_height, in_width, channel] scale_h : float Scaling factor for height scale_w : float Scaling factor for width layout : string, optional either "NCHW" or "NHWC" method : {"bilinear", "nearest_neighbor", "bicubic"} Method to be used for upsampling. output_shape: tvm.tir.container.Array, optional Shape to return. If left None will be inferred (If shape is determined dynamically, pass out_dtype.shape as output_shape) Returns ------- output : tvm.te.Tensor 4-D with shape [batch, channel, in_height*scale_h, in_width*scale_w] or [batch, in_height*scale, in_width*scale, channel] """ base_layout = layout[0:4] if base_layout == "NCHW": if not output_shape: # static case scaled_h = data.shape[2] * scale_h scaled_w = data.shape[3] * scale_w reshape_size = ( simplify(topi.cast(te.round(scaled_h), data.shape[2].dtype)), simplify(topi.cast(te.round(scaled_w), data.shape[3].dtype)), ) else: # dynamic case -- we don't need to scale; already done in shape func reshape_size = ( simplify(topi.cast(te.round(output_shape[2]), output_shape[2].dtype)), simplify(topi.cast(te.round(output_shape[3]), output_shape[3].dtype)), ) elif layout == "NHWC": if not output_shape: # static case scaled_h = data.shape[1] * scale_h scaled_w = data.shape[2] * scale_w reshape_size = ( simplify(topi.cast(te.round(scaled_h), data.shape[1].dtype)), simplify(topi.cast(te.round(scaled_w), data.shape[2].dtype)), ) else: # dynamic case reshape_size = ( simplify(topi.cast(te.round(output_shape[1]), output_shape[1].dtype)), simplify(topi.cast(te.round(output_shape[2]), output_shape[2].dtype)), ) else: raise ValueError("not support this layout {} yet".format(layout)) coord_trans = "align_corners" if align_corners else "asymmetric" if method[0:2] == "bi": method = method[2:] return topi.image.resize2d( data, [0.0] * 4, reshape_size, layout=layout, method=method, coordinate_transformation_mode=coord_trans, output_shape=output_shape, ) def upsampling3d( data, scale_d, scale_h, scale_w, layout="NCDHW", method="nearest_neighbor", coordinate_transformation_mode="half_pixel", output_shape=None, ): """Perform upsampling on the data. Nearest neighbor and bilinear upsampling are supported. Parameters ---------- inputs : tvm.te.Tensor inputs is a 5-D tensor with shape [batch, channel, in_depth, in_height, in_width] or [batch, in_depth, in_height, in_width, channel] scale_d : float Scaling factor for depth scale_h : float Scaling factor for height scale_w : float Scaling factor for width layout : string, optional either "NCDHW" or "NDHWC" method : {"trilinear", "nearest_neighbor"} Method to be used for upsampling. coordinate_transformation_mode: string, optional Describes how to transform the coordinate in the resized tensor to the coordinate in the original tensor. Refer to the ONNX Resize operator specification for details. Available options are "half_pixel", "align_corners" and "asymmetric". output_shape: tvm.tir.container.Array, optional Shape to return. If left None will be inferred (If shape is determined dynamically, pass out_dtype.shape as output_shape) Returns ------- output : tvm.te.Tensor 5-D with shape [batch, channel, in_depth*scale, in_height*scale, in_width*scale] or [batch, in_depth*scale, in_height*scale, in_width*scale, channel] """ base_layout = layout[0:5] if base_layout == "NCDHW": if not output_shape: # static case scaled_d = data.shape[2] * scale_d scaled_h = data.shape[3] * scale_h scaled_w = data.shape[4] * scale_w resize_shape = ( simplify(topi.cast(te.round(scaled_d), data.shape[2].dtype)), simplify(topi.cast(te.round(scaled_h), data.shape[3].dtype)), simplify(topi.cast(te.round(scaled_w), data.shape[4].dtype)), ) else: # dynamic case -- don't need to scale; already done in shape func resize_shape = ( simplify(topi.cast(te.round(output_shape[2]), data.shape[2].dtype)), simplify(topi.cast(te.round(output_shape[3]), data.shape[3].dtype)), simplify(topi.cast(te.round(output_shape[4]), data.shape[4].dtype)), ) elif layout == "NDHWC": if not output_shape: # static case scaled_d = data.shape[1] * scale_d scaled_h = data.shape[2] * scale_h scaled_w = data.shape[3] * scale_w resize_shape = ( simplify(topi.cast(te.round(scaled_d), data.shape[1].dtype)), simplify(topi.cast(te.round(scaled_h), data.shape[2].dtype)), simplify(topi.cast(te.round(scaled_w), data.shape[3].dtype)), ) else: # dynamic case resize_shape = ( simplify(topi.cast(te.round(output_shape[1]), data.shape[1].dtype)), simplify(topi.cast(te.round(output_shape[2]), data.shape[2].dtype)), simplify(topi.cast(te.round(output_shape[3]), data.shape[3].dtype)), ) else: raise ValueError("not support this layout {} yet".format(layout)) if method[0:3] == "tri": method = method[3:] return topi.image.resize3d( data, [0.0] * 6, resize_shape, layout=layout, method=method, coordinate_transformation_mode=coordinate_transformation_mode, )
https://github.com/zk-ml/tachikoma
python/tvm/topi/nn/utils.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=invalid-name, unused-variable """NN operator common utilities""" from __future__ import absolute_import import tvm from ..utils import get_const_int def infer_pad(data, data_pad): """Infer the padding from stages in reverse. Parameters ---------- data : Tensor data stage. data_pad : Tensor pad stage. Returns ------- hpad : int padding size on height wpad : int padding size on width """ if data_pad is None: return 0, 0 _, _, IH, IW = data.shape _, _, TH, TW = data_pad.shape hpad = (TH - IH) // 2 wpad = (TW - IW) // 2 return get_const_int(hpad), get_const_int(wpad) def infer_pad3d(data, data_pad, layout): """Infer the padding from stages in reverse. Parameters ---------- data : Tensor data stage. data_pad : Tensor pad stage. Returns ------- dpad : int padding depth hpad : int padding height wpad : int padding width """ if data_pad is None: return 0, 0, 0 if layout == "NDHWC": _, ID, IH, IW, _ = data.shape _, TD, TH, TW, _ = data_pad.shape elif layout == "NCDHW": _, _, ID, IH, IW = data.shape _, _, TD, TH, TW = data_pad.shape else: raise ValueError("Layout {} is not supported".format(layout)) dpad = TD - ID hpad = TH - IH wpad = TW - IW return get_const_int(dpad), get_const_int(hpad), get_const_int(wpad) def infer_stride(data, kernel, out): """Infer the stride from stages in reverse. Parameters ---------- data : Tensor data stage. kernel : Tensor kernel stage. out : Tensor output stage. Returns ------- hstride : int stride size on height wstride : int stride size on width """ _, _, IH, IW = data.shape _, _, KH, KW = kernel.shape _, _, OH, OW = out.shape hstride = (IH - KH) // tvm.te.max(OH - 1, 1) + tvm.tir.Select(OH == 1, 1, 0) wstride = (IW - KW) // tvm.te.max(OW - 1, 1) + tvm.tir.Select(OW == 1, 1, 0) return get_const_int(hstride), get_const_int(wstride) def get_pad_tuple(padding, kernel): """Common code to get the pad option Parameters ---------- padding : int or str Padding size, or ['VALID', 'SAME'] kernel : tuple of int Conv kernel size Returns ------- pad_top : int Padding size on top pad_left : int Padding size on left pad_down : int Padding size on down. pad_right : int Padding size on right. """ # compute the padding size if isinstance(padding, (tuple, list)): if len(padding) == 2: pad_h = padding[0] * 2 pad_w = padding[1] * 2 elif len(padding) == 4: return padding[0], padding[1], padding[2], padding[3] else: raise ValueError("Size of padding can only be 2 or 4") elif isinstance(padding, int): pad_h = pad_w = padding * 2 elif padding == "VALID": pad_h = 0 pad_w = 0 elif padding == "SAME": pad_h = kernel[0] - 1 pad_w = kernel[1] - 1 else: raise ValueError("Unknown padding option %s" % padding) pad_top = (pad_h + 1) // 2 pad_left = (pad_w + 1) // 2 return pad_top, pad_left, pad_h - pad_top, pad_w - pad_left def get_pad_tuple_generic(padding, kernel): """Common code to get the pad option Parameters ---------- padding : int or str Padding size, or ['VALID', 'SAME'] kernel : tuple of int Conv kernel size Returns ------- pad_top : int Padding size on top pad_down : int Padding size on down. pad_left : int Padding size on left pad_right : int Padding size on right. """ # compute the padding size if isinstance(padding, (tuple, list)): if len(padding) == len(kernel): pad_dimensions = [p * 2 for p in padding] elif len(padding) == len(kernel) * 2: return [padding[i] for i in range(len(kernel))], [ padding[len(kernel) + i] for i in range(len(kernel)) ] else: raise ValueError("Size of padding can only be len(kernel) or len(kernel) * 2") elif isinstance(padding, int): pad_dimensions = [padding * 2 for _ in range(len(kernel))] elif padding == "VALID": pad_dimensions = [0 for _ in range(len(kernel))] elif padding == "SAME": pad_dimensions = [k - 1 for k in kernel] else: raise ValueError("Unknown padding option %s" % padding) pad_begin = [(p + 1) // 2 for p in pad_dimensions] return [pad_begin, [pd - pb for pb, pd in zip(pad_begin, pad_dimensions)]] def get_pad_tuple3d(padding, kernel): """Common code to get the pad option Parameters ---------- padding : int or str Padding size, or ['VALID', 'SAME'] kernel : tuple of int Conv kernel size Returns ------- pad_front : int Padding size on front. pad_top : int Padding size on top pad_left : int Padding size on left pad_back : int Padding size on back. pad_down : int Padding size on down. pad_right : int Padding size on right. """ # compute the padding size if isinstance(padding, (tuple, list)): if len(padding) == 3: pad_d = padding[0] * 2 pad_h = padding[1] * 2 pad_w = padding[2] * 2 elif len(padding) == 6: return padding[0], padding[1], padding[2], padding[3], padding[4], padding[5] else: raise ValueError("Size of padding can only be 3 or 6") elif isinstance(padding, int): pad_d = pad_w = pad_h = padding * 2 elif padding == "VALID": pad_h = 0 pad_w = 0 pad_d = 0 elif padding == "SAME": pad_d = kernel[0] - 1 pad_h = kernel[1] - 1 pad_w = kernel[2] - 1 else: raise ValueError("Unknown padding option %s" % padding) pad_top = (pad_h + 1) // 2 pad_left = (pad_w + 1) // 2 pad_front = (pad_d + 1) // 2 return pad_front, pad_top, pad_left, pad_d - pad_front, pad_h - pad_top, pad_w - pad_left def get_pad_tuple1d(padding, kernel): """Common code to get the pad option Parameters ---------- padding : int or str Padding size, or ['VALID', 'SAME'] kernel : tuple of int Conv kernel size Returns ------- pad_left : int Padding size on left pad_right : int Padding size on right. """ # compute the padding size if isinstance(padding, (tuple, list)): if len(padding) == 1: pad_w = padding[0] * 2 elif len(padding) == 2: return padding[0], padding[1] else: raise ValueError("Size of padding can only be 2 or 4") elif isinstance(padding, int): pad_w = padding * 2 elif padding == "VALID": pad_w = 0 elif padding == "SAME": pad_w = kernel[0] - 1 else: raise ValueError("Unknown padding option %s" % padding) pad_left = (pad_w + 1) // 2 return pad_left, pad_w - pad_left
https://github.com/zk-ml/tachikoma
python/tvm/topi/nn/winograd_util.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # """ Utility functions for implementing Winograd convolutions [*] Fast Algorithms for Convolutional Neural Networks Andrew Lavin, Scott Gray https://arxiv.org/abs/1509.09308 https://github.com/andravin/wincnn """ from operator import mul from functools import reduce import numpy as np from tvm.contrib.pickle_memoize import memoize from ..utils import const_matrix # pylint: disable=invalid-name def _cook_toom_convolution(a, n, r): """Compute Cook-Toom convolution A,B,G matrices""" def _F_m(a, n): f = lambda j, i: reduce(mul, ((a[i] - a[k] if k != i else 1) for k in range(0, n - 1)), 1) F = np.fromfunction(np.vectorize(f), (1, n - 1), dtype=int) F = np.diagflat(F) F = np.append(F, np.zeros((n - 1, 1), dtype=int), axis=1) f = lambda i, j: (1 if j == (n - 1) else 0) z = np.fromfunction(np.vectorize(f), (1, n), dtype=int) return np.append(F, z, axis=0) def _A_m(a, m, n): f = lambda i, j: a[i] ** j A = np.fromfunction(np.vectorize(f), (m - 1, n), dtype=int) f = lambda i, j: (1 if j == (n - 1) else 0) z = np.fromfunction(np.vectorize(f), (1, n), dtype=int) return np.append(A, z, axis=0) def _B_m(a, n): f = lambda j, i: reduce(mul, ((a[i] - a[k] if k != i else 1) for k in range(0, n - 1)), 1) Ff = np.fromfunction(np.vectorize(f), (1, n - 1), dtype=int) f = ( lambda i, nth: ( reduce(mul, [(np.poly1d([1, -a[k]]) if k != i else 1) for k in range(0, n - 1)], 1) ).coef[n - 1 - nth - 1] / Ff[0, i] ) F = np.fromfunction(np.vectorize(f), (n - 1, n - 1), dtype=int) f = lambda i, j: -a[i] ** (n - 1) t = np.fromfunction(np.vectorize(f), (n - 1, 1), dtype=int) T = np.append(np.eye(n - 1), t, axis=1) return np.append(F.T.dot(T), np.array([np.eye(n)[n - 1]]), axis=0) alpha = n + r - 1 f = _F_m(a, alpha) if f[0, 0] < 0: f[0, :] *= -1 A = _A_m(a, alpha, n) G = _A_m(a, alpha, r).T G = G.dot(np.linalg.inv(f)).T B = _B_m(a, alpha) B = B.dot(f.T) return (A, B, G) def _interpolation_points(degree): """Propose filter points""" assert 2 < degree < 18 # Default interpolation lookup table # # [1] Error Analysis and Improving the Accuracy of Winograd Convolution for Deep Neural Networks # Barbara Barabasz, Andrew Anderson, Kirk M. Soodhalter, David Gregg # https://arxiv.org/abs/1803.10986 # # pylint: disable=bad-whitespace,line-too-long in_pts = [ # {invalid} [], # 01 {E=4.63E-08 on conv2d [1]} [], # 02 {E=7.65E-08 on F( 2,3) [1]} [0, -1, 1], # 03 {E=2.35E-07 on F( 3,3) [1]} [0, -1, 1, 1 / 2], # 04 {E=3.29E-07 on F( 4,3) [1]} [0, -1, 1, 1 / 2, -2], # 05 {E=6.81E-07 on F( 5,3) [1]} [0, -1, 1, 1 / 2, -2, -1 / 2], # 06 {E=8.79E-07 on F( 6,3) [1]} [0, -1, 1, 1 / 2, -1 / 2, 2, -2], # 07 {E=3.71E-06 on F( 7,3) [1]} [0, -1, 1, 1 / 2, -1 / 2, 2, -2, -1 / 4], # 08 {E=7.35E-06 on F( 8,3) [1]} [0, -1, 1, 1 / 2, -1 / 2, 2, -2, -1 / 4, 4], # 09 {E=2.20E-05 on F( 9,3) [1]} [0, -1, 1, 1 / 2, -1 / 2, 2, -2, -1 / 4, 3 / 4, -4 / 3], # 10 {E=3.22E-05 on F(10,3) [1]} [0, -1, 1, 1 / 2, -1 / 2, 2, -2, -1 / 4, 4, 3 / 4, -4 / 3], # 11 {E=1.09E-04 on F(11,3) [1]} [0, -1, 1, 1 / 2, -1 / 2, 2, -2, -1 / 4, 4, 3 / 4, -4 / 3, 1 / 4], # 12 {E=1.99E-04 on F(12,3) [1]} [0, -1, 1, 1 / 2, -1 / 2, 2, -2, -1 / 4, 4, 1 / 4, -3 / 4, 4 / 3, -4], # 13 {E=5.54E-04 on F(13,3) [1]} [0, -1, 1, 1 / 2, -1 / 2, 2, -2, -1 / 4, 4, 1 / 4, -3 / 4, 4 / 3, 3 / 4, -4 / 3], # 14 {E=8.80E-04 on F(14,3) [1]} [0, -1, 1, 1 / 2, -1 / 2, 2, -2, -1 / 4, 4, 1 / 4, -3 / 4, 4 / 3, -4, 3 / 4, -4 / 3], # 15 {E=1.07E-02 on F(15,3) [1]} [0, -1, 1, 1 / 2, -1 / 2, 2, -2, -1 / 4, 4, 1 / 4, -3 / 4, 4 / 3, -4, 2 / 3, -3 / 2, 3 / 2], # 16 {E=1.93E-02 on F(16,3) [1]} [ 0, -1, 1, 1 / 2, -1 / 2, 2, -2, -1 / 4, 4, 1 / 4, -3 / 4, 4 / 3, -4, 2 / 3, -3 / 2, -2 / 3, 3 / 2, ], ] # pylint: enable=bad-whitespace,line-too-long return np.array(in_pts[degree - 1], dtype=np.float64) @memoize("topi.nn.winograd_matrices", save_at_exit=False) def winograd_transform_matrices(tile_size, kernel_size, out_dtype): """Compute the A, B, and G transform matrices for `tile_size` as a `tvm.Expr`.""" if not 1 < tile_size < 9: raise ValueError("Unsupported tile size for Winograd: {}".format(tile_size)) if not 2 < kernel_size < 8: raise ValueError("Unsupported kernel size for Winograd: {}".format(kernel_size)) degree = tile_size + kernel_size - 2 intp_pts = _interpolation_points(degree) A_data, B_data, G_data = _cook_toom_convolution(intp_pts, tile_size, kernel_size) return ( const_matrix(A_data.astype(out_dtype), "A"), const_matrix(B_data.astype(out_dtype), "B"), const_matrix(G_data.astype(out_dtype), "G"), )
https://github.com/zk-ml/tachikoma
python/tvm/topi/random/__init__.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=wildcard-import """Pseudorandom generator kernels and operators.""" from __future__ import absolute_import from .kernel import *
https://github.com/zk-ml/tachikoma
python/tvm/topi/random/kernel.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """Pseudorandom number kernels.""" import math import numpy as np import tvm import tvm.topi from ... import tir from ...tir import ir_builder # Threefry PRNG with splitting based on # - J. K. Salmon, M. A. Moraes, R. O. Dror and D. E. Shaw, "Parallel random numbers: As easy as 1, # 2, 3," SC '11: Proceedings of 2011 International Conference for High Performance Computing, # Networking, Storage and Analysis, Seattle, WA, 2011, pp. 1-12, doi: 10.1145/2063384.2063405. # - Claessen, K. ; Palka, M. (2013) "Splittable Pseudorandom Number Generators using Cryptographic # Hashing". Proceedings of Haskell Symposium 2013 pp. 47-58. MLA # - Ferguson, Niels, et al. "The Skein hash function family." Submission to NIST (round 3) 7.7.5 # (2010): 3. # Threefry is a counter based PRNG: given a unique input, it generates a unique random number. As # there is no state to maintain, we can apply it to a sequence of numbers (0..N) to generate a # sequence of random numbers in parallel. In order to make the PRNG splittable (that is we can # generate a sequence of random numbers in one place, and another sequence in another), we add a # path and key in addition to the counter. The path allows us to encode a sequence of splits (a 0 in # the path indicates the left result of a split, a 1 indicates the right). To avoid continuously # growing the path, we can compress an existing path into the key portion of the generator by # hashing the current key, path, and counter to create the new key (this same technique is used if # we run out of room for the counter). They key is initialized with a unique initial state. # # Random numbers are generated by applying the Threefry hash to the current key, path, and counter. # This module use encoding e4 from the appendix of "Splittable Pseudorandom Number Generators using # Cryptographic Hashing" (confusingly, the definition in the paper uses e3 to define the encoding # function). This encoding uses a 10 element uint64 tensor where each byte means the following: # .. code-block: # gen: # words: 0 1 2 3 | 4 5 | 6 7 | 8 9 # usage: key | path | counter | position of next step in path encoded in binary # ex: 0b00010 -> next path entry goes one from the right # Right now, counter only uses the rightmost word. # Threefry rotation constants from the Skein paper ("The Skein Hash Function Family" # https://www.schneier.com/wp-content/uploads/2015/01/skein.pdf) _ROTATIONS = { 4: [[14, 16], [52, 57], [23, 40], [5, 37], [25, 33], [46, 12], [58, 22], [32, 32]], 8: [ [46, 36, 19, 37], [33, 27, 14, 42], [17, 49, 36, 39], [44, 9, 54, 56], [39, 30, 34, 24], [13, 50, 10, 17], [25, 29, 39, 43], [8, 35, 56, 22], ], 16: [ [24, 13, 8, 47, 8, 17, 22, 37], [38, 19, 10, 55, 49, 18, 23, 52], [33, 4, 51, 13, 34, 41, 59, 17], [5, 20, 48, 41, 47, 28, 16, 25], [41, 9, 37, 31, 12, 47, 44, 30], [16, 34, 56, 51, 4, 53, 42, 41], [31, 44, 47, 46, 19, 42, 44, 25], [9, 48, 35, 52, 23, 31, 37, 20], ], } # Threefry permutation constants from the Skein paper ("The Skein Hash Function Family" # https://www.schneier.com/wp-content/uploads/2015/01/skein.pdf) _PERMUTATIONS = { 4: [0, 3, 2, 1], 8: [2, 1, 4, 7, 6, 5, 0, 3], 16: [0, 9, 2, 13, 6, 11, 4, 15, 10, 7, 12, 3, 14, 5, 8, 1], } def _threefry( irb, key_buf, key_offset, counter_buf, counter_offset, out_buf, out_offset, out_shape ): """IRBuilder code for running Threefry Parameters ---------- irb: IRBuilder IRBuilder that this code will be generated for. key_buf: BufferVar Buffer to read the key from. key_offset: number Threefry will write to :code:`key_buf[key_offset:key_offset+4]` counter_buf: BufferVar Buffer to read the counter from. counter_offset: number Threefry will write to :code:`counter_buf[counter_offset:counter_offset+4]` out_buf: BufferVar Buffer to read the counter from. out_offset: number Threefry will write to :code:`out_buf[out_offset:out_offset+4*product(out_shape)]` out_shape: number Determines the number of output states to generate. :code:`state[i]` will correspond to counter+i. """ nrounds = 20 nwords = 4 iwidth = 64 assert nrounds % 4 == 0 assert nwords in [4, 8, 16] # The paper has constants for 32 bit threefry, but we keep the implementation simple by only # using 64-bit words. assert key_buf.dtype == "uint64", "threefry only supports 64-bit keys" assert key_buf.dtype == counter_buf.dtype, "threefry key and counter must be the same dtype" def mix(a, b, rotation): x = a + b # wrapping y = x ^ ((b << rotation) | (b >> (iwidth - rotation))) return [x, y] # temporary buffer for holding the results of _PERMUTATIONS tmp = irb.allocate(out_buf.dtype, out_shape * nwords, name="tmp", scope="global") tmp_offset = 0 # Initialize entire key. It is composed of the original key with one # element appended. The appended element is the xor of all key words plus a # constant. full_key = irb.allocate("uint64", nwords + 1, name="full_key", scope="global") for i in range(nwords): full_key[i] = key_buf[key_offset + i] # initial key constant, full_key[nwords] is equivalent to k_{N_W} in the Skein paper. full_key[nwords] = tvm.tir.const(0x1BD11BDAA9FC1A22, dtype="uint64") for i in range(nwords): full_key[nwords] ^= key_buf[key_offset + i] with irb.for_range(0, out_shape, dtype="uint64", name="i") as i: for j in range(nwords): out_buf[out_offset + i * nwords + j] = counter_buf[counter_offset + j] + i def key_schedule(s, i): # Threefry uses no tweak, so the key schedule is simple if i == nwords - 1: return full_key[(s + i) % (nwords + 1)] + tvm.tir.const(s, dtype="uint64") return full_key[(s + i) % (nwords + 1)] with irb.for_range(0, out_shape, name="l") as l: # pylint: disable=invalid-name for i in range(nrounds // 4): for j in range(nwords): out_buf[out_offset + l * nwords + j] += key_schedule(i, j) # wrapping for k in range(4): for j in range(nwords // 2): ( out_buf[out_offset + l * nwords + j * 2 + 0], out_buf[out_offset + l * nwords + j * 2 + 1], ) = mix( out_buf[out_offset + l * nwords + j * 2 + 0], out_buf[out_offset + l * nwords + j * 2 + 1], _ROTATIONS[nwords][(i * 4 + k) % 8][j], ) for j in range(nwords): tmp[tmp_offset + l * nwords + j] = out_buf[ out_offset + l * nwords + _PERMUTATIONS[nwords][j] ] # number of rounds is even, so out always contains the result (out_buf, tmp) = (tmp, out_buf) (out_offset, tmp_offset) = (tmp_offset, out_offset) def threefry_generate(gen, out_shape): """Generate a series of random values Notes ----- This function uses the counter portion of the generator state to generate a series of random numbers in parallel. Random number `i` is generated by applying Threefry to the current generator state with the counter portion incremented by `i`. This means that each random number is generated independently from each other random number, so we can compute them in parallel. If there is not enough room left in the counter to generate the desired shape of random values, then a new generator is created by applying Threefry to the current key, path, and counter. This new generator will have a reset counter. Warning ------- Threeyfry requires that unsigned integer arithmetic wraps on overflow. Currently TVM has no guarantee of this, so threefry contains an internal assert to check wrapping behavior. This assert may or may not run depending on your platform, so it is recommended you run :py:func:`threefry_test_wrapping` to verify wrapping behavior. Parameters ---------- gen : Tensor[10, uint64] Generator state. Can be create with :py:func:`tvm.relay.random.threefry_key`. This should not be reused in another function, otherwise random numbers will be repeated. out_shape : Sequence[int] Output shape of the random numbers. Returns ------- new_gen : Tensor[10, uint64] The new generator state to be used in subsequent calls. rand : Tensor[out_shape, uint64] Tensor of random numbers with shape `out_shape`. """ out_len = tir.const(1) for s in out_shape: out_len *= s assert ( out_len.value <= 2**64 - 1 ), f"Can only generate up to 2^64 random numbers, but {out_len} were requested." def gen_ir(gen_ptr, out_gen_ptr, out_array_ptr): irb = ir_builder.create() gen = irb.buffer_ptr(gen_ptr) out_gen = irb.buffer_ptr(out_gen_ptr) out_array = irb.buffer_ptr(out_array_ptr) # Check that unsigned arithmetic wraps, as it is required to implement threefry correctly. irb.emit( tvm.tir.AssertStmt( tvm.tir.const(0xFFFFFFFFFFFFFFFF, "uint64") + tvm.tir.const(1, "uint64") == tvm.tir.const(0, "uint64"), tvm.tir.StringImm( "Unsigned integer arithmetic is not wrapping, but threefry requires wrapping." ), tvm.tir.Evaluate(0), ) ) # Create a temporary array to hold the generator state we will use to create the random # numbers. We cannot use gen because we may need to update the key + path if there is not # enough room in the counter. tmp = irb.allocate(gen.dtype, 10, name="tmp", scope="global") # TODO(tkonolige): for now we only use the last word of the counter for counting. It is too # much work to figure out how to do 128 bit addition. # Max value for counter should be 2**64-2 because we need to reserve a special value to # indicate the counter is used up. with irb.if_scope(gen[7] < tir.const(2**64 - 1, dtype=gen.dtype) - out_len): for i in range(10): tmp[i] = gen[i] with irb.else_scope(): # no room left in the counter, we have to change the path or key with irb.if_scope(gen[8] == 0 and gen[9] == 0): # out of room in the path, have to generate new key # The paper says the counter that we will be hashing should be a special value of # all ones. We need to allocate some space for it because we cannot overwrite gen. tmp_counter = irb.allocate(gen.dtype, 2, name="tmp_counter", scope="global") tmp_counter[0] = tir.const(0xFFFFFFFFFFFFFFFF, dtype=gen.dtype) tmp_counter[1] = tir.const(0xFFFFFFFFFFFFFFFF, dtype=gen.dtype) _threefry(irb, gen, 0, tmp_counter, 0, tmp, 0, 1) tmp[4] = tir.const(0, dtype=gen.dtype) # zero path, i.e. no path tmp[5] = tir.const(0, dtype=gen.dtype) tmp[6] = tir.const(0, dtype=gen.dtype) # zero counter tmp[7] = tir.const(0, dtype=gen.dtype) tmp[8] = tir.const(1 << 63, dtype=gen.dtype) # one in the leftmost position tmp[9] = tir.const(0, dtype=gen.dtype) with irb.else_scope(): tmp[0] = gen[0] tmp[1] = gen[1] tmp[2] = gen[2] tmp[3] = gen[3] tmp[4] = gen[4] | gen[8] # add a 1 to the path tmp[5] = gen[5] | gen[9] tmp[6] = tir.const(0, dtype=gen.dtype) # zero counter tmp[7] = tir.const(0, dtype=gen.dtype) _shift_right(irb, gen[8], gen[9], tmp, 8, tmp, 9) # Compute random values if out_len.value >= 4: _threefry(irb, tmp, 0, tmp, 4, out_array, 0, out_len // 4) if out_len.value % 4 != 0: remaining = irb.allocate(gen.dtype, 4, name="remaining", scope="global") tmp[7] = tmp[7] + tir.Cast(gen.dtype, out_len // 4 * 4) # increment counter _threefry(irb, tmp, 0, tmp, 4, remaining, 0, 1) with irb.for_range(0, out_len % 4, dtype="uint64", name="i") as i: out_array[out_len // 4 * 4 + i] = remaining[i] # Update generator state out_gen[0] = tmp[0] # key stays the same out_gen[1] = tmp[1] out_gen[2] = tmp[2] out_gen[3] = tmp[3] out_gen[4] = tmp[4] # path stays the same out_gen[5] = tmp[5] out_gen[6] = tir.const(0, dtype=gen.dtype) # unused, leave it as 0 if out_len.value % 4 != 0: # increment counter for the remaining # as we will generate 4 random numbers for the remaining, increase 4 here. # the main increment was done before the second _threefry. out_gen[7] = tmp[7] + tir.Cast(gen.dtype, 4) else: out_gen[7] = tmp[7] + tir.Cast(gen.dtype, out_len) # increment counter out_gen[8] = tmp[8] # path unchanged, so no update here out_gen[9] = tmp[9] return irb.get() out_gen = tvm.tir.decl_buffer((10,), name="out_gen", dtype="uint64") out_array = tvm.tir.decl_buffer(out_shape, name="out_array", dtype="uint64") return tvm.te.extern( [out_gen.shape, out_array.shape], [gen], lambda ins, outs: gen_ir(ins[0], outs[0], outs[1]), out_buffers=[out_gen, out_array], name="threefry_generate", tag="threefry_generate", ) def _shift_right(irb, a, b, out_a, a_off, out_b, b_off): """Binary shift a 128bit number composed of two 64 bit words right by one.""" with irb.if_scope(a == 1): out_a[a_off] = tir.const(0, dtype=a.dtype) out_b[b_off] = tir.const(0x8000000000000000, dtype=a.dtype) with irb.else_scope(): with irb.if_scope(a == 0): out_a[a_off] = tir.const(0, dtype=a.dtype) out_b[b_off] = b >> 1 with irb.else_scope(): out_a[a_off] = a >> 1 out_b[b_off] = tir.const(0, dtype=a.dtype) def threefry_split(gen): """Split a single generator state into two new ones Notes ----- The new generator is created by appending a one (for the right output) or a zero (for the left output) to the end of the path portion of the generator If there is no longer and room in the path, then we create a new key portion of the generator by applying Threefry to the old state, path, and counter. i.e. :code:`new_key = threefry(old_key, [old_path, old_counter])`. This resets the path portion of the new generator. Parameters ---------- gen : Tensor[10, uint64] Generator state. Can be create with :py:func:`tvm.relay.random.threefry_key`. This should not be reused in another function, otherwise random numbers will be repeated. Returns ------- out_gen_left : Tensor[10, uint64] New generator state that is distinct from `out_gen_right`. out_gen_right : Tensor[10, uint64] New generator state that is distinct from `out_gen_left`. """ def gen_ir(gen_ptr, out_left_ptr, out_right_ptr): irb = ir_builder.create() gen = irb.buffer_ptr(gen_ptr) out_left = irb.buffer_ptr(out_left_ptr) out_right = irb.buffer_ptr(out_right_ptr) with irb.if_scope(gen[8] == 0 and gen[9] == 0): # Generate new key because we have run out of room to extend the path _threefry(irb, gen, 0, gen, 4, out_left, 0, 1) out_left[4] = tir.const(0, dtype=gen.dtype) out_left[5] = tir.const(0, dtype=gen.dtype) out_left[6] = tir.const(0, dtype=gen.dtype) # counter gets zeroed out_left[7] = tir.const(0, dtype=gen.dtype) # counter gets zeroed out_left[8] = tir.const( 1 << 62, dtype=gen.dtype ) # one in the second from the leftmost position out_left[9] = tir.const(0, dtype=gen.dtype) out_right[0] = out_left[0] out_right[1] = out_left[1] out_right[2] = out_left[2] out_right[3] = out_left[3] out_right[4] = tir.const(1 << 63, dtype=gen.dtype) # one in the leftmost position out_right[5] = tir.const(0, dtype=gen.dtype) out_right[6] = tir.const(0, dtype=gen.dtype) out_right[7] = tir.const(0, dtype=gen.dtype) out_right[8] = tir.const( 1 << 62, dtype=gen.dtype ) # one in the second from the leftmost position out_right[9] = tir.const(0, dtype=gen.dtype) with irb.else_scope(): out_left[0] = gen[0] out_left[1] = gen[1] out_left[2] = gen[2] out_left[3] = gen[3] out_left[4] = gen[4] # adding a zero here, but its already zero padded out_left[5] = gen[5] out_left[6] = gen[6] out_left[7] = gen[7] # move path position over one bit _shift_right(irb, gen[8], gen[9], out_left, 8, out_left, 9) out_right[0] = gen[0] out_right[1] = gen[1] out_right[2] = gen[2] out_right[3] = gen[3] out_right[4] = gen[4] | gen[8] # add a one to the path out_right[5] = gen[5] | gen[9] out_right[6] = gen[6] out_right[7] = gen[7] _shift_right(irb, gen[8], gen[9], out_right, 8, out_right, 9) return irb.get() out_left = tvm.tir.decl_buffer((10,), name="out_left", dtype="uint64") out_right = tvm.tir.decl_buffer((10,), name="out_right", dtype="uint64") return tvm.te.extern( [out_left.shape, out_right.shape], [gen], lambda ins, outs: gen_ir(ins[0], outs[0], outs[1]), out_buffers=[out_left, out_right], name="threefry_split", tag="threefry_split", ) def threefry_test_wrapping(target, device): """Test that unsigned arithmetic wraps on overflow. Parameters ---------- target : tvm.target.Target Target to run against device : tvm.runtime.Device Context to run the test on Returns ------- is_wrapping : bool Whether or not unsigned integer arithmetic is wrapping for this target, context pair. True indicates that threefry will work on this platform. """ if isinstance(target, str): target = tvm.target.Target(target) def gen_ir(out_ptr): irb = ir_builder.create() out = irb.buffer_ptr(out_ptr) if "gpu" in target.keys: thread_x = tvm.te.thread_axis("threadIdx.x") irb.scope_attr(thread_x, "thread_extent", 1) out[0] = tvm.tir.const(0xFFFFFFFFFFFFFFFF, "uint64") + tvm.tir.const(1, "uint64") return irb.get() out = tvm.tir.decl_buffer((1,), dtype="uint64") f = tvm.te.extern( [out.shape], [], lambda ins, outs: gen_ir(outs[0]), dtype="uint64", out_buffers=[out] ) s = tvm.te.create_schedule([f.op]) out_ary = tvm.nd.array(np.ones((1,), "uint64"), device) tvm.build(s, [f], target=target)(out_ary) return out_ary.numpy()[0] == 0 def uniform(gen, low, high, out_shape, out_dtype): """Draw samples from a uniform distribution. Samples are uniformly distributed over the half-open interval [low, high) (includes low, but excludes high). In other words, any value within the given interval is equally likely to be drawn by uniform. Parameters ---------- gen : ThreefryKey Generator state. Can be create with :py:func:`tvm.relay.threefry_key`. This should not be reused in another function, otherwise random numbers will be repeated. low : Tensor[(), out_dtype] Lower boundary of the output interval. All values generated will be greater than or equal to low. high : Tensor[(), out_dtype] Upper boundary of the output interval. All values generated will be less than high. out_shape : Sequence[int] Output shape of the random numbers. out_dtype : str The output dtype. Returns ------- new_gen : ThreefryKey New generator state that is distinct from `gen`. out : Tensor[out_shape, out_dtype] Tensor of random numbers with shape `out_shape` and type `out_dtype`. """ new_gen, random_bits = threefry_generate(gen, out_shape) assert out_dtype in ("float32", "float64"), ( "Only support float32 or float64 for now, got %s" % out_dtype ) if out_dtype == "float32": random_dtype = "uint32" nbits = 32 nfraction = 23 elif out_dtype == "float64": random_dtype = "uint64" nbits = 64 nfraction = 52 nexp = nbits - nfraction - 1 random_bits = random_bits.astype(random_dtype) fraction = tvm.topi.right_shift( random_bits, tvm.tir.const(nbits - nfraction, dtype=random_dtype) ) exponent = tvm.topi.left_shift( tvm.topi.full(out_shape, random_dtype, (1 << (nexp - 1)) - 1), tvm.tir.const(nfraction, dtype=random_dtype), ) mantissa = tvm.topi.bitwise_or(fraction, exponent).astype(random_dtype) standard_uniform_values = tvm.topi.reinterpret(mantissa, out_dtype) - tvm.tir.const( 1, dtype=out_dtype ) uniform_values = tvm.topi.add(tvm.topi.multiply(standard_uniform_values, high - low), low) return new_gen, uniform_values def normal(gen, mean, scale, out_shape, out_dtype): """Draw samples from a normal distribution. The algorithm is based on Box-Muller transform Parameters ---------- gen : ThreefryKey Generator state. Can be create with :py:func:`tvm.relay.threefry_key`. This should not be reused in another function, otherwise random numbers will be repeated. mean : Tensor[(), out_dtype] The mean of the normal distribution. scale : Tensor[(), out_dtype] The standard deviation of the normal distribution. out_shape : Sequence[int] Output shape of the random numbers. out_dtype : str The output dtype. Returns ------- new_gen : ThreefryKey New generator state that is distinct from `gen`. out : Tensor[out_shape, out_dtype] Tensor of random numbers with shape `out_shape` and type `out_dtype`. """ out_shape = list(out_shape) # Box-Muller transform need two pieces of original uniform data out_shape.insert(0, 2) new_gen, uniform_values = uniform( gen, tvm.tir.const(0.0, out_dtype), tvm.tir.const(1.0, out_dtype), out_shape, out_dtype, ) two_pi = tvm.tir.const(2.0 * math.pi, out_dtype) uniform_values_1 = tvm.topi.strided_slice(uniform_values, [0], [1], strides=[1], axes=[0]) uniform_values_1 = tvm.topi.squeeze(uniform_values_1, axis=0) uniform_values_2 = tvm.topi.strided_slice(uniform_values, [1], [2], strides=[1], axes=[0]) uniform_values_2 = tvm.topi.squeeze(uniform_values_2, axis=0) uniform_values_1 = tvm.topi.subtract(tvm.tir.const(1.0, out_dtype), uniform_values_1) sqrt_values = tvm.topi.sqrt( tvm.topi.multiply(tvm.tir.const(-2.0, out_dtype), tvm.topi.log(uniform_values_1)) ) sin_values = tvm.topi.sin(tvm.topi.multiply(two_pi, uniform_values_2)) random_values = tvm.topi.add( tvm.topi.multiply(tvm.topi.multiply(sqrt_values, sin_values), scale), mean ) return new_gen, random_values def multinomial(gen, probs, num_samples): """Draw samples from a multinomial distribution defined by the input tensor. Parameters ---------- gen : ThreefryKey Generator state. Can be created with :py:func:`tvm.relay.threefry_key`. This should not be reused in another function, otherwise random numbers will be repeated. probs: Tensor[(input_rows, indices), float] A tensor containing the probabilities to sample from. Each value represents the probability of choosing its corresponding index. If a tensor is provided, the last dimension is treated independently. Negative values in this tensor will be clipped to zero to represent they have no chance of being selected. num_samples: int Number of samples to draw from each row. Returns ------- new_gen : ThreefryKey New generator state that is distinct from `gen`. out : Tensor[(input_rows, num_samples), int64] Tensor of sampled indices with shape `input_rows x num_samples` and type `out_dtype`. """ # Convert to float for consistent behavior. probs = tvm.topi.cast(probs, "float32") # Clip negative values to 0. probs = tvm.topi.maximum(probs, 0) # Normalize input probabilities. probs = tvm.topi.divide(probs, tvm.topi.expand_dims(tvm.topi.sum(probs, axis=-1), -1)) # Convert probability to cumulative sum. cumulative_probs = tvm.topi.cumsum(probs, axis=-1) # Sample a set of uniform values. new_gen, uniform_values = uniform( gen, tvm.tir.const(0.0, "float32"), tvm.tir.const(1.0, "float32"), [*probs.shape[:-1], num_samples], "float32", ) # Find index corresponding to sampled values. closest_prob = tvm.topi.subtract( tvm.topi.expand_dims(cumulative_probs, axis=-1), tvm.topi.expand_dims(uniform_values, axis=-2), ) zeros = tvm.topi.full_like(closest_prob, 0) ones = tvm.topi.full_like(closest_prob, 1) # Find the smallest positive index for each sample. cond = tvm.topi.greater(closest_prob, zeros) closest_non_neg = tvm.topi.where(cond, closest_prob, ones) sampled_indices = tvm.topi.argmin(closest_non_neg, axis=-2) return new_gen, sampled_indices
https://github.com/zk-ml/tachikoma
python/tvm/topi/reduction.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=redefined-builtin,consider-using-enumerate,no-member """Reduce operators""" from __future__ import absolute_import as _abs from . import cpp def _get_real_axis(ndim, axis): if axis is None: real_axis = list(range(ndim)) else: if isinstance(axis, int): axis = [axis] else: assert isinstance(axis, (list, tuple)) real_axis = [] for ele in axis: if ele < 0: ele += ndim if ele >= ndim: raise ValueError( "{} exceeds the maximum dimension {}. Received axis={}".format(ele, ndim, axis) ) real_axis.append(ele) real_axis.sort() real_axis = list(set(real_axis)) # Remove the duplicates return real_axis def sum(data, axis=None, keepdims=False): """Sum of array elements over a given axis or a list of axes Parameters ---------- data : tvm.te.Tensor The input tvm tensor axis : None or int or tuple of int Axis or axes along which a sum is performed. The default, axis=None, will sum all of the elements of the input array. If axis is negative it counts from the last to the first axis. keepdims : bool If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. Returns ------- ret : tvm.te.Tensor """ return cpp.sum(data, axis, keepdims) def all(data, axis=None, keepdims=False): """Logical AND of array elements over a given axis or a list of axes Parameters ---------- data : tvm.te.Tensor The input tvm boolean tensor axis : None or int or tuple of int Axis or axes along which a logical AND is performed. The default, axis=None, will perform logical AND over all elements of the input array. If axis is negative it counts from the last to the first axis. keepdims : bool If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. Returns ------- ret : tvm.te.Tensor """ return cpp.all(data, axis, keepdims) def any(data, axis=None, keepdims=False): """Logical OR of array elements over a given axis or a list of axes Parameters ---------- data : tvm.te.Tensor The input tvm boolean tensor axis : None or int or tuple of int Axis or axes along which a logical OR is performed. The default, axis=None, will perform logical OR over all elements of the input array. If axis is negative it counts from the last to the first axis. keepdims : bool If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. Returns ------- ret : tvm.te.Tensor """ return cpp.any(data, axis, keepdims) def max(data, axis=None, keepdims=False): """Maximum of array elements over a given axis or a list of axes Parameters ---------- data : tvm.te.Tensor The input tvm tensor axis : None or int or tuple of int Axis or axes along which the max operation is performed. The default, axis=None, will find the max element from all of the elements of the input array. If axis is negative it counts from the last to the first axis. keepdims : bool If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. Returns ------- ret : tvm.te.Tensor """ return cpp.max(data, axis, keepdims) def min(data, axis=None, keepdims=False): """Minimum of array elements over a given axis or a list of axes Parameters ---------- data : tvm.te.Tensor The input tvm tensor axis : None or int or tuple of int Axis or axes along which a minimum operation is performed. The default, axis=None, will find the minimum element from all of the elements of the input array. If axis is negative it counts from the last to the first axis. keepdims : bool If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. Returns ------- ret : tvm.te.Tensor """ return cpp.min(data, axis, keepdims) def argmax(data, axis=None, keepdims=False, select_last_index=False): """Returns the indices of the maximum values along an axis. Parameters ---------- data : tvm.te.Tensor The input tvm tensor axis : None or int or tuple of int Axis or axes along which a argmax operation is performed. The default, axis=None, will find the indices of the maximum element of the elements of the input array. If axis is negative it counts from the last to the first axis. keepdims : bool If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. select_last_index: bool Whether to select the last index if the maximum element appears multiple times, else select the first index. Returns ------- ret : tvm.te.Tensor """ return cpp.argmax(data, axis, keepdims, select_last_index) def argmin(data, axis=None, keepdims=False, select_last_index=False): """Returns the indices of the minimum values along an axis. Parameters ---------- data : tvm.te.Tensor The input tvm tensor axis : None or int or tuple of int Axis or axes along which a argmin operation is performed. The default, axis=None, will find the indices of minimum element all of the elements of the input array. If axis is negative it counts from the last to the first axis. keepdims : bool If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. select_last_index: bool Whether to select the last index if the minimum element appears multiple times, else select the first index. Returns ------- ret : tvm.te.Tensor """ return cpp.argmin(data, axis, keepdims, select_last_index) def prod(data, axis=None, keepdims=False): """Product of array elements over a given axis or a list of axes Parameters ---------- data : tvm.te.Tensor The input tvm tensor axis : None or int or tuple of int Axis or axes along which a prod operation is performed. The default, axis=None, will get the prod element over all of the elements of the input array. If axis is negative it counts from the last to the first axis. keepdims : bool If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. Returns ------- ret : tvm.te.Tensor """ return cpp.prod(data, axis, keepdims)
https://github.com/zk-ml/tachikoma
python/tvm/topi/rocm/__init__.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=redefined-builtin, wildcard-import """rocm specific declaration and schedules.""" from __future__ import absolute_import as _abs from .batch_matmul import * from .conv2d import * from .dense import *
https://github.com/zk-ml/tachikoma
python/tvm/topi/rocm/batch_matmul.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=invalid-name, unused-variable, unused-argument """Schedule for batch_matmul operator""" from tvm import autotvm from tvm.contrib import rocblas from .. import generic from ..utils import get_const_tuple @autotvm.register_topi_compute("batch_matmul_rocblas.rocm") def batch_matmul_rocblas( cfg, x, y, out_shape=None, out_dtype=None, transpose_a=False, transpose_b=True ): """Computes matrix multiplication of `x` and `y` via rocblas when `x` and `y` are batched matrices. Parameters ---------- cfg : ConfigSpace Autotvm tuning space config file x : tvm.te.Tensor 3-D with shape [batch, M, K] y : tvm.te.Tensor 3-D with shape [batch, N, K] Returns ------- output : tvm.te.Tensor 3-D with shape [batch, M, N] """ del out_dtype batch, M, K = get_const_tuple(x.shape) _, N, _ = get_const_tuple(y.shape) if out_shape is not None: assert out_shape[0] == batch, "Input and output batch sizes must match" assert out_shape[1] == M and out_shape[2] == N, "Invalid output shape" result = rocblas.batch_matmul(x, y, transpose_a, transpose_b) cfg.add_flop(batch * M * N * K * 2) return result @autotvm.register_topi_schedule("batch_matmul_rocblas.rocm") def schedule_batch_matmul_rocblas(_, outs): """Schedule for batch_matmul operator with rocm cblas""" return generic.schedule_extern(outs)
https://github.com/zk-ml/tachikoma
python/tvm/topi/rocm/conv2d.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=invalid-name, unused-argument """Compute definition for conv2d with rocm backend""" from tvm import autotvm from tvm.contrib import miopen from .. import generic from ..utils import get_const_tuple from ..nn.utils import get_pad_tuple @autotvm.register_topi_compute("conv2d_nchw_miopen.rocm") def conv2d_nchw_miopen( cfg, data, kernel, strides, padding, dilation, layout="NCHW", out_dtype="float32" ): """Conv2D operator for rocm backend. Parameters ---------- cfg: ConfigEntity The config for this template input : tvm.te.Tensor 4-D with shape [batch, in_channel, in_height, in_width] filter : tvm.te.Tensor 4-D with shape [num_filter, in_channel, filter_height, filter_width] strides : int or a list/tuple of two ints stride size, or [stride_height, stride_width] padding : int or a list/tuple of 2 or 4 ints padding size, or [pad_height, pad_width] for 2 ints, or [pad_top, pad_left, pad_bottom, pad_right] for 4 ints layout : str layout of data Returns ------- output : tvm.te.Tensor 4-D with shape [batch, out_channel, out_height, out_width] """ CO, CI, KH, KW = get_const_tuple(kernel.shape) N, _, H, W = get_const_tuple(data.shape) assert layout == "NCHW" # handle dilation stride_h, stride_w = (strides, strides) if isinstance(strides, int) else strides pt, pl, pb, pr = get_pad_tuple(padding, (KH, KW)) pad_h, pad_w = pt + pb, pl + pr dilation_h, dilation_w = (dilation, dilation) if isinstance(dilation, int) else dilation assert (pt == pb) and (pl == pr) OH = (H + 2 * pad_h - KH) // stride_h + 1 OW = (W + 2 * pad_w - KW) // stride_w + 1 cfg.add_flop( 2 * N * OH * OW * CO * CI * ((KH - 1) * dilation_h + 1) * ((KW - 1) * dilation_w + 1) ) return miopen.conv2d_forward( data, kernel, stride_h, stride_w, pt, pl, dilation_h, dilation_w, conv_mode=0, data_type=1 ) @autotvm.register_topi_schedule("conv2d_nchw_miopen.rocm") def schedule_conv2d_nchw_miopen(cfg, outs): """TOPI schedule callback of conv2d for rocm Parameters ---------- cfg: ConfigEntity The config for this template outs: Array of Tensor The computation graph description of conv2d in the format of an array of tensors. Returns ------- s: Schedule The computation schedule for conv2d. """ return generic.schedule_extern(outs)
https://github.com/zk-ml/tachikoma
python/tvm/topi/rocm/dense.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=invalid-name, unused-variable, unused-argument """Schedule for dense operator""" from tvm import te from tvm import autotvm from tvm.contrib import rocblas from .. import generic from .. import tag @autotvm.register_topi_compute("dense_rocblas.rocm") def dense_rocblas(cfg, data, weight, bias=None, out_dtype=None): """Dense operator for rocm backend with cblas. Parameters ---------- data : tvm.te.Tensor 2-D with shape [batch, in_dim] weight : tvm.te.Tensor 2-D with shape [out_dim, in_dim] bias : tvm.te.Tensor, optional 1-D with shape [out_dim] out_dtype : str The output type. This is used for mixed precision. Returns ------- output : tvm.te.Tensor 2-D with shape [batch, out_dim] """ if out_dtype is None: out_dtype = data.dtype assert out_dtype == data.dtype, "Mixed precision not supported." matmul = rocblas.matmul(data, weight, False, True) batch, in_dim = data.shape out_dim, _ = weight.shape cfg.add_flop(batch * in_dim * out_dim * 2) if bias is not None: matmul = te.compute( (batch, out_dim), lambda i, j: matmul[i, j] + bias[j], tag=tag.BROADCAST ) return matmul @autotvm.register_topi_schedule("dense_rocblas.rocm") def schedule_dense_rocblas(_, outs): """Schedule for dense operator with rocm cblas""" return generic.schedule_extern(outs)
https://github.com/zk-ml/tachikoma
python/tvm/topi/scan.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=invalid-name """Scan (cumulative binary) operators""" from typing import Callable, Optional import tvm from ..te import extern from ..tir import decl_buffer, generic, ir_builder from .math import cast from . import utils def scanop( data: tvm.te.Tensor, binop: Callable[["tvm.Expr", "tvm.Expr"], "tvm.Expr"], identity_value: "tvm.Expr", op_name: str, axis: Optional[int] = None, dtype: Optional[str] = None, exclusive: Optional[bool] = None, ) -> tvm.te.Tensor: """Cumulative binary operator (scan) with similar axis behavior as np.cumsum and np.cumprod. See cumprod and cumsum for an example of use. E.g. if * is your binary operator and the input tensor is [1, 2, 3, 4] the output may be [1, 1 * 2, 1 * 2 * 3, 1 * 2 * 3 * 4] Parameters ---------- data : tvm.te.Tensor The input data to the operator. binop: Callable (tvm.Expr, tvm.Expr) -> tvm.Expr A binary operator which should be associative and commutative. E.g. if * is your operator then a * (b * c) = (a * b) * c and a * b = b * a identity_value: tvm.Expr A value for the binary operation which provides the identity property. E.g. if * is your operator and i is the identity_value then a * i = a for all a in the domain of your operation. axis : int, optional Axis along which the operation is computed. The default (None) is to compute the cumulative operation over the flattened array. dtype : string, optional Type of the returned array and of the accumulator in which the elements are computed. If dtype is not specified, it defaults to the dtype of data. exclusive : bool, optional If True will return exclusive cumulative operation in which the first element is not included. In other terms, if True, the j-th output element would be the cumulative operation of the first (j-1) elements. Otherwise, it would be the cumulative operation of the first j elements. The cumulative operation of zero elements is assumed to be the identity_value. Returns ------- result : tvm.te.Tensor The result has the same size as data, and the same shape as data if axis is not None. If axis is None, the result is a 1-d array. """ if dtype is None or dtype == "": dtype = data.dtype if exclusive is None: exclusive = False def maybe_cast(x): if dtype != data.dtype: return cast(x, dtype) return x axis_mul_before = 1 axis_mul_after = 1 if axis is None: axis = 0 cumsum_axis_len = utils.prod(data.shape) shape = (cumsum_axis_len,) else: if not isinstance(axis, int): axis = utils.get_const_int(axis) shape = data.shape cumsum_axis_len = shape[axis] if axis < 0: axis = len(shape) + axis for i, value in enumerate(shape, 0): if i < axis: axis_mul_before *= value elif i > axis: axis_mul_after *= value def gen_ir(data_buf, out_buf): ib = ir_builder.create() data_buf = ib.buffer_ptr(data_buf) out_buf = ib.buffer_ptr(out_buf) with ib.for_range(0, axis_mul_before * axis_mul_after, "fused", kind="parallel") as fused: i = fused // axis_mul_after j = fused % axis_mul_after base_idx = i * cumsum_axis_len * axis_mul_after + j if exclusive: out_buf[base_idx] = cast(identity_value, dtype) else: out_buf[base_idx] = maybe_cast(data_buf[base_idx]) with ib.for_range(0, cumsum_axis_len - 1, "_k") as _k: k = _k + 1 cur_idx = base_idx + k * axis_mul_after prev_idx = base_idx + (k - 1) * axis_mul_after if exclusive: out_buf[cur_idx] = binop(out_buf[prev_idx], maybe_cast(data_buf[prev_idx])) else: out_buf[cur_idx] = binop(out_buf[prev_idx], maybe_cast(data_buf[cur_idx])) return ib.get() out_buf = decl_buffer(shape, dtype, "out_buf") return extern( [shape], [data], lambda ins, outs: gen_ir(ins[0], outs[0]), dtype=dtype, out_buffers=[out_buf], name=op_name, tag=op_name, ) def cumsum( data: tvm.te.Tensor, axis: Optional[int] = None, dtype: Optional[int] = None, exclusive: Optional[bool] = None, ) -> tvm.te.Tensor: """Numpy style cumsum op. Return the cumulative sum of the elements along a given axis. Parameters ---------- data : tvm.te.Tensor The input data to the operator. axis : int, optional Axis along which the cumulative sum is computed. The default (None) is to compute the cumsum over the flattened array. dtype : string, optional Type of the returned array and of the accumulator in which the elements are summed. If dtype is not specified, it defaults to the dtype of data. exclusive : bool, optional If True, will return exclusive sum in which the first element is not included. In other terms, if True, the j-th output element would be the sum of the first (j-1) elements. Otherwise, it would be the sum of the first j elements. Returns ------- result : tvm.te.Tensor The result has the same size as data, and the same shape as data if axis is not None. If axis is None, the result is a 1-d array. """ return scanop( data=data, binop=generic.add, identity_value=0, op_name="cumsum_generic", axis=axis, dtype=dtype, exclusive=exclusive, ) def cumprod( data: tvm.te.Tensor, axis: Optional[int] = None, dtype: Optional[int] = None, exclusive: Optional[bool] = None, ) -> tvm.te.Tensor: """Numpy style cumprod op. Return the cumulative product of the elements along a given axis. Parameters ---------- data : tvm.te.Tensor The input data to the operator. axis : int, optional Axis along which the cumulative product is computed. The default (None) is to compute the cumproduct over the flattened array. dtype : string, optional Type of the returned array and of the accumulator in which the elements are multiplied. If dtype is not specified, it defaults to the dtype of data. exclusive : bool, optional If True, will return exclusive product in which the first element is not included. In other terms, if True, the j-th output element would be the product of the first (j-1) elements. Otherwise, it would be the product of the first j elements. Returns ------- result : tvm.te.Tensor The result has the same size as data, and the same shape as data if axis is not None. If axis is None, the result is a 1-d array. """ return scanop( data=data, binop=generic.multiply, identity_value=1, op_name="cumprod_generic", axis=axis, dtype=dtype, exclusive=exclusive, )
https://github.com/zk-ml/tachikoma
python/tvm/topi/scatter.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=invalid-name, too-many-arguments, too-many-nested-blocks """Scatter operator""" from ..tir import decl_buffer, ir_builder, AssertStmt, StringImm, Evaluate, expr from ..te import extern, hybrid @hybrid.script def _scatter_1d(data, indices, updates): out = output_tensor(data.shape, data.dtype) for i in range(data.shape[0]): out[i] = data[i] for i in range(indices.shape[0]): out[indices[i] if indices[i] >= 0 else indices[i] + data.shape[0]] = updates[i] return out @hybrid.script def _scatter_2d(data, indices, updates, axis): out = output_tensor(data.shape, data.dtype) for i in range(data.shape[0]): for j in range(data.shape[1]): out[i, j] = data[i, j] if axis == 0: for i in range(indices.shape[0]): for j in range(indices.shape[1]): out[ indices[i, j] if indices[i, j] >= 0 else indices[i, j] + data.shape[axis], j ] = updates[i, j] else: for i in range(indices.shape[0]): for j in range(indices.shape[1]): out[ i, indices[i, j] if indices[i, j] >= 0 else indices[i, j] + data.shape[axis] ] = updates[i, j] return out @hybrid.script def _scatter_3d(data, indices, updates, axis): out = output_tensor(data.shape, data.dtype) for i in range(data.shape[0]): for j in range(data.shape[1]): for k in range(data.shape[2]): out[i, j, k] = data[i, j, k] if axis == 0: for i in range(indices.shape[0]): for j in range(indices.shape[1]): for k in range(indices.shape[2]): out[ indices[i, j, k] if indices[i, j, k] >= 0 else indices[i, j, k] + data.shape[axis], j, k, ] = updates[i, j, k] elif axis == 1: for i in range(indices.shape[0]): for j in range(indices.shape[1]): for k in range(indices.shape[2]): out[ i, indices[i, j, k] if indices[i, j, k] >= 0 else indices[i, j, k] + data.shape[axis], k, ] = updates[i, j, k] else: for i in range(indices.shape[0]): for j in range(indices.shape[1]): for k in range(indices.shape[2]): out[ i, j, indices[i, j, k] if indices[i, j, k] >= 0 else indices[i, j, k] + data.shape[axis], ] = updates[i, j, k] return out @hybrid.script def _scatter_4d(data, indices, updates, axis): out = output_tensor(data.shape, data.dtype) for i in range(data.shape[0]): for j in range(data.shape[1]): for k in range(data.shape[2]): for l in range(data.shape[3]): out[i, j, k, l] = data[i, j, k, l] if axis == 0: for i in range(indices.shape[0]): for j in range(indices.shape[1]): for k in range(indices.shape[2]): for l in range(indices.shape[3]): out[ indices[i, j, k, l] if indices[i, j, k, l] >= 0 else indices[i, j, k, l] + data.shape[axis], j, k, l, ] = updates[i, j, k, l] elif axis == 1: for i in range(indices.shape[0]): for j in range(indices.shape[1]): for k in range(indices.shape[2]): for l in range(indices.shape[3]): out[ i, indices[i, j, k, l] if indices[i, j, k, l] >= 0 else indices[i, j, k, l] + data.shape[axis], k, l, ] = updates[i, j, k, l] elif axis == 2: for i in range(indices.shape[0]): for j in range(indices.shape[1]): for k in range(indices.shape[2]): for l in range(indices.shape[3]): out[ i, j, indices[i, j, k, l] if indices[i, j, k, l] >= 0 else indices[i, j, k, l] + data.shape[axis], l, ] = updates[i, j, k, l] else: for i in range(indices.shape[0]): for j in range(indices.shape[1]): for k in range(indices.shape[2]): for l in range(indices.shape[3]): out[ i, j, k, indices[i, j, k, l] if indices[i, j, k, l] >= 0 else indices[i, j, k, l] + data.shape[axis], ] = updates[i, j, k, l] return out def scatter(data, indices, updates, axis=0): """Update data at positions defined by indices with values in updates Parameters ---------- data : relay.Expr The input data to the operator. indices : relay.Expr The index locations to update. updates : relay.Expr The values to update. axis : int The axis to scatter on Returns ------- ret : relay.Expr The computed result. """ if axis < 0: axis += len(data.shape) assert axis >= 0 assert axis < len(data.shape) if len(data.shape) == 1: return _scatter_1d(data, indices, updates) if len(data.shape) == 2: return _scatter_2d(data, indices, updates, axis) if len(data.shape) == 3: return _scatter_3d(data, indices, updates, axis) if len(data.shape) == 4: return _scatter_4d(data, indices, updates, axis) raise ValueError("scatter only support for 1-4 dimensions") def _verify_scatter_nd_inputs(data, indices, updates): mdim = int(indices.shape[0]) assert mdim <= len(data.shape), ( f"The first dimension of the indices ({mdim}) must be less than or equal to " f"the length of the shape of the output ({len(data.shape)})." ) for i in range(len(indices.shape) - 1): if isinstance(indices.shape[i + 1], expr.Var) or isinstance(updates.shape[i], expr.Var): continue assert indices.shape[i + 1] == updates.shape[i], ( f"Dimension of indices[{i+1}] ({indices.shape[i+1]}) must equal dimension of " f"updates[{i}] ({updates.shape[i]})." ) for i in range(mdim, len(data.shape)): data_ind = i - mdim + len(indices.shape) - 1 if isinstance(updates.shape[data_ind], expr.Var) or isinstance(data.shape[i], expr.Var): continue assert updates.shape[data_ind] == data.shape[i], ( f"Dimension of updates[{data_ind}] ({updates.shape[data_ind]}) must equal dimension " f"of out_shape[{i}] ({data.shape[i]})." ) assert ( "int" in indices.dtype ), f"Indices must be a tensor of integers, but its elements are {indices.dtype}." def scatter_nd(data, indices, updates, mode): """Scatter elements from a n-dimension array. Given updates with shape (Y_0, ..., Y_{K-1}, X_M, ..., X_{N-1}), indices with shape (M, Y_0, ..., Y_{K-1}), and output copied from data with shape (X_0, X_1, ..., X_{N-1}), scatter_nd computes .. code-block:: output[indices[0, y_0, ..., y_{K-1}], ..., indices[M-1, y_0, ..., y_{K-1}], x_M, ..., x_{N-1} ] = f(output[...], updates[y_0, ..., y_{K-1}, x_M, ..., x_{N-1}]) where the update function f is determinted by the mode. Parameters ---------- data : tvm.te.Tensor The source array. indices : tvm.te.Tensor The indices of the values to extract. updates : tvm.te.Tensor The updates to apply at the Indices mode : string The update mode for the algorithm, either "update" or "add" If update, the update values will replace the input data If add, the update values will be added to the input data Returns ------- ret : tvm.te.Tensor """ _verify_scatter_nd_inputs(data, indices, updates) def gen_ir(data_ptr, indices_ptr, updates_ptr, out_ptr): ib = ir_builder.create() data = ib.buffer_ptr(data_ptr) indices = ib.buffer_ptr(indices_ptr) updates = ib.buffer_ptr(updates_ptr) out = ib.buffer_ptr(out_ptr) fused_shape = 1 for i in data.shape: fused_shape *= i with ib.for_range(0, fused_shape) as i: out[i] = data[i] # We combine all the indices dimensions but the first one into a single # dimension so we can iterate it in single loop instead of an arbitrary # number of loops. We do the same thing for all the data dimensions. fused_indices_dimension = 1 for i in indices_ptr.shape[1:]: fused_indices_dimension *= i fused_data_dimension = 1 for i in data_ptr.shape[len(indices_ptr.shape) - 1 :]: fused_data_dimension *= i with ib.for_range(0, fused_indices_dimension, name="i") as i: with ib.for_range(0, fused_data_dimension, name="j") as j: offset = fused_data_dimension index = j # This is x_M, .. x_{N-1} part of the index into out. # Build up the indices[0, y_0, .. y_{K-1}], .. indices[M-1, y_0, .. y_{K-1}] part # of the index into out. for l in reversed(range(indices_ptr.shape[0].value)): # indices[i * l * fused_indices_dimension] = indices[l, y_0, ... y_{k-1}] index += offset * indices[i + l * fused_indices_dimension] ib.emit( AssertStmt( indices[i + l * fused_indices_dimension] < shape[l], StringImm("index out of bounds"), Evaluate(0), ) ) offset *= shape[l] if mode == "add": out[index] += updates[i * fused_data_dimension + j] elif mode == "update": out[index] = updates[i * fused_data_dimension + j] else: raise NotImplementedError("scatter_nd mode not in [update, add]:", mode) return ib.get() out_buf = decl_buffer(shape, data.dtype, "out_buf") return extern( [shape], [data, indices, updates], lambda ins, outs: gen_ir(ins[0], ins[1], ins[2], outs[0]), dtype=data.dtype, out_buffers=[out_buf], name="scatter_nd_generic", tag="scatter_nd_generic", )
https://github.com/zk-ml/tachikoma