MKLDNNFcLayer.cpp 10.4 KB
Newer Older
T
tensor-tang 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/* Copyright (c) 2017 PaddlePaddle Authors. All Rights Reserve.

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 "MKLDNNFcLayer.h"
T
tensor-tang 已提交
16
#include "paddle/utils/Logging.h"
T
tensor-tang 已提交
17

T
tensor-tang 已提交
18 19 20
using namespace mkldnn;  // NOLINT
typedef memory::format format;

T
tensor-tang 已提交
21 22
namespace paddle {

23
REGISTER_LAYER(mkldnn_fc, MKLDNNFcLayer);
T
tensor-tang 已提交
24

25
bool MKLDNNFcLayer::init(const LayerMap& layerMap,
T
tensor-tang 已提交
26
                         const ParameterMap& parameterMap) {
27
  if (!MKLDNNLayer::init(layerMap, parameterMap)) {
T
tensor-tang 已提交
28 29 30
    return false;
  }

31
  CHECK_EQ(inputLayers_.size(), 1UL) << "Only support one input layer yet";
T
tensor-tang 已提交
32 33 34 35 36 37 38
  CHECK_EQ(inputLayers_.size(), parameters_.size());
  CHECK(!parameters_[0]->isSparse()) << "Do not support sparse yet";

  // output size, cat not be changed
  oc_ = getSize();
  oh_ = 1;
  ow_ = 1;
39 40
  ih_ = 1;
  iw_ = 1;
T
tensor-tang 已提交
41 42 43 44 45 46 47 48 49 50 51

  // input size can not change in FC
  iLayerSize_ = inputLayers_[0]->getSize();
  CHECK_EQ(parameters_[0]->getSize(), iLayerSize_ * oc_);

  // create weight
  weight_ =
      std::unique_ptr<Weight>(new Weight(oc_, iLayerSize_, parameters_[0], 0));

  // create biases
  if (biasParameter_.get() != NULL) {
T
tensor-tang 已提交
52
    biases_ = std::unique_ptr<Weight>(new Weight(1, oc_, biasParameter_, 0));
T
tensor-tang 已提交
53 54 55 56
  }
  return true;
}

57
void MKLDNNFcLayer::convertWeightsFromPaddle() {
T
tensor-tang 已提交
58
  if (hasInitedWgt_) {
T
tensor-tang 已提交
59 60 61
    return;
  }

T
tensor-tang 已提交
62 63 64 65 66
  CHECK(wgtVal_) << "should have been initialized";
  bool hasNoSpatial_ = ih_ == 1 && iw_ == 1;
  auto targetDim = wgtVal_->getDims();
  auto srcFmt = hasNoSpatial_ ? memory::format::io : memory::format::ihwo;
  wgtVal_->reorderDataFrom(wgtVal_, srcFmt, targetDim);
T
tensor-tang 已提交
67 68 69
  hasInitedWgt_ = true;
}

70
void MKLDNNFcLayer::convertWeightsToPaddle() {
T
tensor-tang 已提交
71 72 73 74 75
  CHECK(wgtVal_) << "should have been initialized";
  bool hasNoSpatial_ = ih_ == 1 && iw_ == 1;
  auto targetDim = wgtVal_->getDims();
  auto dstFmt = hasNoSpatial_ ? memory::format::io : memory::format::ihwo;
  wgtVal_->reorderDataTo(wgtVal_, dstFmt, targetDim);
T
tensor-tang 已提交
76 77
}

78 79 80
void MKLDNNFcLayer::reshape(
    int& bs, int& ic, int& ih, int& iw, int oc, int& oh, int& ow) {
  reshapeInput(bs, ih, iw);
81

T
tensor-tang 已提交
82
  CHECK_EQ(iLayerSize_, inputLayers_[0]->getSize());
83 84 85
  ic = iLayerSize_ / (ih * iw);
  CHECK_EQ(size_t(ic * ih * iw), iLayerSize_) << "not divisible";
  CHECK_EQ(size_t(oc), getSize());
T
tensor-tang 已提交
86

87 88
  reshapeOutput(oh, ow);
  resizeOutput(bs, oc);
T
tensor-tang 已提交
89

90
  printSizeInfo();
T
tensor-tang 已提交
91 92
}

93
void MKLDNNFcLayer::resetFwd(std::vector<primitive>& pipeline,
94 95 96 97
                             MKLDNNMatrixPtr& in,
                             MKLDNNMatrixPtr& wgt,
                             MKLDNNMatrixPtr& bias,
                             MKLDNNMatrixPtr& out) {
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
  resetFwdBuffers(in, wgt, bias, out);

  resetFwdPD(fwdPD_, in, wgt, bias, out);

  resetFwdPipeline(pipeline, fwdPD_, in, wgt, bias, out);

  printValueFormatFlow();
}

void MKLDNNFcLayer::resetBwd(std::vector<primitive>& pipeline,
                             MKLDNNMatrixPtr& in,
                             MKLDNNMatrixPtr& wgt,
                             MKLDNNMatrixPtr& bias,
                             MKLDNNMatrixPtr& out) {
  std::shared_ptr<fc_bwdWgt::primitive_desc> bwdWgtPD;
  std::shared_ptr<fc_bwdData::primitive_desc> bwdDataPD;

  resetBwdBuffers(in, wgt, bias, out);

  resetBwdWgtPD(bwdWgtPD, wgt, bias, out);

  resetBwdDataPD(bwdDataPD, in, out);

  resetBwdPipeline(pipeline, bwdWgtPD, bwdDataPD, in, wgt, bias, out);

  printGradFormatFlow();
}

void MKLDNNFcLayer::updateInputData() {
  inVal_->setData(getInputValue(0, CPU_DEVICE)->getData());
}
T
tensor-tang 已提交
129

130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
void MKLDNNFcLayer::updateWeights(const UpdateCallback& callback) {
  weight_->getParameterPtr()->incUpdate(callback);
  if (biases_ && biases_->getWGrad()) {
    biases_->getParameterPtr()->incUpdate(callback);
  }
}

void MKLDNNFcLayer::resetFwdBuffers(MKLDNNMatrixPtr& in,
                                    MKLDNNMatrixPtr& wgt,
                                    MKLDNNMatrixPtr& bias,
                                    MKLDNNMatrixPtr& out) {
  resetInValue(in);

  resetWgtBiasValue(wgt, bias);

  resetOutValue(out);
}

void MKLDNNFcLayer::resetInValue(MKLDNNMatrixPtr& in) {
T
rename  
tensor-tang 已提交
149
  if (inputIsOnlyMKLDNN()) {
150 151
    const MatrixPtr& dnnIn = getInputValue(0);
    in = std::dynamic_pointer_cast<MKLDNNMatrix>(dnnIn);
152
    CHECK(in) << "Input should be MKLDNNMatrix";
T
tensor-tang 已提交
153
  } else {
154
    CHECK_EQ(getPrev(0)->getDeviceId(), CPU_DEVICE) << "Only support CPU yet";
155
    const MatrixPtr& cpuIn = getInputValue(0, CPU_DEVICE);
156
    in = MKLDNNMatrix::create(
157
        cpuIn, {bs_, ic_, ih_, iw_}, format::nchw, engine_);
T
tensor-tang 已提交
158
  }
159
  in->downSpatial();
160 161 162 163
}

void MKLDNNFcLayer::resetWgtBiasValue(MKLDNNMatrixPtr& wgt,
                                      MKLDNNMatrixPtr& bias) {
T
tensor-tang 已提交
164 165 166 167 168 169
  format wgtFmt = format::oihw;
  if (inVal_->getFormat() == format::nChw8c) {
    wgtFmt = format::oIhw8i;
  } else if (inVal_->getFormat() == format::nChw16c) {
    wgtFmt = format::oIhw16i;
  }
170
  wgt = MKLDNNMatrix::create(
T
tensor-tang 已提交
171
      weight_->getW(), {oc_, ic_, ih_, iw_}, wgtFmt, engine_);
172
  wgt->downSpatial();
T
tensor-tang 已提交
173
  VLOG(MKLDNN_FMTS) << "Weight value format: " << wgt->getFormat();
T
tensor-tang 已提交
174

175 176 177 178 179 180 181
  bias = (biases_ && biases_->getW())
             ? MKLDNNMatrix::create(biases_->getW(), {oc_}, format::x, engine_)
             : nullptr;
}

void MKLDNNFcLayer::resetOutValue(MKLDNNMatrixPtr& out) {
  out = MKLDNNMatrix::create(output_.value, {bs_, oc_}, format::nc, engine_);
T
rename  
tensor-tang 已提交
182
  if (!outputIsOnlyMKLDNN()) {
T
tensor-tang 已提交
183 184
    // fc cpu output value do not need create convert
    // just share point
185
    getOutput(CPU_DEVICE).value->setData(out->getData());
186
  }
187
}
T
tensor-tang 已提交
188

189 190 191 192 193 194 195 196
void MKLDNNFcLayer::resetFwdPD(std::shared_ptr<fc_fwd::primitive_desc>& pd,
                               MKLDNNMatrixPtr in,
                               MKLDNNMatrixPtr wgt,
                               MKLDNNMatrixPtr bias,
                               MKLDNNMatrixPtr out) {
  CHECK(in);
  CHECK(wgt);
  CHECK(out);
T
tensor-tang 已提交
197
  prop_kind pk = prop_kind::forward;
198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218
  fc_fwd::desc fwdDesc = bias != nullptr ? fc_fwd::desc(pk,
                                                        in->getMemoryDesc(),
                                                        wgt->getMemoryDesc(),
                                                        bias->getMemoryDesc(),
                                                        out->getMemoryDesc())
                                         : fc_fwd::desc(pk,
                                                        in->getMemoryDesc(),
                                                        wgt->getMemoryDesc(),
                                                        out->getMemoryDesc());
  pd.reset(new fc_fwd::primitive_desc(fwdDesc, engine_));
}

void MKLDNNFcLayer::resetFwdPipeline(
    std::vector<primitive>& pipeline,
    std::shared_ptr<fc_fwd::primitive_desc>& pd,
    MKLDNNMatrixPtr& in,
    MKLDNNMatrixPtr& wgt,
    MKLDNNMatrixPtr& bias,
    MKLDNNMatrixPtr& out) {
  if (bias) {
    fwd_.reset(new fc_fwd(*pd, *in, *wgt, *bias, *out));
T
tensor-tang 已提交
219
  } else {
220
    fwd_.reset(new fc_fwd(*pd, *in, *wgt, *out));
T
tensor-tang 已提交
221
  }
222

223
  pipeline.push_back(*fwd_);
T
tensor-tang 已提交
224 225
}

226 227 228 229 230 231 232
void MKLDNNFcLayer::resetBwdBuffers(MKLDNNMatrixPtr& in,
                                    MKLDNNMatrixPtr& wgt,
                                    MKLDNNMatrixPtr& bias,
                                    MKLDNNMatrixPtr& out) {
  resetOutGrad(out);

  resetWgtBiasGrad(wgt, bias);
T
tensor-tang 已提交
233

234 235
  resetInGrad(in);
}
T
tensor-tang 已提交
236

237 238
void MKLDNNFcLayer::resetOutGrad(MKLDNNMatrixPtr& out) {
  CHECK(outVal_);
T
tensor-tang 已提交
239 240 241 242 243 244 245
  if (outputIsOnlyMKLDNN()) {
    MKLDNNLayer::resetOutGrad(out, outVal_->getPrimitiveDesc());
  } else {
    const MatrixPtr& cpuOut = getOutput(CPU_DEVICE).grad;
    output_.grad->setData(cpuOut->getData());
    out = MKLDNNMatrix::create(cpuOut, outVal_->getPrimitiveDesc());
  }
246 247 248 249 250 251 252 253 254 255
}

void MKLDNNFcLayer::resetWgtBiasGrad(MKLDNNMatrixPtr& wgt,
                                     MKLDNNMatrixPtr& bias) {
  CHECK(wgtVal_);
  wgt = MKLDNNMatrix::create(weight_->getWGrad(), wgtVal_->getPrimitiveDesc());

  bias = nullptr;
  if (biasVal_ == nullptr) {
    return;
T
tensor-tang 已提交
256
  }
257 258 259
  bias =
      MKLDNNMatrix::create(biases_->getWGrad(), biasVal_->getPrimitiveDesc());
}
T
tensor-tang 已提交
260

261 262
void MKLDNNFcLayer::resetInGrad(MKLDNNMatrixPtr& in) {
  in = nullptr;
T
tensor-tang 已提交
263
  if (inputLayers_[0]->getOutput().grad == nullptr) {
T
refine  
tensor-tang 已提交
264 265
    return;
  }
266
  CHECK(inVal_);
T
tensor-tang 已提交
267
  MKLDNNLayer::resetInGrad(in, inVal_->getPrimitiveDesc());
268
}
T
tensor-tang 已提交
269

270 271 272 273 274 275 276 277 278 279 280 281 282 283
void MKLDNNFcLayer::resetBwdWgtPD(
    std::shared_ptr<fc_bwdWgt::primitive_desc>& pd,
    MKLDNNMatrixPtr& wgt,
    MKLDNNMatrixPtr& bias,
    MKLDNNMatrixPtr& out) {
  CHECK(inVal_);
  fc_bwdWgt::desc bwdWgtDesc = bias ? fc_bwdWgt::desc(inVal_->getMemoryDesc(),
                                                      wgt->getMemoryDesc(),
                                                      bias->getMemoryDesc(),
                                                      out->getMemoryDesc())
                                    : fc_bwdWgt::desc(inVal_->getMemoryDesc(),
                                                      wgt->getMemoryDesc(),
                                                      out->getMemoryDesc());
  pd.reset(new fc_bwdWgt::primitive_desc(bwdWgtDesc, engine_, *fwdPD_));
T
tensor-tang 已提交
284 285
}

286 287 288 289 290 291 292 293 294 295 296 297
void MKLDNNFcLayer::resetBwdDataPD(
    std::shared_ptr<fc_bwdData::primitive_desc>& pd,
    MKLDNNMatrixPtr& in,
    MKLDNNMatrixPtr& out) {
  pd = nullptr;
  if (in == nullptr) {
    return;
  }
  CHECK(wgtVal_);
  fc_bwdData::desc bwdDataDesc = fc_bwdData::desc(
      in->getMemoryDesc(), wgtVal_->getMemoryDesc(), out->getMemoryDesc());
  pd.reset(new fc_bwdData::primitive_desc(bwdDataDesc, engine_, *fwdPD_));
T
tensor-tang 已提交
298 299
}

300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317
void MKLDNNFcLayer::resetBwdPipeline(
    std::vector<primitive>& pipeline,
    std::shared_ptr<fc_bwdWgt::primitive_desc>& bwdWgtPD,
    std::shared_ptr<fc_bwdData::primitive_desc>& bwdDataPD,
    MKLDNNMatrixPtr& in,
    MKLDNNMatrixPtr& wgt,
    MKLDNNMatrixPtr& bias,
    MKLDNNMatrixPtr& out) {
  CHECK(inVal_);
  if (bias) {
    bwdWgt_.reset(new fc_bwdWgt(*bwdWgtPD, *inVal_, *out, *wgt, *bias));
  } else {
    bwdWgt_.reset(new fc_bwdWgt(*bwdWgtPD, *inVal_, *out, *wgt));
  }
  pipeline.push_back(*bwdWgt_);

  if (bwdDataPD == nullptr) {
    return;
T
tensor-tang 已提交
318
  }
319 320 321
  CHECK(wgtVal_) << "Should have weight memory";
  bwdData_.reset(new fc_bwdData(*bwdDataPD, *out, *wgtVal_, *in));
  pipeline.push_back(*bwdData_);
T
tensor-tang 已提交
322
}
323

T
tensor-tang 已提交
324
}  // namespace paddle