MKLDNNConvLayer.cpp 19.4 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 24 25 26 27 28 29 30
/* 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 "MKLDNNConvLayer.h"
#include "paddle/math/MathUtils.h"
#include "paddle/utils/Logging.h"

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

namespace paddle {

REGISTER_LAYER(mkldnn_conv, MKLDNNConvLayer);

bool MKLDNNConvLayer::init(const LayerMap& layerMap,
                           const ParameterMap& parameterMap) {
  if (!MKLDNNLayer::init(layerMap, parameterMap)) {
    return false;
  }
31
  CHECK_EQ(inputLayers_.size(), 1UL) << "Only support one input layer yet";
T
tensor-tang 已提交
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
  CHECK_EQ(inputLayers_.size(), parameters_.size());
  CHECK(config_.shared_biases()) << "Only support shared biases yet";

  oc_ = config_.num_filters();
  const ConvConfig& conf = config_.inputs(0).conv_conf();
  ic_ = conf.channels();
  fw_ = conf.filter_size();
  fh_ = conf.filter_size_y();
  pw_ = conf.padding();
  ph_ = conf.padding_y();
  dw_ = conf.dilation();
  dh_ = conf.dilation_y();
  sw_ = conf.stride();
  sh_ = conf.stride_y();
  gp_ = conf.groups();
47
  oh_ = conf.output_y();
T
tensor-tang 已提交
48
  ow_ = conf.output_x();
49
  ih_ = conf.img_size_y();
T
tensor-tang 已提交
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
  iw_ = conf.img_size();
  caffeMode_ = conf.caffe_mode();
  CHECK(caffeMode_) << "Only support caffe mode yet";
  CHECK(dh_ == 1 && dw_ == 1) << "Only support dilation 1 yet";
  // check group setting
  CHECK_EQ((oc_ / gp_) * gp_, oc_) << "group is indivisible for oc";
  CHECK_EQ((ic_ / gp_) * gp_, ic_) << "group is indivisible for ic";

  // create weight
  size_t height = oc_ / gp_;
  size_t width = ic_ * fh_ * fw_;
  CHECK_EQ(parameters_[0]->getSize(), height * width);
  weight_ =
      std::unique_ptr<Weight>(new Weight(height, width, parameters_[0], 0));

  // create biases
  if (biasParameter_.get() != NULL) {
T
tensor-tang 已提交
67
    biases_ = std::unique_ptr<Weight>(new Weight(1, oc_, biasParameter_, 0));
T
tensor-tang 已提交
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
  }
  return true;
}

void MKLDNNConvLayer::convertWeightsFromPaddle() {
  if (hasInitedWgt_) {
    return;
  }

  CHECK(wgtVal_) << "should have been initialized";
  // the paddle weight format is oihw or goihw
  auto targetDim = wgtVal_->getDims();
  auto srcFmt = (gp_ == 1) ? memory::format::oihw : memory::format::goihw;
  wgtVal_->reorderDataFrom(wgtVal_, srcFmt, targetDim);
  hasInitedWgt_ = true;
}

void MKLDNNConvLayer::convertWeightsToPaddle() {
  CHECK(wgtVal_) << "should have been initialized";
  auto targetDim = wgtVal_->getDims();
  auto dstFmt = (gp_ == 1) ? memory::format::oihw : memory::format::goihw;
  wgtVal_->reorderDataTo(wgtVal_, dstFmt, targetDim);
}

void MKLDNNConvLayer::reshape(
    int& bs, int& ic, int& ih, int& iw, int oc, int& oh, int& ow) {
  reshapeInput(bs, ih, iw);

  // cal output sizes
  // oc can not be changed
  int fh = (fh_ - 1) * dh_ + 1;
  int fw = (fw_ - 1) * dw_ + 1;
  oh = outputSize(ih, fh, ph_, sh_, caffeMode_);
  ow = outputSize(iw, fw, pw_, sw_, caffeMode_);

  reshapeOutput(oh, ow);
  resizeOutput(bs, oc * oh * ow);

  printSizeInfo();
}

void MKLDNNConvLayer::resetFwd(std::vector<primitive>& pipeline,
                               MKLDNNMatrixPtr& in,
                               MKLDNNMatrixPtr& wgt,
                               MKLDNNMatrixPtr& bias,
                               MKLDNNMatrixPtr& out) {
114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
  resetFwdPD(fwdPD_);

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

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

  printValueFormatFlow();
}

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

  resetBwdWgtPD(bwdWgtPD);

  resetBwdDataPD(bwdDataPD);

  resetBwdBuffers(bwdWgtPD, bwdDataPD, in, wgt, bias, out);
T
tensor-tang 已提交
136

137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
  resetBwdPipeline(pipeline, bwdWgtPD, bwdDataPD, in, wgt, bias, out);

  printGradFormatFlow();
}

void MKLDNNConvLayer::updateInputData() {
  cpuInVal_->setData(getInputValue(0, CPU_DEVICE)->getData());
}

void MKLDNNConvLayer::updateWeights(const UpdateCallback& callback) {
  weight_->getParameterPtr()->incUpdate(callback);
  if (biases_ && biases_->getWGrad()) {
    biases_->getParameterPtr()->incUpdate(callback);
  }
}

void MKLDNNConvLayer::loadConvSettings(memory::dims& wgt,
                                       memory::dims& bias,
                                       memory::dims& stride,
                                       memory::dims& dilation,
                                       memory::dims& padL,
                                       memory::dims& padR) {
  wgt = (gp_ == 1) ? memory::dims{oc_, ic_, fh_, fw_}
                   : memory::dims{gp_, oc_ / gp_, ic_ / gp_, fh_, fw_};
  bias = memory::dims{oc_};
  stride = memory::dims{sh_, sw_};
  padL = memory::dims{ph_, pw_};
  padR = getPaddingR();
  // note: mkldnn dilation start from 0
  dilation = memory::dims{dh_ - 1, dw_ - 1};
}

void MKLDNNConvLayer::resetFwdPD(
    std::shared_ptr<conv_fwd::primitive_desc>& pd) {
T
tensor-tang 已提交
171 172 173
  // dims for conv
  memory::dims inDims = memory::dims{bs_, ic_, ih_, iw_};
  memory::dims outDims = memory::dims{bs_, oc_, oh_, ow_};
174 175
  memory::dims wgtDims, biasDims, strides, dilations, padL, padR;
  loadConvSettings(wgtDims, biasDims, strides, dilations, padL, padR);
T
tensor-tang 已提交
176

177 178
  prop_kind pk = passType_ == PASS_TEST ? prop_kind::forward_scoring
                                        : prop_kind::forward_training;
T
tensor-tang 已提交
179 180 181
  algorithm algo = algorithm::convolution_direct;
  padding_kind padKind = padding_kind::zero;
  conv_fwd::desc fwdDesc =
182 183 184 185 186 187 188 189 190 191 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 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235
      biases_ && biases_->getW()
          ? conv_fwd::desc(pk,
                           algo,
                           MKLDNNMatrix::createMemoryDesc(inDims),
                           MKLDNNMatrix::createMemoryDesc(wgtDims),
                           MKLDNNMatrix::createMemoryDesc(biasDims),
                           MKLDNNMatrix::createMemoryDesc(outDims),
                           strides,
                           dilations,
                           padL,
                           padR,
                           padKind)
          : conv_fwd::desc(pk,
                           algo,
                           MKLDNNMatrix::createMemoryDesc(inDims),
                           MKLDNNMatrix::createMemoryDesc(wgtDims),
                           MKLDNNMatrix::createMemoryDesc(outDims),
                           strides,
                           dilations,
                           padL,
                           padR,
                           padKind);
  pd.reset(new conv_fwd::primitive_desc(fwdDesc, engine_));
}

void MKLDNNConvLayer::resetFwdBuffers(
    std::shared_ptr<conv_fwd::primitive_desc>& pd,
    MKLDNNMatrixPtr& in,
    MKLDNNMatrixPtr& wgt,
    MKLDNNMatrixPtr& bias,
    MKLDNNMatrixPtr& out) {
  CHECK(pd);
  resetInValue(pd, in);

  resetWgtBiasValue(pd, wgt, bias);

  resetOutValue(pd, out);
}

void MKLDNNConvLayer::resetFwdPipeline(
    std::vector<primitive>& pipeline,
    std::shared_ptr<conv_fwd::primitive_desc>& pd,
    MKLDNNMatrixPtr& in,
    MKLDNNMatrixPtr& wgt,
    MKLDNNMatrixPtr& bias,
    MKLDNNMatrixPtr& out) {
  if (cvtInVal_) {
    pipeline.push_back(*cvtInVal_);
  }

  if (bias) {
    fwd_.reset(new conv_fwd(*pd, *in, *wgt, *bias, *out));
  } else {
    fwd_.reset(new conv_fwd(*pd, *in, *wgt, *out));
T
tensor-tang 已提交
236
  }
237 238 239 240 241 242
  pipeline.push_back(*fwd_);

  if (cvtOutVal_) {
    pipeline.push_back(*cvtOutVal_);
  }
}
T
tensor-tang 已提交
243

244 245
void MKLDNNConvLayer::resetInValue(
    std::shared_ptr<conv_fwd::primitive_desc>& pd, MKLDNNMatrixPtr& in) {
246
  const MatrixPtr& inMat = inputLayers_[0]->getOutputValue();
247 248 249 250 251
  in = MKLDNNMatrix::create(inMat, pd->src_primitive_desc());

  // create buffer and reorder if input value do not match
  cpuInVal_ = nullptr;
  cvtInVal_ = nullptr;
252 253 254 255 256 257 258 259 260

  MKLDNNMatrixPtr dnnIn = std::dynamic_pointer_cast<MKLDNNMatrix>(inMat);
  CHECK_EQ(inputIsOnlyMKLDNN(), dnnIn != nullptr);
  if (dnnIn != nullptr && dnnIn->getPrimitiveDesc() == in->getPrimitiveDesc()) {
    in = dnnIn;
    return;
  }
  if (dnnIn) {
    if (dnnIn->getFormat() == format::nc) {
261 262 263 264
      CHECK(ih_ == 1 && iw_ == 1) << "when input is nc format";
      // create a new one with nchw format and same data
      memory::dims inDims = memory::dims{bs_, ic_, 1, 1};
      dnnIn = MKLDNNMatrix::create(inMat, inDims, format::nchw, engine_);
T
tensor-tang 已提交
265
    }
266 267 268 269 270 271 272 273
    if (dnnIn->getPrimitiveDesc() == in->getPrimitiveDesc()) {
      in = dnnIn;
      return;
    }
    cpuInVal_ = dnnIn;
    in = MKLDNNMatrix::create(nullptr, pd->src_primitive_desc());
    cvtInVal_ = MKLDNNMatrix::createReorder(cpuInVal_, in);
    CHECK(cvtInVal_) << "should not be emptry";
T
tensor-tang 已提交
274
  } else {
275
    memory::dims inDims = memory::dims{bs_, ic_, ih_, iw_};
276
    cpuInVal_ = MKLDNNMatrix::create(inMat, inDims, format::nchw, engine_);
T
tensor-tang 已提交
277 278
    if (cpuInVal_->getPrimitiveDesc() != in->getPrimitiveDesc()) {
      // create new mkldnn matrix
279
      in = MKLDNNMatrix::create(nullptr, pd->src_primitive_desc());
T
tensor-tang 已提交
280
      cvtInVal_ = MKLDNNMatrix::createReorder(cpuInVal_, in);
281
      CHECK(cvtInVal_) << "should not be emptry";
T
tensor-tang 已提交
282 283 284 285
    } else {
      in = cpuInVal_;
    }
  }
286
}
T
tensor-tang 已提交
287

288 289 290 291 292 293 294
void MKLDNNConvLayer::resetWgtBiasValue(
    std::shared_ptr<conv_fwd::primitive_desc>& pd,
    MKLDNNMatrixPtr& wgt,
    MKLDNNMatrixPtr& bias) {
  wgt = MKLDNNMatrix::create(weight_->getW(), pd->weights_primitive_desc());
  VLOG(MKLDNN_FMTS) << "Weight value format: " << wgt->getFormat();

295 296 297
  bias = (biases_ && biases_->getW())
             ? MKLDNNMatrix::create(biases_->getW(), pd->bias_primitive_desc())
             : nullptr;
298 299 300 301 302
}

void MKLDNNConvLayer::resetOutValue(
    std::shared_ptr<conv_fwd::primitive_desc>& pd, MKLDNNMatrixPtr& out) {
  out = MKLDNNMatrix::create(output_.value, pd->dst_primitive_desc());
T
tensor-tang 已提交
303

304 305
  // create reorder if output value has cpu device and pd do not match
  cpuOutVal_ = nullptr;
306
  cvtOutVal_ = nullptr;
T
tensor-tang 已提交
307 308
  if (!outputIsOnlyMKLDNN()) {
    const MatrixPtr& cpuOut = getOutput(CPU_DEVICE).value;
309
    memory::dims outDims = memory::dims{bs_, oc_, oh_, ow_};
T
tensor-tang 已提交
310
    cpuOutVal_ = MKLDNNMatrix::create(cpuOut, outDims, format::nchw, engine_);
311 312
    if (cpuOutVal_->getPrimitiveDesc() != pd->dst_primitive_desc()) {
      out = MKLDNNMatrix::create(nullptr, pd->dst_primitive_desc());
T
tensor-tang 已提交
313
      cvtOutVal_ = MKLDNNMatrix::createReorder(out, cpuOutVal_);
314
      CHECK(cvtOutVal_) << "should not be empty";
T
tensor-tang 已提交
315 316 317
    } else {
      cpuOutVal_ = out;
    }
T
tensor-tang 已提交
318
    // when output is cpu device, change the mkldnn output value and make them
319 320 321 322
    // share the same data. Then if next layer use inputlayer->getOuputValue()
    // to achieve the input value, it will get the right data.
    output_.value = std::dynamic_pointer_cast<Matrix>(cpuOutVal_);
    return;
T
tensor-tang 已提交
323
  }
324
  output_.value = std::dynamic_pointer_cast<Matrix>(out);
T
tensor-tang 已提交
325 326
}

327 328 329 330
void MKLDNNConvLayer::resetBwdWgtPD(
    std::shared_ptr<conv_bwdWgt::primitive_desc>& pd) {
  memory::dims wgtDims, biasDims, strides, dilations, padL, padR;
  loadConvSettings(wgtDims, biasDims, strides, dilations, padL, padR);
T
tensor-tang 已提交
331

332
  // create backward weight using input, output and weight value memory desc
T
tensor-tang 已提交
333 334 335 336 337
  CHECK(inVal_) << "Should have input value";
  CHECK(outVal_) << "Should have output value";
  CHECK(wgtVal_) << "Should have weight value";
  algorithm algo = algorithm::convolution_direct;
  padding_kind padKind = padding_kind::zero;
338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357
  auto bwdWgtDesc = biasVal_ != nullptr
                        ? conv_bwdWgt::desc(algo,
                                            inVal_->getMemoryDesc(),
                                            wgtVal_->getMemoryDesc(),
                                            biasVal_->getMemoryDesc(),
                                            outVal_->getMemoryDesc(),
                                            strides,
                                            padL,
                                            padR,
                                            padKind)
                        : conv_bwdWgt::desc(algo,
                                            inVal_->getMemoryDesc(),
                                            wgtVal_->getMemoryDesc(),
                                            outVal_->getMemoryDesc(),
                                            strides,
                                            padL,
                                            padR,
                                            padKind);
  pd.reset(new conv_bwdWgt::primitive_desc(bwdWgtDesc, engine_, *fwdPD_));
  CHECK(pd->src_primitive_desc() == inVal_->getPrimitiveDesc())
T
tensor-tang 已提交
358
      << "primitive desc of in value should equal";
359
  CHECK(pd->diff_dst_primitive_desc() == outVal_->getPrimitiveDesc())
T
tensor-tang 已提交
360
      << "primitive desc of out grad should equal the out value";
361
  CHECK(pd->diff_weights_primitive_desc() == wgtVal_->getPrimitiveDesc())
T
tensor-tang 已提交
362
      << "primitive desc of weight grad should equal the weight value";
363
}
T
tensor-tang 已提交
364

365 366
void MKLDNNConvLayer::resetBwdDataPD(
    std::shared_ptr<conv_bwdData::primitive_desc>& pd) {
367
  pd = nullptr;
368 369
  if (inputLayers_[0]->getOutput().grad == nullptr) {
    return;
T
tensor-tang 已提交
370 371
  }

372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451
  memory::dims wgtDims, biasDims, strides, dilations, padL, padR;
  loadConvSettings(wgtDims, biasDims, strides, dilations, padL, padR);
  CHECK(inVal_) << "Should have input value";
  CHECK(outVal_) << "Should have output value";
  // create backward data using input and output value memory desc
  // but using weight memory desc with any format
  auto bwdDataDesc = conv_bwdData::desc(algorithm::convolution_direct,
                                        inVal_->getMemoryDesc(),
                                        MKLDNNMatrix::createMemoryDesc(wgtDims),
                                        outVal_->getMemoryDesc(),
                                        strides,
                                        padL,
                                        padR,
                                        padding_kind::zero);
  pd.reset(new conv_bwdData::primitive_desc(bwdDataDesc, engine_, *fwdPD_));
  CHECK(pd->diff_src_primitive_desc() == inVal_->getPrimitiveDesc())
      << "primitive desc of in grad should equal the in value";
  CHECK(pd->diff_dst_primitive_desc() == outVal_->getPrimitiveDesc())
      << "primitive desc of out grad should equal";
}

void MKLDNNConvLayer::resetBwdBuffers(
    std::shared_ptr<conv_bwdWgt::primitive_desc>& wgtPD,
    std::shared_ptr<conv_bwdData::primitive_desc>& dataPD,
    MKLDNNMatrixPtr& in,
    MKLDNNMatrixPtr& wgt,
    MKLDNNMatrixPtr& bias,
    MKLDNNMatrixPtr& out) {
  CHECK(wgtPD);
  resetOutGrad(wgtPD, out);

  resetWgtBiasGrad(wgtPD, wgt, bias);

  resetInGrad(dataPD, in);

  resetWgtValBwdData(dataPD, wgtValBwdData_);
}

void MKLDNNConvLayer::resetBwdPipeline(
    std::vector<primitive>& pipeline,
    std::shared_ptr<conv_bwdWgt::primitive_desc>& wgtPD,
    std::shared_ptr<conv_bwdData::primitive_desc>& dataPD,
    MKLDNNMatrixPtr& in,
    MKLDNNMatrixPtr& wgt,
    MKLDNNMatrixPtr& bias,
    MKLDNNMatrixPtr& out) {
  if (cvtOutGrad_) {
    pipeline.push_back(*cvtOutGrad_);
  }

  // add bwdWgt handle
  if (bias) {
    bwdWgt_.reset(new conv_bwdWgt(*wgtPD, *inVal_, *out, *wgt, *bias));
  } else {
    bwdWgt_.reset(new conv_bwdWgt(*wgtPD, *inVal_, *out, *wgt));
  }
  pipeline.push_back(*bwdWgt_);

  if (dataPD == nullptr) {
    return;
  }

  if (cvtWgtVal_) {
    pipeline.push_back(*cvtWgtVal_);
  }

  // add bwdData handle
  CHECK(wgtValBwdData_) << "Should have weight memory";
  bwdData_.reset(new conv_bwdData(*dataPD, *out, *wgtValBwdData_, *in));
  pipeline.push_back(*bwdData_);

  if (cvtInGrad_) {
    pipeline.push_back(*cvtInGrad_);
  }
}

void MKLDNNConvLayer::resetOutGrad(
    std::shared_ptr<conv_bwdWgt::primitive_desc>& wgtPD, MKLDNNMatrixPtr& out) {
  cpuOutGrad_ = nullptr;
  cvtOutGrad_ = nullptr;
T
tensor-tang 已提交
452 453 454 455 456 457
  CHECK(outVal_ != nullptr &&
        outVal_->getPrimitiveDesc() == wgtPD->diff_dst_primitive_desc())
      << "primitive desc of out grad and value should be equal";
  if (outputIsOnlyMKLDNN()) {
    MKLDNNLayer::resetOutGrad(out, outVal_->getPrimitiveDesc());
  } else {
T
tensor-tang 已提交
458 459 460 461
    const MatrixPtr& cpuOut = getOutput(CPU_DEVICE).grad;
    // same PrimitiveDesc with cpuInVal_
    CHECK(cpuOutVal_);
    cpuOutGrad_ = MKLDNNMatrix::create(cpuOut, cpuOutVal_->getPrimitiveDesc());
T
tensor-tang 已提交
462 463 464
    // create reorder if primitive desc does not match
    if (cpuOutGrad_->getPrimitiveDesc() != outVal_->getPrimitiveDesc()) {
      out = MKLDNNMatrix::create(output_.grad, outVal_->getPrimitiveDesc());
T
tensor-tang 已提交
465 466
      cvtOutGrad_ = MKLDNNMatrix::createReorder(cpuOutGrad_, out);
      CHECK(cvtOutGrad_);
T
tensor-tang 已提交
467 468 469 470
    } else {
      // share the same data of CPU output
      output_.grad->setData(cpuOut->getData());
      out = cpuOutGrad_;
T
tensor-tang 已提交
471 472
    }
  }
473
}
T
tensor-tang 已提交
474

475 476 477 478 479 480 481 482 483 484
void MKLDNNConvLayer::resetWgtBiasGrad(
    std::shared_ptr<conv_bwdWgt::primitive_desc>& wgtPD,
    MKLDNNMatrixPtr& wgt,
    MKLDNNMatrixPtr& bias) {
  wgt = MKLDNNMatrix::create(weight_->getWGrad(),
                             wgtPD->diff_weights_primitive_desc());
  CHECK(nullptr != wgtVal_ &&
        wgt->getPrimitiveDesc() == wgtVal_->getPrimitiveDesc())
      << "primitive desc of weight grad and value should be equal";
  VLOG(MKLDNN_FMTS) << "weight grad format: " << wgt->getFormat();
T
tensor-tang 已提交
485

486
  bias = nullptr;
487
  if (biasVal_ == nullptr) {
T
tensor-tang 已提交
488 489
    return;
  }
490 491 492 493 494
  bias = MKLDNNMatrix::create(biases_->getWGrad(),
                              wgtPD->diff_bias_primitive_desc());
  CHECK(bias->getPrimitiveDesc() == biasVal_->getPrimitiveDesc())
      << "primitive desc of bias grad should equal the bias value";
}
T
tensor-tang 已提交
495

496 497 498
void MKLDNNConvLayer::resetInGrad(
    std::shared_ptr<conv_bwdData::primitive_desc>& dataPD,
    MKLDNNMatrixPtr& in) {
T
tensor-tang 已提交
499 500 501
  in = nullptr;
  cpuInGrad_ = nullptr;
  cvtInGrad_ = nullptr;
502 503 504
  if (dataPD == nullptr) {
    return;
  }
T
tensor-tang 已提交
505

T
tensor-tang 已提交
506 507 508 509 510 511
  if (inputIsOnlyMKLDNN()) {
    MKLDNNLayer::resetInGrad(in, dataPD->diff_src_primitive_desc());
    CHECK(nullptr != inVal_ &&
          in->getPrimitiveDesc() == inVal_->getPrimitiveDesc())
        << "primitive desc of input grad and value should be equal";
  } else {
T
tensor-tang 已提交
512 513 514 515
    const MatrixPtr& cpuIn = getInputGrad(0, CPU_DEVICE);
    // same PrimitiveDesc with cpuInVal_
    CHECK(cpuInVal_);
    cpuInGrad_ = MKLDNNMatrix::create(cpuIn, cpuInVal_->getPrimitiveDesc());
T
tensor-tang 已提交
516 517 518 519 520
    in = cpuInGrad_;
    // create reorder if PrimitiveDesc does not match
    if (cpuInGrad_->getPrimitiveDesc() != dataPD->diff_src_primitive_desc()) {
      in = MKLDNNMatrix::create(getInputGrad(0, MKLDNN_DEVICE),
                                dataPD->diff_src_primitive_desc());
T
tensor-tang 已提交
521 522 523 524
      cvtInGrad_ = MKLDNNMatrix::createReorder(in, cpuInGrad_);
      CHECK(cvtInGrad_);
    }
  }
525
}
T
tensor-tang 已提交
526

527 528 529 530 531 532 533 534
void MKLDNNConvLayer::resetWgtValBwdData(
    std::shared_ptr<conv_bwdData::primitive_desc>& dataPD,
    MKLDNNMatrixPtr& wgt) {
  if (dataPD == nullptr) {
    return;
  }

  // create new weight value for backward data, and create reorder if necessary
T
tensor-tang 已提交
535
  // since the primitive_desc would be different with wgtVal_
536 537
  CHECK(wgtVal_) << "should have weight value";
  if (dataPD->weights_primitive_desc() != wgtVal_->getPrimitiveDesc()) {
T
tensor-tang 已提交
538
    wgtValBwdData_ =
539
        MKLDNNMatrix::create(nullptr, dataPD->weights_primitive_desc());
T
tensor-tang 已提交
540 541 542 543 544
    cvtWgtVal_ = MKLDNNMatrix::createReorder(wgtVal_, wgtValBwdData_);
    CHECK(cvtWgtVal_);
  } else {
    wgtValBwdData_ = wgtVal_;
  }
T
tensor-tang 已提交
545
  VLOG(MKLDNN_FMTS) << "weight value format for backward data: "
T
tensor-tang 已提交
546 547 548 549
                    << wgtValBwdData_->getFormat();
}

}  // namespace paddle