MKLDNNFcLayer.cpp 9.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
#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
  // TODO(TJ): dst format should get from wgtVal_
  int dstFmt = PARAM_FORMAT_MKLDNN_OI;
  int srcFmt = weight_->getParameterPtr()->getHeaderFormat();
  if (srcFmt == dstFmt) {
T
tensor-tang 已提交
68 69 70
    return;
  }

T
tensor-tang 已提交
71 72 73 74
  // The weight_ is transposed from initial paddle weight
  MatrixPtr paddleWgt = Matrix::create(
      weight_->getW()->getData(), iLayerSize_, oc_, false, false);

T
tensor-tang 已提交
75
  // TODO(TJ): remove this print when do not need differ weights
T
tensor-tang 已提交
76 77
  std::ostringstream ostr;
  paddleWgt->print(ostr);
T
tensor-tang 已提交
78
  VLOG(MKLDNN_ALL) << "Initial Weight from paddle: " << std::endl << ostr.str();
T
tensor-tang 已提交
79

T
tensor-tang 已提交
80
  // The mkldnn weight is transposed from initial paddle matrix
T
tensor-tang 已提交
81 82 83
  MatrixPtr paddleWgtT;
  paddleWgt->transpose(paddleWgtT, true);
  weight_->getW()->copyFrom(*paddleWgtT);
T
tensor-tang 已提交
84
  weight_->getParameterPtr()->setHeaderFormat(dstFmt);
T
tensor-tang 已提交
85 86 87
  hasInitedWgt_ = true;
}

88
void MKLDNNFcLayer::convertWeightsToPaddle() {
T
tensor-tang 已提交
89 90 91 92 93 94 95 96
  MatrixPtr dnnWgt = weight_->getW();
  MatrixPtr paddleWgt;
  dnnWgt->transpose(paddleWgt, true);

  // copy paddle weight and override on weight_
  MatrixPtr dnnWgtT = Matrix::create(
      dnnWgt->getData(), dnnWgt->getWidth(), dnnWgt->getHeight(), false, false);
  dnnWgtT->copyFrom(*paddleWgt);
T
tensor-tang 已提交
97 98
}

99
void MKLDNNFcLayer::reshape() {
T
tensor-tang 已提交
100 101 102 103 104 105 106 107 108 109 110 111 112 113
  const Argument& input = getInput(0);
  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;
  }
T
tensor-tang 已提交
114 115 116 117
  hasSpatial_ = true;
  if (ih_ == 1 && iw_ == 1) {
    hasSpatial_ = false;
  }
T
tensor-tang 已提交
118 119 120 121
  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 已提交
122
  printSizeInfo();
T
tensor-tang 已提交
123 124 125 126 127

  // reset output
  output_.setFrameHeight(oh_);
  output_.setFrameWidth(ow_);
  resetOutput(bs_, oc_);
T
tensor-tang 已提交
128 129 130 131 132 133 134 135

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

  convertWeightsFromPaddle();
}

136
void MKLDNNFcLayer::resetFwd() {
T
tensor-tang 已提交
137
  bool hasBias = biases_ && biases_->getW();
T
tensor-tang 已提交
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154
  const MatrixPtr& in = getInputValue(0);
  const MatrixPtr& wgt = weight_->getW();
  const MatrixPtr& bias = hasBias ? biases_->getW() : nullptr;
  const MatrixPtr& out = output_.value;

  if (getPrev(0)->getDeviceId() == MKLDNN_DEVICE) {
    inVal_ = std::dynamic_pointer_cast<MKLDNNMatrix>(in);
    CHECK(inVal_) << "Input should be MKLDNNMatrix";
    // TODO:  change input nchw to nc if available
    // inVal_->downSpatial()
  } else {
    inVal_ = MKLDNNMatrix::create(
        in,
        hasSpatial_ ? memory::dims{bs_, ic_, ih_, iw_} : memory::dims{bs_, ic_},
        hasSpatial_ ? format::nchw : format::nc,
        engine_);
  }
T
tensor-tang 已提交
155

T
tensor-tang 已提交
156 157 158 159 160
  wgtVal_ = MKLDNNMatrix::create(
      wgt,
      hasSpatial_ ? memory::dims{oc_, ic_, ih_, iw_} : memory::dims{oc_, ic_},
      hasSpatial_ ? format::oihw : format::oi,
      engine_);
T
tensor-tang 已提交
161

T
tensor-tang 已提交
162 163 164 165 166 167 168
  biasVal_ =
      hasBias ? MKLDNNMatrix::create(bias, {oc_}, format::x, engine_) : nullptr;

  outVal_ = MKLDNNMatrix::create(out, {bs_, oc_}, format::nc, engine_);

  // change original output to mkldnn output
  output_.value = std::dynamic_pointer_cast<Matrix>(outVal_);
T
tensor-tang 已提交
169

T
tensor-tang 已提交
170
  // create forward handle
T
tensor-tang 已提交
171
  prop_kind pk = prop_kind::forward;
T
tensor-tang 已提交
172 173 174 175 176 177 178 179
  fc_fwd::desc fwdDesc =
      hasBias ? fc_fwd::desc(pk,
                             inVal_->getMD(),
                             wgtVal_->getMD(),
                             biasVal_->getMD(),
                             outVal_->getMD())
              : fc_fwd::desc(
                    pk, inVal_->getMD(), wgtVal_->getMD(), outVal_->getMD());
T
tensor-tang 已提交
180 181
  fc_fwd::primitive_desc fwdPD = fc_fwd::primitive_desc(fwdDesc, engine_);

T
tensor-tang 已提交
182
  if (hasBias) {
T
tensor-tang 已提交
183 184 185 186 187 188 189 190
    fwd_.reset(new fc_fwd(fwdPD, *inVal_, *wgtVal_, *biasVal_, *outVal_));
  } else {
    fwd_.reset(new fc_fwd(fwdPD, *inVal_, *wgtVal_, *outVal_));
  }
  pipelineFwd_.clear();
  pipelineFwd_.push_back(*fwd_);
}

