conv_op.cc 7.0 KB
Newer Older
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 17 18
#include "lite/kernels/npu/bridges/registry.h"
#include "lite/kernels/xpu/bridges/graph.h"
#include "lite/kernels/xpu/bridges/utility.h"
19 20 21

namespace paddle {
namespace lite {
22
namespace subgraph {
23 24
namespace xpu {

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

34 35 36 37 38 39
  // Get input and output vars and op attributes
  auto input_name = op_info->Input("Input").front();
  auto input_type = kernel->GetInputDeclType("Input");
  CHECK(input_type->precision() == PRECISION(kFloat));
  CHECK(input_type->layout() == DATALAYOUT(kNCHW));
  auto input = scope->FindMutableTensor(input_name);
40
  auto input_dims = input->dims();
41 42 43 44 45
  auto filter_name = op_info->Input("Filter").front();
  auto filter_type = kernel->GetInputDeclType("Filter");
  CHECK(filter_type->precision() == PRECISION(kFloat));
  CHECK(filter_type->layout() == DATALAYOUT(kNCHW));
  auto filter = scope->FindMutableTensor(filter_name);
46
  auto filter_dims = filter->dims();
47 48 49 50
  auto output_name = op_info->Output("Output").front();
  auto output_type = kernel->GetOutputDeclType("Output");
  CHECK(output_type->precision() == PRECISION(kFloat));
  CHECK(output_type->layout() == DATALAYOUT(kNCHW));
51 52 53 54 55 56 57 58 59
  auto bs = input_dims[0];
  auto oc = filter_dims[0];
  CHECK_EQ(input_dims.size(), 4);
  CHECK_EQ(filter_dims.size(), 4);
  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");
  auto fuse_relu = op_info->GetAttr<bool>("fuse_relu");
H
HappyAngel 已提交
60 61
  CHECK_EQ(strides.size(), 2L);
  CHECK_EQ(dilations.size(), 2L);
62

63 64 65 66 67 68 69 70
  // Input node
  std::shared_ptr<xtcl::xExpr> input_node = nullptr;
  if (graph->HasNode(input_name)) {
    input_node = graph->GetNode(input_name);
  } else {
    input_node = graph->AddNode(input_name, input_dims);
  }

71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
  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)
      << "Paddings size should be the same or twice as the input size.";

  std::string padding_algorithm("");
  if (op_info->HasAttr("padding_algorithm")) {
    padding_algorithm = op_info->GetAttr<std::string>("padding_algorithm");
  }
  operators::UpdatePaddingAndDilation(&paddings,
                                      &dilations,
                                      strides,
                                      padding_algorithm,
                                      input_dims,
                                      filter_dims);

91 92 93 94
  std::vector<int64_t> output_shape({bs, oc});
  for (size_t i = 0; i < 2; i++) {
    const int dkernel = dilations[i] * (filter_dims[2 + i] - 1) + 1;
    output_shape.push_back(
H
HappyAngel 已提交
95 96 97
        (input_dims[i + 2] + paddings[2 * i] + paddings[2 * i + 1] - dkernel) /
            strides[i] +
        1);
98 99 100
  }
  DDim output_dims(output_shape);

101 102
  // Filter node
  auto filter_const_node = graph->AddNode(filter_name, *filter);
103

104
  // Conv node
105
  auto conv_attrs = xtcl::make_node<xtcl::network::Conv2DAttrs>();
106 107 108
  conv_attrs->strides = std::move(CvtShape<xtcl::xIndexExpr>(strides));
  conv_attrs->padding = std::move(CvtShape<xtcl::xIndexExpr>(paddings));
  conv_attrs->dilation = std::move(CvtShape<xtcl::xIndexExpr>(dilations));
109 110 111 112 113 114 115
  conv_attrs->groups = groups;
  // conv_attrs->channels = nullptr;
  conv_attrs->kernel_size = std::move(xtcl::Array<xtcl::xIndexExpr>(nullptr));
  conv_attrs->data_layout = "NCHW";
  conv_attrs->kernel_layout = "OIHW";
  conv_attrs->out_layout = "";
  // conv_attrs->out_dtype = "";
116 117 118 119
  auto conv_node =
      graph->AddNode(output_name,
                     graph->builder_.CreateConv2D(
                         *input_node, *filter_const_node, conv_attrs));
120

121
  // Add bias node if exists bias
122 123 124 125
  // supports the bias nodes with the following dimensions
  // 0: {oc}
  // 1: {1, oc, oh, ow}
  // 2: {n, oc, oh, ow}
126
  if (HasInputArg(op_info, scope, "Bias")) {
127 128 129 130 131
    auto bias_name = op_info->Input("Bias").front();
    auto bias_type = kernel->GetInputDeclType("Bias");
    CHECK(bias_type->precision() == PRECISION(kFloat));
    CHECK(bias_type->layout() == DATALAYOUT(kNCHW));
    auto bias = scope->FindMutableTensor(bias_name);
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
    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;
    bool is_channel_bias = false;
    if (bias_data_size == oc) {
      // 0: {oc}
      bias_shape = {oc};
      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 {
148
      LOG(ERROR) << "[XPU] Bias dimension " << bias_dims
149 150 151 152
                 << " isn't supported in conv2d Op when output dimension is "
                 << output_dims;
    }
    std::shared_ptr<xtcl::xExpr> bias_node = nullptr;
153
    if (graph->HasNode(bias_name)) {
154
      // Bias node from input node
155
      bias_node = graph->GetNode(bias_name);
156
    } else {
157 158
      // Bias node with const data
      bias_node = graph->AddNode(bias_name, *bias, bias_shape);
159 160 161
    }
    std::shared_ptr<xtcl::xExpr> add_node = nullptr;
    if (is_channel_bias) {
162
      add_node = graph->AddNode(
163
          output_name,
164
          graph->builder_.CreateBiasAdd(*conv_node, 1, *bias_node));
165
    } else {
166
      add_node = graph->AddNode(
167
          output_name,
168
          graph->builder_.CreateBinaryOp("add", *conv_node, *bias_node));
169 170 171 172 173
    }
    conv_node = add_node;
  }

  if (fuse_relu) {
174
    // Append relu node if fuse_relu is true
175
    graph->AddNode(output_name, graph->builder_.CreateRelu(*conv_node));
176
  }
177
  return REBUILD_WHEN_SHAPE_CHANGED;
178 179 180
}

}  // namespace xpu
181
}  // namespace subgraph
182 183 184
}  // namespace lite
}  // namespace paddle

185 186 187 188 189 190
REGISTER_SUBGRAPH_BRIDGE(XPU,
                         conv2d,
                         paddle::lite::subgraph::xpu::ConvConverter);
REGISTER_SUBGRAPH_BRIDGE(XPU,
                         depthwise_conv2d,
                         paddle::lite::subgraph::xpu::ConvConverter);