MKLDNNFcLayer.cpp 10.0 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
#include "paddle/utils/Stat.h"
T
tensor-tang 已提交
18

T
tensor-tang 已提交
19 20 21 22 23 24
using namespace mkldnn;  // NOLINT
typedef memory::format format;
typedef inner_product_forward fc_fwd;
typedef inner_product_backward_weights fc_bwdWgt;
typedef inner_product_backward_data fc_bwdData;

T
tensor-tang 已提交
25 26
namespace paddle {

27
REGISTER_LAYER(mkldnn_fc, MKLDNNFcLayer);
T
tensor-tang 已提交
28

29
bool MKLDNNFcLayer::init(const LayerMap& layerMap,
T
tensor-tang 已提交
30
                         const ParameterMap& parameterMap) {
31
  if (!MKLDNNLayer::init(layerMap, parameterMap)) {
T
tensor-tang 已提交
32 33 34
    return false;
  }

T
tensor-tang 已提交
35
  CHECK_EQ(inputLayers_.size(), 1) << "Only support one input layer yet";
T
tensor-tang 已提交
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
  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;

  // 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) {
    biases_ = std::unique_ptr<Weight>(new Weight(1, oc_, biasParameter_));
  }
  return true;
}

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

T
tensor-tang 已提交
64 65 66 67 68
  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 已提交
69 70 71
  hasInitedWgt_ = true;
}

72
void MKLDNNFcLayer::convertWeightsToPaddle() {
T
tensor-tang 已提交
73 74 75 76 77
  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 已提交
78 79
}

T
refine  
tensor-tang 已提交
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
void MKLDNNFcLayer::convertOutputToOtherDevice() {
  copyOutputInfoToOtherDevice();
  // find other cpu device and reorder output to cpu device
  int cnt = 0;
  for (size_t i = 0; i < outputOtherDevice_.size(); i++) {
    if (outputOtherDevice_[i].deviceId == CPU_DEVICE) {
      // fc cpu output value do not need convert
      // just share point
      outputOtherDevice_[i].value = output_.value;
      ++cnt;
    }
  }

  if (cnt > 1) {
    LOG(WARNING) << "should not have more than one CPU devie";
  }
}

98
void MKLDNNFcLayer::reshape() {
99
  const Argument& input = getInput(0, getPrev(0)->getDeviceId());
T
tensor-tang 已提交
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
  int batchSize = input.getBatchSize();
  if (bs_ == batchSize) {
    return;
  }
  bs_ = batchSize;
  ih_ = input.getFrameHeight();
  iw_ = input.getFrameWidth();
  if (ih_ == 0) {
    ih_ = 1;
  }
  if (iw_ == 0) {
    iw_ = 1;
  }
  CHECK_EQ(iLayerSize_, inputLayers_[0]->getSize());
  ic_ = iLayerSize_ / (ih_ * iw_);
  CHECK_EQ(size_t(ic_ * ih_ * iw_), iLayerSize_) << "not divisible";
  CHECK_EQ(size_t(oc_), getSize());
T
tensor-tang 已提交
117
  printSizeInfo();
T
tensor-tang 已提交
118 119 120 121 122

  // reset output
  output_.setFrameHeight(oh_);
  output_.setFrameWidth(ow_);
  resetOutput(bs_, oc_);
T
tensor-tang 已提交
123 124 125 126 127 128 129 130

  // reset mkldnn forward
  resetFwd();
  needResetBwd_ = true;

  convertWeightsFromPaddle();
}

