fc_mkldnn_op.cc 10.1 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
    weights_ = TransposeWeights(weights);
    if (src_desc.data.ndims == 4) {
      weights_ = CreateFourDimWeightsMemory(input, weights);
    }

62
    auto dst_desc = CreateMemDescriptor(output, MKLDNNMemoryFormat::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
 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()));
73
    if (out->format() == MKLDNNMemoryFormat::format_undef) {
A
Adam 已提交
74
      auto output_format = platform::GetMKLDNNFormat(*output_);
75
      out->set_format((MKLDNNMemoryFormat)output_format);
76
    }
M
mozga-intel 已提交
77 78
  }

79 80
  MKLDNNMemoryFormat MatchWeightFormat(MKLDNNMemoryFormat fmt) {
    using format = MKLDNNMemoryFormat;
81 82 83 84 85 86 87 88 89 90
    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
  static mkldnn::memory::desc CreateMemDescriptor(const std::vector<int>& dims,
105
                                                  MKLDNNMemoryFormat format) {
106 107
    return platform::MKLDNNMemDesc(dims, platform::MKLDNNGetDataType<T>(),
                                   format);
M
mozga-intel 已提交
108 109
  }

110
  static mkldnn::memory::desc CreateMemDescriptor(const Tensor* tensor,
111
                                                  MKLDNNMemoryFormat format) {
112
    auto dims = framework::vectorize<int>(tensor->dims());
113
    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
  mkldnn::memory TransposeWeights(const Tensor* weights) {
127
    auto dims = framework::vectorize<int>(weights->dims());
128
    std::swap(dims[0], dims[1]);  // Correct output dimensions
129 130
    auto src_desc = CreateMemDescriptor(dims, MKLDNNMemoryFormat::io);
    auto dst_desc = CreateMemDescriptor(dims, MKLDNNMemoryFormat::oi);
131 132
    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
  mkldnn::memory CreateFourDimWeightsMemory(const Tensor* input,
                                            const Tensor* weights) {
185 186
    auto input_dims = framework::vectorize<int>(input->dims());
    auto weight_dims = framework::vectorize<int>(weights->dims());
187
    auto dims = {weight_dims[1], input_dims[1], input_dims[2], input_dims[3]};
M
mozga-intel 已提交
188

189
    auto dst_format = MatchWeightFormat(input->format());
190
    auto src_desc = CreateMemDescriptor(dims, MKLDNNMemoryFormat::oihw);
191
    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);
A
Adam 已提交
202 203 204
    memory dst_mem(dst_prim_desc, to_void_cast<T>(output_data));
    output->set_format(platform::GetMKLDNNFormat(dst_mem));
    return dst_mem;
205
  }
M
mozga-intel 已提交
206

207 208
  void RecomputeOutputDims(const ExecutionContext& ctx, const LoDTensor* input,
                           const Tensor* w, LoDTensor* output) {
L
luotao1 已提交
209 210 211 212 213
    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());
214
  }
L
luotao1 已提交
215

216 217 218 219 220 221 222 223
 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 已提交
224

225 226 227 228 229
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) {
230
  const std::string key = platform::CreateKey(
231
      framework::vectorize<int>(weights->dims()), ctx.op().Output("Out"));
232 233 234 235 236 237

  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 已提交
238 239
  }

240 241
  return prim_creator;
}
M
mozga-intel 已提交
242 243

template <typename T>
244
class FCMKLDNNOpKernel : public framework::OpKernel<T> {
M
mozga-intel 已提交
245 246
 public:
  void Compute(const paddle::framework::ExecutionContext& ctx) const override {
247
    PADDLE_ENFORCE(platform::is_cpu_place(ctx.GetPlace()),
M
mozga-intel 已提交
248 249 250 251
                   "It must use CPUPlace.");
    auto& dev_ctx = ctx.template device_context<MKLDNNDeviceContext>();
    const auto& mkldnn_engine = dev_ctx.GetEngine();

252 253
    auto input = ctx.Input<LoDTensor>("Input");
    auto w = ctx.Input<Tensor>("W");
T
tensor-tang 已提交
254
    auto bias = ctx.Input<Tensor>("Bias");
255
    auto output = ctx.Output<LoDTensor>("Out");
M
mozga-intel 已提交
256

257 258 259 260
    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 已提交
261

262
    output->set_layout(DataLayout::kMKLDNN);
M
mozga-intel 已提交
263 264 265 266 267 268 269
  }
};
}  // namespace operators
}  // namespace paddle

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