fc_mkldnn_op.cc 10.4 KB
Newer Older
M
mozga-intel 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/* Copyright (c) 2018 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 16
#include <mkldnn/include/mkldnn_types.h>
#include <memory>
M
mozga-intel 已提交
17
#include "paddle/fluid/framework/tensor.h"
18
#include "paddle/fluid/operators/fc_op.h"
M
mozga-intel 已提交
19 20
#include "paddle/fluid/platform/device_context.h"
#include "paddle/fluid/platform/mkldnn_helper.h"
21
#include "paddle/fluid/platform/variant.h"
M
mozga-intel 已提交
22 23 24 25

namespace paddle {
namespace operators {

26 27 28 29 30 31 32 33 34 35 36 37 38
using framework::DataLayout;
using framework::Tensor;
using framework::LoDTensor;
using framework::DDim;
using framework::ExecutionContext;
using platform::MKLDNNDeviceContext;
using platform::to_void_cast;
using platform::GetMKLDNNFormat;
using mkldnn::memory;
using mkldnn::inner_product_forward;
using mkldnn::primitive;
using mkldnn::stream;
using mkldnn::prop_kind;
M
mozga-intel 已提交
39 40

template <typename T>
41
class FCPrimitiveFactory {
M
mozga-intel 已提交
42
 public:
43 44 45 46 47 48 49 50 51 52 53 54 55
  explicit FCPrimitiveFactory(const mkldnn::engine& engine) : engine_(engine) {}

  inner_product_forward CreateFcPrimitive(const LoDTensor* input,
                                          const Tensor* weights,
                                          const Tensor* bias, LoDTensor* output,
                                          const ExecutionContext& ctx) {
    RecomputeOutputDims(ctx, input, weights, output);
    if (fc_) {
      UpdateDataPointers(ctx, output, input);
      return *fc_;
    }
    auto src_desc = CreateMemDescriptor(input, input->format());
    input_ = CreateMemory(src_desc, input);
M
mozga-intel 已提交
56

57 58 59 60 61 62
    weights_ = TransposeWeights(weights);
    if (src_desc.data.ndims == 4) {
      weights_ = CreateFourDimWeightsMemory(input, weights);
    }

    auto dst_desc = CreateMemDescriptor(output, memory::format::any);
M
mozga-intel 已提交
63

64 65
    fc_ = CreateFcPrimitive(*input_, *weights_, dst_desc, bias, output, ctx);
    return *fc_;
M
mozga-intel 已提交
66 67
  }

68 69 70 71 72 73 74 75 76
 private:
  void UpdateDataPointers(const ExecutionContext& ctx, Tensor* out,
                          const Tensor* in) {
    input_->set_data_handle(const_cast<T*>(in->data<T>()));
    output_->set_data_handle(out->mutable_data<T>(ctx.GetPlace()));
    if (out->format() == memory::format::format_undef) {
      auto output_format = output_->get_primitive_desc().desc().data.format;
      out->set_format((memory::format)output_format);
    }
M
mozga-intel 已提交
77 78
  }

79 80 81 82 83 84 85 86 87 88 89 90
  memory::format MatchWeightFormat(memory::format fmt) {
    using format = memory::format;
    switch (fmt) {
      case format::nChw16c:
        return format::oIhw16i;
      case format::nChw8c:
        return format::oIhw8i;
      case format::nchw:
        return format::oihw;
      default:
        return format::format_undef;
    }
M
mozga-intel 已提交
91 92
  }

93 94 95 96
  mkldnn::memory Reorder(const memory::desc& src_desc,
                         const memory::desc& dst_desc, const void* src_data) {
    auto src_mem = memory({src_desc, engine_}, const_cast<void*>(src_data));
    auto dst_mem = memory({dst_desc, engine_});
M
mozga-intel 已提交
97

98 99
    auto reorder = mkldnn::reorder(src_mem, dst_mem);
    stream(stream::kind::eager).submit({reorder}).wait();
M
mozga-intel 已提交
100

101
    return dst_mem;
M
mozga-intel 已提交
102 103
  }

104 105 106 107
  static mkldnn::memory::desc CreateMemDescriptor(const std::vector<int>& dims,
                                                  memory::format format) {
    return platform::MKLDNNMemDesc(dims, platform::MKLDNNGetDataType<T>(),
                                   format);
M
mozga-intel 已提交
108 109
  }

110 111 112 113
  static mkldnn::memory::desc CreateMemDescriptor(const Tensor* tensor,
                                                  memory::format format) {
    auto dims = framework::vectorize2int(tensor->dims());
    return CreateMemDescriptor(dims, format);
M
mozga-intel 已提交
114 115
  }

116 117 118
  mkldnn::memory CreateMemory(const mkldnn::memory::desc& desc,
                              const Tensor* tensor) {
    return CreateMemory(desc, tensor->data<T>());
M
mozga-intel 已提交
119 120
  }

121 122 123
  mkldnn::memory CreateMemory(const mkldnn::memory::desc& desc,
                              const void* data) {
    return memory({desc, engine_}, const_cast<void*>(data));
M
mozga-intel 已提交
124 125
  }

126 127 128 129 130 131 132
  mkldnn::memory TransposeWeights(const Tensor* weights) {
    auto dims = framework::vectorize2int(weights->dims());
    std::swap(dims[0], dims[1]);  // Correct output dimensions
    auto src_desc = CreateMemDescriptor(dims, memory::format::io);
    auto dst_desc = CreateMemDescriptor(dims, memory::format::oi);
    return Reorder(src_desc, dst_desc, weights->data<T>());
  }
M
mozga-intel 已提交
133

134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
  inner_product_forward CreateFcPrimitive(const memory& src_memory,
                                          const memory& weights_memory,
                                          const memory::desc& dst_desc,
                                          const Tensor* bias, Tensor* output,
                                          const ExecutionContext& ctx) {
    const auto weights_desc = weights_memory.get_primitive_desc().desc();
    const auto src_desc = src_memory.get_primitive_desc().desc();
    if (bias) {
      auto bias_desc = CreateMemDescriptor(bias, bias->format());
      bias_ = CreateMemory(bias_desc, bias);
      auto fc_prim_desc =
          CreateFcPrimDesc(src_desc, weights_desc, bias_desc, dst_desc);

      output_ = CreateDstMemory(fc_prim_desc, ctx, output);

      return inner_product_forward(fc_prim_desc, src_memory, weights_memory,
                                   *bias_, *output_);
    } else {
      auto fc_prim_desc = CreateFcPrimDesc(src_desc, weights_desc, dst_desc);

      output_ = CreateDstMemory(fc_prim_desc, ctx, output);

      return inner_product_forward(fc_prim_desc, src_memory, weights_memory,
                                   *output_);
    }
  }
M
mozga-intel 已提交
160

161 162 163 164 165 166 167 168
  mkldnn::inner_product_forward::primitive_desc CreateFcPrimDesc(
      const mkldnn::memory::desc& input_desc,
      const mkldnn::memory::desc& weights_desc,
      const mkldnn::memory::desc& bias_desc,
      const mkldnn::memory::desc& dst_desc) {
    auto fc_desc =
        inner_product_forward::desc(prop_kind::forward_scoring, input_desc,
                                    weights_desc, bias_desc, dst_desc);
M
mozga-intel 已提交
169

170 171
    return inner_product_forward::primitive_desc(fc_desc, engine_);
  }
M
mozga-intel 已提交
172

173 174 175 176 177 178
  mkldnn::inner_product_forward::primitive_desc CreateFcPrimDesc(
      const mkldnn::memory::desc& input_desc,
      const mkldnn::memory::desc& weights_desc,
      const mkldnn::memory::desc& dst_desc) {
    auto fc_desc = inner_product_forward::desc(prop_kind::forward, input_desc,
                                               weights_desc, dst_desc);
M
mozga-intel 已提交
179

180 181
    return inner_product_forward::primitive_desc(fc_desc, engine_);
  }
M
mozga-intel 已提交
182

183 184 185 186 187
  mkldnn::memory CreateFourDimWeightsMemory(const Tensor* input,
                                            const Tensor* weights) {
    auto input_dims = framework::vectorize2int(input->dims());
    auto weight_dims = framework::vectorize2int(weights->dims());
    auto dims = {weight_dims[1], input_dims[1], input_dims[2], input_dims[3]};
M
mozga-intel 已提交
188

189 190 191
    auto dst_format = MatchWeightFormat(input->format());
    auto src_desc = CreateMemDescriptor(dims, memory::format::oihw);
    auto dst_desc = CreateMemDescriptor(dims, dst_format);
M
mozga-intel 已提交
192

193 194
    return Reorder(src_desc, dst_desc, weights_->get_data_handle());
  }
M
mozga-intel 已提交
195

196 197 198 199 200
  mkldnn::memory CreateDstMemory(
      const mkldnn::inner_product_forward::primitive_desc& fc_prim_desc,
      const ExecutionContext& ctx, Tensor* output) {
    auto dst_prim_desc = fc_prim_desc.dst_primitive_desc();
    auto buffer_size = dst_prim_desc.get_size();
201
    T* output_data = output->mutable_data<T>(ctx.GetPlace(), buffer_size);
202 203 204
    output->set_format((memory::format)dst_prim_desc.desc().data.format);
    return memory(dst_prim_desc, to_void_cast<T>(output_data));
  }
M
mozga-intel 已提交
205

206 207
  void RecomputeOutputDims(const ExecutionContext& ctx, const LoDTensor* input,
                           const Tensor* w, LoDTensor* output) {
L
luotao1 已提交
208 209 210 211 212
    int in_num_col_dims = ctx.Attr<int>("in_num_col_dims");
    std::vector<int64_t> output_dims;
    FCOutputSize(input->dims(), w->dims(), output_dims, in_num_col_dims);
    output->Resize(framework::make_ddim(output_dims));
    output->set_lod(input->lod());
213
  }
L
luotao1 已提交
214

215 216 217 218 219 220 221 222
 private:
  const mkldnn::engine& engine_;
  boost::optional<memory> bias_;
  boost::optional<memory> input_;
  boost::optional<memory> output_;
  boost::optional<memory> weights_;
  boost::optional<inner_product_forward> fc_;
};
M
mozga-intel 已提交
223

224 225 226 227 228 229 230 231 232 233 234 235
static std::string GetHash(const Tensor* input, const Tensor* weights,
                           const std::string& suffix) {
  auto dim2str = [](const DDim& operand_dims) {
    std::string str = "";
    for (size_t i = 0; i < operand_dims.size(); ++i) {
      str += std::to_string(operand_dims[i]) + "-";
    }
    return str;
  };
  return std::to_string((unsigned)input->format()) + dim2str(weights->dims()) +
         suffix;
}
M
mozga-intel 已提交
236

237 238 239 240 241 242 243 244 245 246 247 248
template <typename T>
std::shared_ptr<FCPrimitiveFactory<T>> GetPrimitiveFactory(
    const MKLDNNDeviceContext& dev_ctx, const ExecutionContext& ctx,
    const Tensor* input, const Tensor* weights,
    const mkldnn::engine& mkldnn_engine) {
  const std::string key = GetHash(input, weights, ctx.op().Output("Out"));

  auto prim_creator =
      std::static_pointer_cast<FCPrimitiveFactory<T>>(dev_ctx.GetBlob(key));
  if (prim_creator == nullptr) {
    prim_creator = std::make_shared<FCPrimitiveFactory<T>>(mkldnn_engine);
    dev_ctx.SetBlob(key, prim_creator);
M
mozga-intel 已提交
249 250
  }

251 252
  return prim_creator;
}
M
mozga-intel 已提交
253 254

template <typename T>
255
class FCMKLDNNOpKernel : public framework::OpKernel<T> {
M
mozga-intel 已提交
256 257
 public:
  void Compute(const paddle::framework::ExecutionContext& ctx) const override {
258
    PADDLE_ENFORCE(platform::is_cpu_place(ctx.GetPlace()),
M
mozga-intel 已提交
259 260 261 262
                   "It must use CPUPlace.");
    auto& dev_ctx = ctx.template device_context<MKLDNNDeviceContext>();
    const auto& mkldnn_engine = dev_ctx.GetEngine();

263 264
    auto input = ctx.Input<LoDTensor>("Input");
    auto w = ctx.Input<Tensor>("W");
T
tensor-tang 已提交
265
    auto bias = ctx.Input<Tensor>("Bias");
266
    auto output = ctx.Output<LoDTensor>("Out");
M
mozga-intel 已提交
267

268 269 270 271
    auto prim_creator =
        GetPrimitiveFactory<T>(dev_ctx, ctx, input, w, mkldnn_engine);
    auto fc = prim_creator->CreateFcPrimitive(input, w, bias, output, ctx);
    stream(stream::kind::eager).submit({fc}).wait();
M
mozga-intel 已提交
272

273
    output->set_layout(DataLayout::kMKLDNN);
M
mozga-intel 已提交
274 275 276 277 278 279 280
  }
};
}  // namespace operators
}  // namespace paddle

REGISTER_OP_KERNEL(fc, MKLDNN, ::paddle::platform::CPUPlace,
                   paddle::operators::FCMKLDNNOpKernel<float>);