131
void MKLDNNFcLayer::resetFwd() {
T
tensor-tang 已提交
132
  bool hasBias = biases_ && biases_->getW();
T
tensor-tang 已提交
133 134 135 136
  const MatrixPtr& wgt = weight_->getW();
  const MatrixPtr& bias = hasBias ? biases_->getW() : nullptr;
  const MatrixPtr& out = output_.value;

T
rename  
tensor-tang 已提交
137
  if (inputIsOnlyMKLDNN()) {
138
    const MatrixPtr& in = getInputValue(0);
T
tensor-tang 已提交
139 140 141
    inVal_ = std::dynamic_pointer_cast<MKLDNNMatrix>(in);
    CHECK(inVal_) << "Input should be MKLDNNMatrix";
  } else {
142 143
    CHECK_EQ(getPrev(0)->getDeviceId(), CPU_DEVICE) << "Only support CPU yet";
    const MatrixPtr& in = getInputValue(0, CPU_DEVICE);
T
tensor-tang 已提交
144
    inVal_ = MKLDNNMatrix::create(
145
        in, memory::dims{bs_, ic_, ih_, iw_}, format::nchw, engine_);
T
tensor-tang 已提交
146
  }
147
  inVal_->downSpatial();
T
tensor-tang 已提交
148
  wgtVal_ = MKLDNNMatrix::create(
149 150
      wgt, memory::dims{oc_, ic_, ih_, iw_}, format::oihw, engine_);
  wgtVal_->downSpatial();
T
tensor-tang 已提交
151 152 153 154
  biasVal_ =
      hasBias ? MKLDNNMatrix::create(bias, {oc_}, format::x, engine_) : nullptr;
  outVal_ = MKLDNNMatrix::create(out, {bs_, oc_}, format::nc, engine_);

155
  // change original output value to mkldnn output value
T
tensor-tang 已提交
156
  output_.value = std::dynamic_pointer_cast<Matrix>(outVal_);
T
rename  
tensor-tang 已提交
157
  if (!outputIsOnlyMKLDNN()) {
T
refine  
tensor-tang 已提交
158
    convertOutputToOtherDevice();
159
  }
T
tensor-tang 已提交
160

T
tensor-tang 已提交
161
  // create forward handle
T
tensor-tang 已提交
162
  prop_kind pk = prop_kind::forward;
T
refine  
tensor-tang 已提交
163 164 165 166 167 168 169 170 171
  fc_fwd::desc fwdDesc = hasBias ? fc_fwd::desc(pk,
                                                inVal_->getMemoryDesc(),
                                                wgtVal_->getMemoryDesc(),
                                                biasVal_->getMemoryDesc(),
                                                outVal_->getMemoryDesc())
                                 : fc_fwd::desc(pk,
                                                inVal_->getMemoryDesc(),
                                                wgtVal_->getMemoryDesc(),
                                                outVal_->getMemoryDesc());
T
tensor-tang 已提交
172
  fc_fwd::primitive_desc fwdPD = fc_fwd::primitive_desc(fwdDesc, engine_);
T
tensor-tang 已提交
173
  if (hasBias) {
T
tensor-tang 已提交
174 175 176 177
    fwd_.reset(new fc_fwd(fwdPD, *inVal_, *wgtVal_, *biasVal_, *outVal_));
  } else {
    fwd_.reset(new fc_fwd(fwdPD, *inVal_, *wgtVal_, *outVal_));
  }
178 179
  printValueFormatFlow();

T
tensor-tang 已提交
180 181 182 183
  pipelineFwd_.clear();
  pipelineFwd_.push_back(*fwd_);
}

