conv_op.cc 9.0 KB
Newer Older
Y
Yan Chunwei 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed 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.

15
#include "lite/operators/conv_op.h"
16
#include "lite/core/subgraph_bridge_registry.h"
17 18
#include "lite/kernels/npu/bridges/graph.h"
#include "lite/kernels/npu/bridges/utility.h"
Y
Yan Chunwei 已提交
19 20 21

namespace paddle {
namespace lite {
22
namespace subgraph {
Y
Yan Chunwei 已提交
23 24
namespace npu {

25
int ConvConverter(void* ctx, OpLite* op, KernelBase* kernel) {
26 27 28 29
  CHECK(ctx != nullptr);
  CHECK(op != nullptr);
  auto graph = static_cast<Graph*>(ctx);
  auto op_info = op->op_info();
Y
Yan Chunwei 已提交
30
  auto op_type = op_info->Type();
31 32
  auto scope = op->scope();
  VLOG(3) << "[NPU] Converting " << op_type << "... ";
Y
Yan Chunwei 已提交
33

34 35 36
  // Get input and output vars and op attributes
  auto input_name = op_info->Input("Input").front();
  auto input = scope->FindMutableTensor(input_name);
Y
Yan Chunwei 已提交
37
  auto input_dims = input->dims();
Z
zhupengyang 已提交
38

39 40
  auto filter_name = op_info->Input("Filter").front();
  auto filter = scope->FindMutableTensor(filter_name);
Y
Yan Chunwei 已提交
41
  auto filter_dims = filter->dims();
Z
zhupengyang 已提交
42

43 44 45
  auto output_name = op_info->Output("Output").front();
  auto output = scope->FindMutableTensor(output_name);
  auto output_dims = output->dims();
Z
zhupengyang 已提交
46

47 48 49
  auto bs = input_dims[0];
  auto ic = input_dims[1];
  auto oc = filter_dims[0];
H
HappyAngel 已提交
50 51 52
  CHECK_EQ(input_dims.size(), 4L);
  CHECK_EQ(output_dims.size(), 4L);
  CHECK_EQ(filter_dims.size(), 4L);
53 54
  CHECK_EQ(output_dims[0], bs);
  CHECK_EQ(output_dims[1], oc);
Y
Yan Chunwei 已提交
55 56 57 58
  auto strides = op_info->GetAttr<std::vector<int>>("strides");
  auto paddings = op_info->GetAttr<std::vector<int>>("paddings");
  auto groups = op_info->GetAttr<int>("groups");
  auto dilations = op_info->GetAttr<std::vector<int>>("dilations");
Z
zhupengyang 已提交
59 60 61 62 63 64 65
  bool with_act =
      op_info->HasAttr("with_act") && op_info->GetAttr<bool>("with_act");
  std::string act_type =
      with_act ? op_info->GetAttr<std::string>("act_type") : "";
  float leaky_relu_alpha = act_type == "leaky_relu"
                               ? op_info->GetAttr<float>("leaky_relu_alpha")
                               : 0.f;
H
HappyAngel 已提交
66 67 68
  CHECK_EQ(strides.size(), 2L);
  CHECK_EQ(dilations.size(), 2L);

69
  // Input node
70 71 72
  std::shared_ptr<Node> input_node = nullptr;
  if (graph->Has(input_name)) {
    input_node = graph->Get(input_name);
73
  } else {
74
    input_node = graph->Add(input_name, *input);
75 76
  }

77 78 79 80 81 82 83
  if (paddings.size() == 2L) {
    for (size_t i = 0; i < strides.size(); ++i) {
      int copy_pad = *(paddings.begin() + 2 * i);
      paddings.insert(paddings.begin() + 2 * i + 1, copy_pad);
    }
  }
  CHECK_EQ(paddings.size(), 4L)
84
      << "[NPU] Paddings size should be the same or twice as the input size.";
85 86 87 88

  std::string padding_algorithm("");
  if (op_info->HasAttr("padding_algorithm")) {
    padding_algorithm = op_info->GetAttr<std::string>("padding_algorithm");
H
HappyAngel 已提交
89
  }
90 91 92 93 94 95
  operators::UpdatePaddingAndDilation(&paddings,
                                      &dilations,
                                      strides,
                                      padding_algorithm,
                                      input_dims,
                                      filter_dims);
Y
Yan Chunwei 已提交
96

97
  // Check depthwise mode, and decide whether use ConvolutionDepthwise Op
Y
Yan Chunwei 已提交
98
  bool use_depthwise_conv =
99
      false;  // Whether use ge::op::ConvolutionDepthwise ?
100
  bool is_depthwise_mode = ic == groups && oc == groups;
Y
Yan Chunwei 已提交
101 102 103 104
  if (is_depthwise_mode &&
      !((groups == 1 || groups >= 5) && dilations[0] == 1 &&
        dilations[1] == 1)) {
    use_depthwise_conv = true;
105 106 107 108
    LOG(WARNING) << "[NPU] For depthwise mode, dilation = 1 and groups >= 5 "
                    "(or groups = 1) is only supported in Convolution Op, so "
                    "force to use ConvolutionDepthwise Op, but may lead poor "
                    "performance.";
Y
Yan Chunwei 已提交
109 110
  }

111
  // Filter node
112
  auto filter_node = graph->Add(filter_name, *filter);
Y
Yan Chunwei 已提交
113

114
  // Add bias node if exists bias
115
  // Supports the bias nodes with the following dimensions
116 117 118
  // 0: {oc}
  // 1: {1, oc, oh, ow}
  // 2: {n, oc, oh, ow}
119
  std::shared_ptr<Node> bias_node = nullptr;
120
  bool is_channel_bias = false;
121
  if (HasInputArg(op_info, scope, "Bias")) {
122
    auto bias_name = op_info->Input("Bias").front();
123 124
    if (graph->Has(bias_name)) {
      bias_node = graph->Get(bias_name);
125
    } else {
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
      auto bias = scope->FindMutableTensor(bias_name);
      auto bias_dims = bias->dims();
      auto bias_data_size = bias_dims.production();
      auto output_data_size = output_dims.production();
      std::vector<int64_t> bias_shape;
      if (bias_data_size == oc) {
        // 0: {oc}
        bias_shape = {1, oc, 1, 1};
        is_channel_bias = true;
      } else if (bias_data_size == output_data_size / bs) {
        // 1: {1, oc, oh, ow}
        bias_shape = {1, output_dims[1], output_dims[2], output_dims[3]};
      } else if (bias_data_size == output_data_size) {
        // 2: {n, oc, oh, ow}
        bias_shape = output_dims.Vectorize();
      } else {
        LOG(WARNING)
            << "[NPU] Bias dimension " << bias_dims
            << " isn't supported in conv2d Op when output dimension is "
            << output_dims;
        return FAILED;
      }
      bias_node = graph->Add(bias_name, *bias, bias_shape);
149
    }
Y
Yan Chunwei 已提交
150 151
  }

152
  // Conv node
153
  std::shared_ptr<Node> conv_node = nullptr;
Y
Yan Chunwei 已提交
154
  if (use_depthwise_conv && is_depthwise_mode) {
155 156 157 158 159 160 161 162 163 164
    conv_node = graph->Add<ge::op::ConvolutionDepthwise>(output_name);
    auto conv_op = conv_node->data<ge::op::ConvolutionDepthwise>();
    conv_op->set_input_x(*input_node->data());
    conv_op->set_input_filter(*filter_node->data());
    conv_op->set_attr_mode(1);
    conv_op->set_attr_algo(0);
    conv_op->set_attr_format(0);    // NCHW
    conv_op->set_attr_pad_mode(5);  // VALID
    conv_op->set_attr_group(groups);
    conv_op->set_attr_pad(ge::AttrValue::LIST_INT(
165
        {paddings[0], paddings[1], paddings[2], paddings[3]}));
166
    conv_op->set_attr_dilation(
Y
Yan Chunwei 已提交
167
        ge::AttrValue::LIST_INT({dilations[0], dilations[1]}));
168 169
    conv_op->set_attr_stride(ge::AttrValue::LIST_INT({strides[0], strides[1]}));
    conv_op->set_attr_kernel(
Y
Yan Chunwei 已提交
170
        ge::AttrValue::LIST_INT({filter_dims[2], filter_dims[3]}));
171 172 173
    // ConvolutionDepthwise Op doesn't support bias, so append Add node to
    // support bias
    if (bias_node != nullptr) {
174 175 176 177
      auto add_node = graph->Add<ge::op::Add>(output_name);
      auto add_op = add_node->data<ge::op::Add>();
      add_op->set_input_x1(*conv_node->data());
      add_op->set_input_x2(*bias_node->data());
Y
Yan Chunwei 已提交
178
      conv_node = add_node;
Y
Yan Chunwei 已提交
179 180
    }
  } else {
181 182 183 184 185
    conv_node = graph->Add<ge::op::Convolution>(output_name);
    auto conv_op = conv_node->data<ge::op::Convolution>();
    conv_op->set_input_x(*input_node->data());
    conv_op->set_input_w(*filter_node->data());
    conv_op->set_attr_mode(1);
Z
zhupengyang 已提交
186 187 188 189 190 191
    // when padding_algorithm=="SAME", NPU is different from lite
    if (padding_algorithm == "VALID") {
      conv_op->set_attr_pad_mode(5);
    } else {
      conv_op->set_attr_pad_mode(0);
    }
192 193
    conv_op->set_attr_group(groups);
    conv_op->set_attr_pad(ge::AttrValue::LIST_INT(
Z
zhupengyang 已提交
194
        {paddings[0], paddings[1], paddings[2], paddings[3]}));
195
    conv_op->set_attr_dilation(
Y
Yan Chunwei 已提交
196
        ge::AttrValue::LIST_INT({dilations[0], dilations[1]}));
197 198
    conv_op->set_attr_stride(ge::AttrValue::LIST_INT({strides[0], strides[1]}));
    conv_op->set_attr_kernel(
Y
Yan Chunwei 已提交
199
        ge::AttrValue::LIST_INT({filter_dims[2], filter_dims[3]}));
200 201 202 203
    // Convolution Op only support bias with dimension {1, oc, 1, 1},
    // so append Add node if dimension is {1, oc, oh, ow} or (n, oc, oh, ow)
    if (bias_node != nullptr) {
      if (is_channel_bias) {
204
        conv_op->set_input_b(*bias_node->data());
205
      } else {
206 207 208 209
        auto add_node = graph->Add<ge::op::Add>(output_name);
        auto add_op = add_node->data<ge::op::Add>();
        add_op->set_input_x1(*conv_node->data());
        add_op->set_input_x2(*bias_node->data());
210 211 212
        conv_node = add_node;
      }
    }
Y
Yan Chunwei 已提交
213 214 215
  }
  CHECK(conv_node);

Z
zhupengyang 已提交
216 217 218 219 220 221 222
  if (!act_type.empty()) {
    auto act_node = graph->Add<ge::op::Activation>(output_name);
    auto act_op = act_node->data<ge::op::Activation>();
    act_op->set_input_x(*conv_node->data());
    act_op->set_attr_mode(CvtActMode(act_type));
    if (act_type == "leaky_relu") {
      act_op->set_attr_negative_slope(leaky_relu_alpha);
223 224
    } else if (act_type == "relu6") {
      act_op->set_attr_coef(6.f);
Z
zhupengyang 已提交
225
    }
Y
Yan Chunwei 已提交
226
  }
Z
zhupengyang 已提交
227

228
  return REBUILD_WHEN_SHAPE_CHANGED;
Y
Yan Chunwei 已提交
229 230 231
}

}  // namespace npu
232
}  // namespace subgraph
Y
Yan Chunwei 已提交
233 234 235
}  // namespace lite
}  // namespace paddle

236 237
REGISTER_SUBGRAPH_BRIDGE(conv2d,
                         kNPU,
238
                         paddle::lite::subgraph::npu::ConvConverter);
239 240
REGISTER_SUBGRAPH_BRIDGE(depthwise_conv2d,
                         kNPU,
241
                         paddle::lite::subgraph::npu::ConvConverter);