191
void MKLDNNFcLayer::resetBwd() {
T
tensor-tang 已提交
192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217
  if (!needResetBwd_) {
    return;
  }
  needResetBwd_ = false;

  bool hasBias = biases_ && biases_->getWGrad();
  real* iData = getInputValue(0)->getData();
  real* iDiff = getInputGrad(0) != nullptr ? getInputGrad(0)->getData() : NULL;
  real* oDiff = getOutputGrad()->getData();
  real* wDiff = weight_->getWGrad()->getData();
  real* bDiff = hasBias ? biases_->getWGrad()->getData() : NULL;

  /// backward weight
  // create memory desc for backward memory
  memory::desc iMD = hasSpatial_ ? createMD({bs_, ic_, ih_, iw_}, format::nchw)
                                 : createMD({bs_, ic_}, format::nc);
  memory::desc wMD = hasSpatial_ ? createMD({oc_, ic_, ih_, iw_}, format::oihw)
                                 : createMD({oc_, ic_}, format::oi);
  memory::desc oMD = createMD({bs_, oc_}, format::nc);
  memory::desc bMD = bDiff != NULL ? createMD({oc_}, format::x)
                                   : createMD({}, format::format_undef);

  if (inVal_) {
    // update data
    inVal_->set_data_handle(iData);
  } else {
T
tensor-tang 已提交
218 219
    LOG(FATAL) << "Should not be empty";
    // inVal_.reset(new memory(memory::primitive_desc(iMD, engine_), iData));
T
tensor-tang 已提交
220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254
  }

  // create memory primitive desc and memory self
  wgtGrad_.reset(new memory(memory::primitive_desc(wMD, engine_), wDiff));
  outGrad_.reset(new memory(memory::primitive_desc(oMD, engine_), oDiff));

  fc_fwd::desc fwdDesc = fc_fwd::desc(prop_kind::forward, iMD, wMD, oMD);
  fc_fwd::primitive_desc fwdPD = fc_fwd::primitive_desc(fwdDesc, engine_);
  fc_bwdWgt::desc bwdWgtDesc = bDiff != NULL
                                   ? fc_bwdWgt::desc(iMD, wMD, bMD, oMD)
                                   : fc_bwdWgt::desc(iMD, wMD, oMD);
  fc_bwdWgt::primitive_desc bwdWgtPD =
      fc_bwdWgt::primitive_desc(bwdWgtDesc, engine_, fwdPD);

  if (bDiff != NULL) {
    biasGrad_.reset(new memory(memory::primitive_desc(bMD, engine_), bDiff));
    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
  if (iDiff == NULL) {
    return;
  }
  fc_bwdData::desc bwdDataDesc = fc_bwdData::desc(iMD, wMD, oMD);
  fc_bwdData::primitive_desc bwdDataPD =
      fc_bwdData::primitive_desc(bwdDataDesc, engine_, fwdPD);
  inGrad_.reset(new memory(memory::primitive_desc(iMD, engine_), iDiff));
  CHECK(wgtVal_) << "Should have weight memory";
  bwdData_.reset(new fc_bwdData(bwdDataPD, *outGrad_, *wgtVal_, *inGrad_));
  pipelineBwd_.push_back(*bwdData_);
T
tensor-tang 已提交
255 256
}

257
void MKLDNNFcLayer::forward(PassType passType) {
T
tensor-tang 已提交
258 259
  Layer::forward(passType);
  reshape();
T
tensor-tang 已提交
260

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

    // update input data
    // since it might be changed if this is after data layer
    real* iData = getInputValue(0)->getData();
    inVal_->set_data_handle(iData);

    // 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 289 290 291 292 293 294
    resetBwd();

    // update diff
    real* oDiff = getOutputGrad()->getData();
    outGrad_->set_data_handle(oDiff);

    // just sumbmit backward pipeline
    stream_->submit(pipelineBwd_);
T
tensor-tang 已提交
295 296 297 298 299
  }

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