184
void MKLDNNFcLayer::resetBwd() {
T
tensor-tang 已提交
185 186 187 188 189 190 191
  if (!needResetBwd_) {
    return;
  }
  needResetBwd_ = false;
  bool hasBias = biases_ && biases_->getWGrad();

  /// backward weight
T
tensor-tang 已提交
192 193 194 195
  CHECK(inVal_) << "Should have input value";
  const MatrixPtr& wgt = weight_->getWGrad();
  const MatrixPtr& bias = hasBias ? biases_->getWGrad() : nullptr;

T
refine  
tensor-tang 已提交
196
  // TODO(TJ): merge outgrad
T
rename  
tensor-tang 已提交
197 198 199 200 201 202 203 204 205 206
  int device = outputIsOnlyMKLDNN() ? MKLDNN_DEVICE : CPU_DEVICE;
  // for MKLDNN device:
  // can not directly cast outputgrad to mkldnnmatrix,
  // since each layer can not write the inputgrad to mkldnn inputgrad.
  // So just create from matrix with outputvalue format.
  // for CPU device:
  // fc do not need to convert from cpu device since output is always nc format
  // only need create from cpu device
  const MatrixPtr& out = getOutput(device).grad;
  outGrad_ = MKLDNNMatrix::create(out, outVal_->getPrimitiveDesc());
T
refine  
tensor-tang 已提交
207 208 209
  wgtGrad_ = MKLDNNMatrix::create(wgt, wgtVal_->getPrimitiveDesc());
  biasGrad_ = hasBias ? MKLDNNMatrix::create(bias, biasVal_->getPrimitiveDesc())
                      : nullptr;
T
tensor-tang 已提交
210 211 212

  // create memory primitive desc
  fc_fwd::desc fwdDesc = fc_fwd::desc(prop_kind::forward,
T
refine  
tensor-tang 已提交
213 214 215
                                      inVal_->getMemoryDesc(),
                                      wgtGrad_->getMemoryDesc(),
                                      outGrad_->getMemoryDesc());
T
tensor-tang 已提交
216
  fc_fwd::primitive_desc fwdPD = fc_fwd::primitive_desc(fwdDesc, engine_);
T
refine  
tensor-tang 已提交
217 218 219 220 221 222 223 224
  fc_bwdWgt::desc bwdWgtDesc = hasBias
                                   ? fc_bwdWgt::desc(inVal_->getMemoryDesc(),
                                                     wgtGrad_->getMemoryDesc(),
                                                     biasGrad_->getMemoryDesc(),
                                                     outGrad_->getMemoryDesc())
                                   : fc_bwdWgt::desc(inVal_->getMemoryDesc(),
                                                     wgtGrad_->getMemoryDesc(),
                                                     outGrad_->getMemoryDesc());
T
tensor-tang 已提交
225 226 227
  fc_bwdWgt::primitive_desc bwdWgtPD =
      fc_bwdWgt::primitive_desc(bwdWgtDesc, engine_, fwdPD);

T
tensor-tang 已提交
228
  if (hasBias) {
T
tensor-tang 已提交
229 230 231 232 233 234 235 236 237
    bwdWgt_.reset(
        new fc_bwdWgt(bwdWgtPD, *inVal_, *outGrad_, *wgtGrad_, *biasGrad_));
  } else {
    bwdWgt_.reset(new fc_bwdWgt(bwdWgtPD, *inVal_, *outGrad_, *wgtGrad_));
  }
  pipelineBwd_.clear();
  pipelineBwd_.push_back(*bwdWgt_);

  /// backward data
T
rename  
tensor-tang 已提交
238
  device = inputIsOnlyMKLDNN() ? MKLDNN_DEVICE : CPU_DEVICE;
T
refine  
tensor-tang 已提交
239 240 241 242 243 244
  const MatrixPtr& in = getInputGrad(0, device);
  if (in == nullptr) {
    return;
  }
  if (getInput(0, device).getAllCount() > 1) {
    // TODO(TJ): use outputMaps_ ways when merge outgrad done
245
  } else {
T
refine  
tensor-tang 已提交
246
    inGrad_ = MKLDNNMatrix::create(in, inVal_->getPrimitiveDesc());
T
tensor-tang 已提交
247
  }
248

T
refine  
tensor-tang 已提交
249 250 251
  fc_bwdData::desc bwdDataDesc = fc_bwdData::desc(inVal_->getMemoryDesc(),
                                                  wgtGrad_->getMemoryDesc(),
                                                  outGrad_->getMemoryDesc());
T
tensor-tang 已提交
252 253
  fc_bwdData::primitive_desc bwdDataPD =
      fc_bwdData::primitive_desc(bwdDataDesc, engine_, fwdPD);
T
tensor-tang 已提交
254

T
tensor-tang 已提交
255 256
  CHECK(wgtVal_) << "Should have weight memory";
  bwdData_.reset(new fc_bwdData(bwdDataPD, *outGrad_, *wgtVal_, *inGrad_));
257
  printGradFormatFlow();
T
tensor-tang 已提交
258
  pipelineBwd_.push_back(*bwdData_);
T
tensor-tang 已提交
259 260
}

261
void MKLDNNFcLayer::forward(PassType passType) {
T
tensor-tang 已提交
262 263
  Layer::forward(passType);
  reshape();
T
tensor-tang 已提交
264

T
tensor-tang 已提交
265 266
  {
    REGISTER_TIMER_INFO("mkldnn_FwdTimer", getName().c_str());
267
    syncInputValue();
T
tensor-tang 已提交
268 269 270

    // just submit forward pipeline
    stream_->submit(pipelineFwd_);
T
tensor-tang 已提交
271
  }
T
tensor-tang 已提交
272

T
tensor-tang 已提交
273 274 275 276 277 278
  /* activation */ {
    REGISTER_TIMER_INFO("FwActTimer", getName().c_str());
    forwardActivation();
  }
}

279
void MKLDNNFcLayer::backward(const UpdateCallback& callback) {
T
tensor-tang 已提交
280 281 282 283 284 285 286
  /* Do derivation */ {
    REGISTER_TIMER_INFO("BpActTimer", getName().c_str());
    backwardActivation();
  }

  {
    REGISTER_TIMER_INFO("mkldnn_bwdTimer", getName().c_str());
T
tensor-tang 已提交
287 288
    resetBwd();

289
    syncOutputGrad();
T
tensor-tang 已提交
290 291
    // just sumbmit backward pipeline
    stream_->submit(pipelineBwd_);
T
tensor-tang 已提交
292 293 294 295 296
  }

  {
    REGISTER_TIMER_INFO("WeightUpdate", getName().c_str());
    weight_->getParameterPtr()->incUpdate(callback);
T
tensor-tang 已提交
297
    if (biases_ && biases_->getWGrad()) {
T
tensor-tang 已提交
298 299 300
      biases_->getParameterPtr()->incUpdate(callback);
    }
  }
T
tensor-tang 已提交
301
}
T
tensor-tang 已提交
302
}  // namespace paddle