You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@tvm.apache.org by GitBox <gi...@apache.org> on 2021/05/18 17:57:48 UTC

[GitHub] [tvm] tkonolige commented on a change in pull request #8065: [Autoscheduler] Add sparse conv2d(1*1) support for auto_scheduler

tkonolige commented on a change in pull request #8065:
URL: https://github.com/apache/tvm/pull/8065#discussion_r634603256



##########
File path: python/tvm/relay/analysis/sparse_conv2d.py
##########
@@ -0,0 +1,154 @@
+# 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=no-else-return
+# pylint: disable=unidiomatic-typecheck
+"""
+This file contains helper functions for convert dense model
+to block sparse model
+"""
+from collections import namedtuple
+import numpy as np
+import scipy.sparse as sp
+import tvm
+from . import _ffi_api
+
+
+SparseAnalysisResult = namedtuple(
+    "SparseAnalysisResult",
+    [
+        "weight_name",
+        "weight_shape",
+    ],
+)
+
+
+def _search_conv2d_op_weight(expr):
+    """Search name of weight in all ```nn.conv2d``` operator
+       This is a helpful function to determine which param need
+       to be converted to sparse
+
+    Parameters
+    ----------
+    expr : relay.Expr
+        Expr will be searched
+
+    Returns
+    -------
+    ret : Array[String]
+        name of weight in all ``nn.conv2d``` operator
+    """
+    return _ffi_api.search_conv2d_op_weight(expr)
+
+
+def process_params(expr, params, block_size, sparsity_threshold, layout):
+    """[summary]

Review comment:
       Missing documentation?

##########
File path: python/tvm/topi/nn/sparse.py
##########
@@ -478,6 +478,270 @@ def _traverse(t):
     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"):
+    """
+    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], float32 (layout=NHWC)
+        4-D with shape [M, K, H, W], float32 (layout=NCHW)

Review comment:
       Is float32 required?

##########
File path: src/relay/transforms/convert_sparse_conv2d.cc
##########
@@ -0,0 +1,161 @@
+/*
+ * 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.
+ */
+
+/*!
+ *
+ * \file convert_sparse_conv2d.cc
+ *
+ * \brief Mutate dense operator to sparse dense operator

Review comment:
       ```suggestion
    * \brief Mutate dense conv2d operator to sparse conv2d operator
   ```

##########
File path: src/relay/op/nn/sparse.cc
##########
@@ -237,5 +238,67 @@ RELAY_REGISTER_OP("nn.sparse_add")
     .set_support_level(1)
     .add_type_rel("SparseAdd", SparseAddRel);
 
+TVM_REGISTER_NODE_TYPE(SparseConv2DAttrs);
+
+bool SparseConv2dRel(const Array<Type>& types, int num_inputs, const Attrs& attrs,
+                     const TypeReporter& reporter) {
+  ICHECK_EQ(types.size(), 5);
+  const auto* param = attrs.as<SparseConv2DAttrs>();
+  ICHECK(param != nullptr);
+
+  const auto* data = types[0].as<TensorTypeNode>();
+  const auto* weight_data = types[1].as<TensorTypeNode>();
+  ICHECK(weight_data->shape.size() == 1 || weight_data->shape.size() == 2 ||
+         weight_data->shape.size() == 3);
+  const auto* weight_indptr = types[3].as<TensorTypeNode>();
+  if (data == nullptr) return false;
+
+  if (weight_data->shape.size() == 2 || weight_data->shape.size() == 3) {
+    // BSR case.
+    if (param->layout == "NHWC") {
+      Array<IndexExpr> oshape({data->shape[0], data->shape[1], data->shape[2],
+                               (weight_indptr->shape[0] - 1) * weight_data->shape[1]});
+      reporter->Assign(types[4], TensorType(oshape, data->dtype));
+      return true;
+    } else if (param->layout == "NCHW") {
+      Array<IndexExpr> oshape({data->shape[0],
+                               (weight_indptr->shape[0] - 1) * weight_data->shape[1],
+                               data->shape[2], data->shape[3]});
+      reporter->Assign(types[4], TensorType(oshape, data->dtype));
+      return true;
+    }
+  }
+  LOG(FATAL) << "Unknown weight ndim for nn.sparse_conv2d, should be 3 (BSR)";

Review comment:
       Can you print out the actual weight here.

##########
File path: src/relay/op/nn/sparse.cc
##########
@@ -237,5 +238,67 @@ RELAY_REGISTER_OP("nn.sparse_add")
     .set_support_level(1)
     .add_type_rel("SparseAdd", SparseAddRel);
 
+TVM_REGISTER_NODE_TYPE(SparseConv2DAttrs);
+
+bool SparseConv2dRel(const Array<Type>& types, int num_inputs, const Attrs& attrs,
+                     const TypeReporter& reporter) {
+  ICHECK_EQ(types.size(), 5);

Review comment:
       Can you add an error message.




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org