MKLDNNLayer.cpp 10.6 KB
Newer Older
T
tensor-tang 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
/* 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. */

#include "MKLDNNLayer.h"

using namespace mkldnn;  // NOLINT
typedef memory::format format;

namespace paddle {

bool MKLDNNLayer::init(const LayerMap& layerMap,
                       const ParameterMap& parameterMap) {
T
tensor-tang 已提交
24
  CHECK(FLAGS_use_mkldnn) << "MKLDNNLayers only support use_mkldnn."
25
                          << "Please set WITH_MKL=ON "
T
tensor-tang 已提交
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
                          << "and set use_mkldnn=True";
  CHECK(!useGpu_) << "Do not support GPU yet";

  // set device id before Layer::init
  setDevice(MKLDNN_DEVICE);
  // change param device to MKLDNN device
  setParamsDevice(MKLDNN_DEVICE, parameterMap);
  if (!Layer::init(layerMap, parameterMap)) {
    return false;
  }
  setOutputMap();
  checkCPUOutputsNumber();

  stream_.reset(new MKLDNNStream());
  engine_ = CPUEngine::Instance().getEngine();
  return true;
}

void MKLDNNLayer::forward(PassType passType) {
  passType_ = passType;

  {
    REGISTER_TIMER_INFO("mkldnn_FwdTimer", getName().c_str());
    CHECK(!inputLayers_.empty());
    copySeqInfoToOutputs();
    size_t elemenCnt = inputLayers_[0]->getOutputValue()->getElementCnt();
    if (inputElemenCnt_ != elemenCnt) {
      VLOG(MKLDNN_BASE) << getName() << " reset mkldnn forward";
      // reset when input total sizes changed, not only the batchsize
      inputElemenCnt_ = elemenCnt;
      reshape(bs_, ic_, ih_, iw_, oc_, oh_, ow_);
57
      printSizeInfo();
58
      // the output_.value and output_.grad are shared with CPU device
T
tensor-tang 已提交
59
      shareCPUDevice();
60 61 62 63 64 65 66

      pipelineFwd_.clear();
      inVals_.resize(inputLayers_.size(), nullptr);
      extInVals_.resize(inputLayers_.size(), nullptr);
      cvtInVals_.resize(inputLayers_.size(), nullptr);
      resetFwd(pipelineFwd_, inVals_, outVal_);
      prepareValueConversions(pipelineFwd_);
T
tensor-tang 已提交
67 68 69 70 71
      convertWeightsFromPaddle();
      printValueFormat();
      needResetBwd_ = true;
    }

72
    if (inputLayers_[0]->getType() == "data" && inputLayers_.size() == 1) {
T
tensor-tang 已提交
73 74
      // Update input value data when input layer is "data" type,
      // since the input value data address might be changed.
75 76
      CHECK(extInVals_[0]);
      extInVals_[0]->setData(getInputValue(0, CPU_DEVICE)->getData());
T
tensor-tang 已提交
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
    }

    if (!outputOnlyMKLDNN_) {
      clearGrads();
    }
    stream_->submit(pipelineFwd_);
  }
  {
    REGISTER_TIMER_INFO("FwActTimer", getName().c_str());
    forwardActivation();
  }
}

void MKLDNNLayer::backward(const UpdateCallback& callback) {
  if (needResetBwd_) {
    VLOG(MKLDNN_BASE) << getName() << " reset mkldnn backward";
    pipelineBwd_.clear();
94 95 96
    inGrads_.resize(inputLayers_.size(), nullptr);
    extInGrads_.resize(inputLayers_.size(), nullptr);
    cvtInGrads_.resize(inputLayers_.size(), nullptr);
T
tensor-tang 已提交
97 98
    pipelineMergeGrad_.clear();
    mergeGrad_ = nullptr;
99 100
    resetBwd(pipelineBwd_, inGrads_, outGrad_);
    prepareGradConversions(pipelineBwd_);
T
tensor-tang 已提交
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
    printGradFormat();
    needResetBwd_ = false;
  }

  // merge grad must before backward activation
  if (mergeGrad_) {
    REGISTER_TIMER_INFO("MergeBpGrad", getName().c_str());
    stream_->submit(pipelineMergeGrad_);
  }
  {
    REGISTER_TIMER_INFO("BpActTimer", getName().c_str());
    backwardActivation();
  }
  {
    REGISTER_TIMER_INFO("mkldnn_bwdTimer", getName().c_str());
    stream_->submit(pipelineBwd_);
  }
  {
    REGISTER_TIMER_INFO("WeightUpdate", getName().c_str());
    updateWeights(callback);
  }
}

124 125 126
void MKLDNNLayer::reshapeInput(int& batchsize,
                               int& height,
                               int& width,
127 128
                               size_t idx) {
  const Argument& input = inputLayers_[idx]->getOutput();
T
tensor-tang 已提交
129 130 131 132 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
  batchsize = input.getBatchSize();
  int h = input.getFrameHeight();
  int w = input.getFrameWidth();
  if (h != 0) {
    height = h;
  }
  if (w != 0) {
    width = w;
  }
}

void MKLDNNLayer::reshapeOutput(size_t height, size_t width) {
  output_.setFrameHeight(height);
  output_.setFrameWidth(width);
  for (size_t i = 0; i < outputOtherDevice_.size(); i++) {
    outputOtherDevice_[i].setFrameHeight(height);
    outputOtherDevice_[i].setFrameWidth(width);
  }
}

void MKLDNNLayer::resetWithMatrix(MKLDNNMatrixPtr& dnn,
                                  const MatrixPtr& mat,
                                  memory::primitive_desc pd) {
  dnn = nullptr;
  if (mat == nullptr) {
    return;
  }
  dnn = MKLDNNMatrix::create(pd, mat);
}

void MKLDNNLayer::resetInValue(
160 161
    MKLDNNMatrixPtr& in,
    const std::shared_ptr<memory::primitive_desc>& intPD,
162
    size_t idx,
163
    int inputChannel) {
164 165
  cvtInVals_[idx] = nullptr;
  extInVals_[idx] = nullptr;
T
tensor-tang 已提交
166
  in = nullptr;
167 168
  inputChannel = inputChannel == 0 ? ic_ : inputChannel;
  CHECK_GT(bs_ * inputChannel * ih_ * iw_, 0);
T
tensor-tang 已提交
169
  auto extPD = MKLDNNMatrix::createPrimitiveDesc(
170
      {bs_, inputChannel, ih_, iw_}, format::nchw, engine_);
171 172 173 174 175 176
  const MatrixPtr& inMat = inputLayers_[idx]->getOutputValue();
  extInVals_[idx] = std::dynamic_pointer_cast<MKLDNNMatrix>(inMat);
  CHECK_EQ(inputIsOnlyMKLDNN(), extInVals_[idx] != nullptr);
  if (extInVals_[idx] == nullptr ||
      extInVals_[idx]->getFormat() == format::nc) {
    extInVals_[idx] = MKLDNNMatrix::create(extPD, inMat);
T
tensor-tang 已提交
177
  }
178
  in = extInVals_[idx];
T
tensor-tang 已提交
179 180 181 182 183
  if (nullptr == intPD || in->getPrimitiveDesc() == *intPD) {
    return;
  }
  // need create reorder
  in = MKLDNNMatrix::create(*intPD);
184 185
  cvtInVals_[idx] = MKLDNNMatrix::createReorder(extInVals_[idx], in);
  CHECK(cvtInVals_[idx]) << "should not be emptry";
T
tensor-tang 已提交
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205
}

void MKLDNNLayer::resetOutValue(MKLDNNMatrixPtr& out,
                                memory::primitive_desc intPD) {
  cvtOutVal_ = nullptr;
  out = MKLDNNMatrix::create(intPD, output_.value);
  extOutVal_ = out;
  if (outputIsOnlyMKLDNN() || isPaddleFormat(extOutVal_->getFormat())) {
    return;
  }
  // need create reorder
  CHECK_GT(bs_ * oc_ * oh_ * ow_, 0);
  extOutVal_ = MKLDNNMatrix::create(
      memory::dims{bs_, oc_, oh_, ow_}, format::nchw, engine_, output_.value);
  out = MKLDNNMatrix::create(intPD);
  cvtOutVal_ = MKLDNNMatrix::createReorder(out, extOutVal_);
  CHECK(cvtOutVal_) << "should not be empty";
}

void MKLDNNLayer::resetInGrad(MKLDNNMatrixPtr& in,
206
                              memory::primitive_desc intPD,
207
                              size_t idx) {
208 209
  cvtInGrads_[idx] = nullptr;
  extInGrads_[idx] = nullptr;
T
tensor-tang 已提交
210
  in = nullptr;
211
  LayerPtr& input = inputLayers_[idx];
T
tensor-tang 已提交
212 213 214 215 216 217 218 219 220 221 222 223 224 225
  if (input->getOutputGrad() == nullptr) {
    // no need input grad
    return;
  }
  CHECK(inputIsOnlyMKLDNN() || input->getOutputMapSize() <= 1)
      << "only support input is MKLDNN layer or only have one output layer";
  // when input is a mkldnn branch node,
  // this layer will save input grad to a internal buffer,
  // and the mkldnn input layer will merge them to actual prev->output_.grad
  const MatrixPtr& inMat =
      input->getOutputMapSize() <= 1 ? input->getOutputGrad() : nullptr;
  in = MKLDNNMatrix::create(intPD, inMat);
  Argument& arg = input->getOutput(this->getName());
  arg.grad = std::dynamic_pointer_cast<Matrix>(in);
226
  CHECK_PRIMITIVE_DESC_EQ(inVals_[idx], intPD);
T
tensor-tang 已提交
227 228 229 230
  if (inputIsOnlyMKLDNN()) {
    return;
  }

231 232
  extInGrads_[idx] = in;
  if (isPaddleFormat(extInGrads_[idx]->getFormat())) {
T
tensor-tang 已提交
233 234 235
    return;
  }
  // need create reorder
236 237
  CHECK(extInVals_[idx] != nullptr &&
        isPaddleFormat(extInVals_[idx]->getFormat()))
T
tensor-tang 已提交
238
      << "should have external input value and the format must be nchw(nc)";
239 240
  extInGrads_[idx] =
      MKLDNNMatrix::create(extInVals_[idx]->getPrimitiveDesc(), inMat);
241
  CHECK_PRIMITIVE_DESC_EQ(inVals_[idx], intPD);
T
tensor-tang 已提交
242
  in = MKLDNNMatrix::create(intPD);
243 244
  cvtInGrads_[idx] = MKLDNNMatrix::createReorder(in, extInGrads_[idx]);
  CHECK(cvtInGrads_[idx]);
T
tensor-tang 已提交
245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
}

void MKLDNNLayer::resetOutGrad(MKLDNNMatrixPtr& out,
                               memory::primitive_desc intPD) {
  cvtOutGrad_ = nullptr;
  extOutGrad_ = nullptr;
  out = nullptr;
  MatrixPtr& outMat = output_.grad;
  out = MKLDNNMatrix::create(intPD, outMat);
  resetMergeGrad(out);
  if (outputIsOnlyMKLDNN()) {
    return;
  }
  CHECK_LE(outputMap_.size(), 1U) << "do not support mixed with cpu device";
  extOutGrad_ = out;
  if (isPaddleFormat(extOutGrad_->getFormat())) {
    return;
  }
  // need create reorder
  CHECK(extOutVal_ != nullptr && isPaddleFormat(extOutVal_->getFormat()))
      << "should have external output value and the format must be nchw(nc)";
  extOutGrad_ = MKLDNNMatrix::create(extOutVal_->getPrimitiveDesc(), outMat);
T
tensor-tang 已提交
267
  CHECK_PRIMITIVE_DESC_EQ(outVal_, intPD);
T
tensor-tang 已提交
268 269 270 271 272 273 274 275 276 277 278 279 280
  out = MKLDNNMatrix::create(intPD);
  cvtOutGrad_ = MKLDNNMatrix::createReorder(extOutGrad_, out);
  CHECK(cvtOutGrad_);
}

void MKLDNNLayer::resetMergeGrad(MKLDNNMatrixPtr& out) {
  mergeGrad_ = nullptr;
  pipelineMergeGrad_.clear();
  if (outputMap_.size() <= 1 || !outputIsOnlyMKLDNN()) {
    // do not merge when output is not all MKLDNN or only one output
    return;
  }
  CHECK(out) << "should have reset internal ouput grad";
T
tensor-tang 已提交
281
  std::vector<float> scales(outputMap_.size(), 1.0);
T
tensor-tang 已提交
282 283 284 285 286 287 288 289 290 291 292 293
  std::vector<memory::primitive_desc> srcPDs;
  std::vector<primitive::at> srcs;
  for (auto it = outputMap_.begin(); it != outputMap_.end(); ++it) {
    MKLDNNMatrixPtr src =
        std::dynamic_pointer_cast<MKLDNNMatrix>(it->second->grad);
    CHECK(src) << "should be MKLDNNMatrix";
    auto srcDims = src->getDims();
    auto dstDims = out->getDims();
    CHECK_EQ(srcDims.size(), dstDims.size());
    for (size_t i = 0; i < srcDims.size(); ++i) {
      CHECK_EQ(srcDims[i], dstDims[i]);
    }
294 295
    VLOG(MKLDNN_BASE) << getName() << " has output grad " << it->first
                      << ", format " << src->getFormat();
T
tensor-tang 已提交
296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
    srcPDs.push_back(src->getPrimitiveDesc());
    srcs.push_back(*src);
  }

  // TODO(TJ): remove me when mkldnn sum support different formats
  for (size_t i = 1; i < srcPDs.size(); ++i) {
    CHECK(srcPDs[0] == srcPDs[i]);
  }
  tmpOutGrad_ = out;
  tmpCvt_ = nullptr;
  if (out->getPrimitiveDesc() != srcPDs[0]) {
    tmpOutGrad_ = MKLDNNMatrix::create(srcPDs[0]);
    tmpCvt_ = MKLDNNMatrix::createReorder(tmpOutGrad_, out);
    CHECK(tmpCvt_);
    pipelineMergeGrad_.push_back(*tmpCvt_);
  }

  auto sumPD =
      sum::primitive_desc(tmpOutGrad_->getMemoryDesc(), scales, srcPDs);
  mergeGrad_.reset(new sum(sumPD, srcs, *tmpOutGrad_));
  pipelineMergeGrad_.insert(pipelineMergeGrad_.begin(), *mergeGrad_);
}

}  // namespace paddle