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

#pragma once

#include <vector>
#include "Layer.h"
19
#include "MKLDNNBase.h"
T
tensor-tang 已提交
20
#include "mkldnn.hpp"
T
tensor-tang 已提交
21
#include "paddle/math/MKLDNNMatrix.h"
22
#include "paddle/utils/Stat.h"
T
tensor-tang 已提交
23

T
tensor-tang 已提交
24 25
DECLARE_bool(use_mkldnn);

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

28 29
class MKLDNNLayer;
typedef std::shared_ptr<MKLDNNLayer> MKLDNNLayerPtr;
T
tensor-tang 已提交
30 31

/**
32
 * @brief Base class of MKLDNNlayer.
T
tensor-tang 已提交
33 34
 *
 */
35
class MKLDNNLayer : public Layer {
T
tensor-tang 已提交
36
protected:
37 38
  // input value element count
  size_t inputElemenCnt_;
T
tensor-tang 已提交
39 40 41 42 43 44 45
  // batch size
  int bs_;
  // input image channel, height and width
  int ic_, ih_, iw_;
  // output image channel, height and width
  int oc_, oh_, ow_;

T
tensor-tang 已提交
46 47 48
  // backward also need reset after reset forward handle
  bool needResetBwd_;

49 50 51
  // is output only mkldnn
  bool outputOnlyMKLDNN_;

T
tensor-tang 已提交
52 53
  // mkldnn engine, stream and primivtives
  mkldnn::engine engine_;
54
  std::shared_ptr<MKLDNNStream> stream_;
T
tensor-tang 已提交
55
  std::shared_ptr<mkldnn::primitive> fwd_;
T
tensor-tang 已提交
56 57
  std::shared_ptr<mkldnn::primitive> bwdWgt_;
  std::shared_ptr<mkldnn::primitive> bwdData_;
T
tensor-tang 已提交
58 59 60
  std::vector<mkldnn::primitive> pipelineFwd_;
  std::vector<mkldnn::primitive> pipelineBwd_;

61 62 63 64 65 66 67 68
  /// value and grad are seperate as internal and external buffers.
  /// each MKLDNNLayer must init or reset internal buffer at least,
  /// and the external buffer format is always nchw of nc(when h==w==1),
  /// which is the same format as paddle.
  /// When mixed with cpu device, the output_.value and output_.grad
  /// always save the external data.
  /// When all layers are all mkldnn layers, they could be internal data.
  /// below MKLDNNMatrix buffers are all internal buffers
T
tensor-tang 已提交
69
  MKLDNNMatrixPtr inVal_;
T
tensor-tang 已提交
70
  MKLDNNMatrixPtr inGrad_;
T
tensor-tang 已提交
71
  MKLDNNMatrixPtr outVal_;
T
tensor-tang 已提交
72
  MKLDNNMatrixPtr outGrad_;
73 74 75 76 77 78 79 80 81 82 83 84
  // below are external value and grad
  MKLDNNMatrixPtr extInVal_;
  MKLDNNMatrixPtr extInGrad_;
  MKLDNNMatrixPtr extOutVal_;
  MKLDNNMatrixPtr extOutGrad_;
  // convert handle between external and internal buffers
  std::shared_ptr<mkldnn::reorder> cvtInVal_;
  std::shared_ptr<mkldnn::reorder> cvtInGrad_;
  std::shared_ptr<mkldnn::reorder> cvtOutVal_;
  std::shared_ptr<mkldnn::reorder> cvtOutGrad_;

  // weight and bias are always internal buffers
T
tensor-tang 已提交
85
  MKLDNNMatrixPtr wgtVal_;
T
tensor-tang 已提交
86
  MKLDNNMatrixPtr wgtGrad_;
T
tensor-tang 已提交
87
  MKLDNNMatrixPtr biasVal_;
T
tensor-tang 已提交
88
  MKLDNNMatrixPtr biasGrad_;
T
tensor-tang 已提交
89

T
tensor-tang 已提交
90 91
  // merge grad primitive
  std::shared_ptr<mkldnn::primitive> mergeGrad_;
92
  std::vector<mkldnn::primitive> pipelineMergeGrad_;
T
tensor-tang 已提交
93 94
  // tmp input argument to save input grad, only used to merge grad
  Argument tmpInArg_;
95 96 97 98 99
  // since mkldnn sum do not support different formats:
  // can refer to https://github.com/01org/mkl-dnn/issues/134
  // so need create reorder manually and save tmp MKLDNNMatrix
  MKLDNNMatrixPtr tmpOutGrad_;
  std::shared_ptr<mkldnn::primitive> tmpCvt_;
T
tensor-tang 已提交
100

T
tensor-tang 已提交
101
public:
102
  explicit MKLDNNLayer(const LayerConfig& config)
T
tensor-tang 已提交
103
      : Layer(config),
104
        inputElemenCnt_(0),
T
tensor-tang 已提交
105 106 107 108 109 110 111
        bs_(0),
        ic_(0),
        ih_(0),
        iw_(0),
        oc_(0),
        oh_(0),
        ow_(0),
T
tensor-tang 已提交
112
        needResetBwd_(true),
113
        outputOnlyMKLDNN_(false),
T
tensor-tang 已提交
114
        engine_(mkldnn::engine::cpu, 0),
T
tensor-tang 已提交
115 116 117 118
        stream_(nullptr),
        fwd_(nullptr),
        bwdWgt_(nullptr),
        bwdData_(nullptr) {}
T
tensor-tang 已提交
119

120
  ~MKLDNNLayer() {}
T
tensor-tang 已提交
121

T
tensor-tang 已提交
122 123
  virtual bool init(const LayerMap& layerMap,
                    const ParameterMap& parameterMap) {
T
tensor-tang 已提交
124 125 126
    CHECK(FLAGS_use_mkldnn) << "MkldnnLayers only support use_mkldnn."
                            << "Please set WITH_MKLDNN=ON "
                            << "and set use_mkldnn=True";
T
refine  
tensor-tang 已提交
127
    CHECK(!useGpu_) << "Do not support GPU yet";
T
tensor-tang 已提交
128 129 130 131 132

    // set device id before Layer::init
    setDevice(MKLDNN_DEVICE);
    // change param device to MKLDNN device
    setParamsDevice(MKLDNN_DEVICE, parameterMap);
T
tensor-tang 已提交
133 134 135
    if (!Layer::init(layerMap, parameterMap)) {
      return false;
    }
T
tensor-tang 已提交
136
    setOutputMap();
137
    checkCPUOutputsNumber();
T
tensor-tang 已提交
138

139 140
    stream_.reset(new MKLDNNStream());
    engine_ = CPUEngine::Instance().getEngine();
T
tensor-tang 已提交
141 142
    return true;
  }
T
tensor-tang 已提交
143

144 145 146 147 148 149
  void forward(PassType passType) override {
    passType_ = passType;

    {
      REGISTER_TIMER_INFO("mkldnn_FwdTimer", getName().c_str());
      CHECK(!inputLayers_.empty());
150
      copySeqInfoToOutputs();
151
      size_t elemenCnt = inputLayers_[0]->getOutputValue()->getElementCnt();
152
      if (inputElemenCnt_ != elemenCnt) {
T
tensor-tang 已提交
153
        VLOG(MKLDNN_BASE) << getName() << " reset mkldnn forward";
154
        // reset when input total sizes changed, not only the batchsize
155
        inputElemenCnt_ = elemenCnt;
T
tensor-tang 已提交
156
        pipelineFwd_.clear();
157
        reshape(bs_, ic_, ih_, iw_, oc_, oh_, ow_);
158 159
        // all cpu device output grad or value share output's
        shareCPUDevice();
160
        resetFwd(pipelineFwd_, inVal_, wgtVal_, biasVal_, outVal_);
161 162 163 164 165 166 167 168 169 170 171 172 173
        // MKLDNNLayer output value should be MKLDNNMatrix
        // so external output value is necessary.
        // then external input value is not necessary,
        // since input may be mkldnn internal buffer.
        CHECK(extOutVal_) << "external output value is necessary";
        output_.value = std::dynamic_pointer_cast<Matrix>(extOutVal_);
        CHECK(inVal_ && outVal_) << "internal memories are necessary";
        if (cvtInVal_) {
          pipelineFwd_.insert(pipelineFwd_.begin(), *cvtInVal_);
        }
        if (cvtOutVal_) {
          pipelineFwd_.push_back(*cvtOutVal_);
        }
174
        convertWeightsFromPaddle();
175
        printValueFormat();
176 177 178 179
        needResetBwd_ = true;
      }

      if (inputLayers_[0]->getType() == "data") {
180 181 182 183
        // Update input value data when input layer is "data" type,
        // since the input value data address might be changed.
        CHECK(extInVal_);
        extInVal_->setData(getInputValue(0, CPU_DEVICE)->getData());
184 185
      }

186 187 188
      if (!outputOnlyMKLDNN_) {
        clearGrads();
      }
189 190
      stream_->submit(pipelineFwd_);
    }
191
    {
192 193 194 195 196 197
      REGISTER_TIMER_INFO("FwActTimer", getName().c_str());
      forwardActivation();
    }
  }

  void backward(const UpdateCallback& callback) override {
T
tensor-tang 已提交
198
    if (needResetBwd_) {
T
tensor-tang 已提交
199
      VLOG(MKLDNN_BASE) << getName() << " reset mkldnn backward";
T
tensor-tang 已提交
200
      pipelineBwd_.clear();
201 202
      pipelineMergeGrad_.clear();
      mergeGrad_ = nullptr;
T
tensor-tang 已提交
203
      resetBwd(pipelineBwd_, inGrad_, wgtGrad_, biasGrad_, outGrad_);
204 205 206 207 208 209 210 211 212 213
      // external output grad is not necessary
      // since output may be mkldnn internal buffer or merge them directly.
      CHECK(outGrad_) << "internal output grad is necessary";
      if (cvtOutGrad_) {
        pipelineBwd_.insert(pipelineBwd_.begin(), *cvtOutGrad_);
      }
      if (cvtInGrad_) {
        pipelineBwd_.push_back(*cvtInGrad_);
      }
      printGradFormat();
T
tensor-tang 已提交
214 215
      needResetBwd_ = false;
    }
216 217 218 219 220 221

    // merge grad must before backward activation
    if (mergeGrad_) {
      REGISTER_TIMER_INFO("MergeBpGrad", getName().c_str());
      stream_->submit(pipelineMergeGrad_);
    }
T
tensor-tang 已提交
222
    {
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
      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);
    }
  }

  /**
   * reshape the input image sizes
   * and reset output image and buffer size
239
   * output channel can not be changed
240
   */
241 242
  virtual void reshape(
      int& bs, int& ic, int& ih, int& iw, int oc, int& oh, int& ow) = 0;
243 244

  /**
245
   * reset the mkldnn forward primitve and memories
246 247
   * only would be called when input size changes
   */
248 249 250 251 252
  virtual void resetFwd(std::vector<mkldnn::primitive>& pipeline,
                        MKLDNNMatrixPtr& in,
                        MKLDNNMatrixPtr& wgt,
                        MKLDNNMatrixPtr& bias,
                        MKLDNNMatrixPtr& out) = 0;
253 254

  /**
255
   * reset the mkldnn backward primitve and memories
256 257
   * only would be called when needed
   */
258 259 260 261 262
  virtual void resetBwd(std::vector<mkldnn::primitive>& pipeline,
                        MKLDNNMatrixPtr& in,
                        MKLDNNMatrixPtr& wgt,
                        MKLDNNMatrixPtr& bias,
                        MKLDNNMatrixPtr& out) = 0;
263 264 265 266 267 268

  /**
   * Update weights and biases if necessary.
   */
  virtual void updateWeights(const UpdateCallback& callback) {}

T
tensor-tang 已提交
269 270 271 272
  /**
   * convert weight from paddle format to mkldnn format
   * weight_ will be override
   */
273
  virtual void convertWeightsFromPaddle() {}
T
tensor-tang 已提交
274 275 276 277 278

  /**
   * convert mkldnn weight to paddle format
   * weight_ will be override
   */
279
  virtual void convertWeightsToPaddle() {}
T
tensor-tang 已提交
280

281
  /**
282
   * add this interface as public for unit test
283
   */
284 285 286 287 288 289
  void addOutputArgument(int deviceId) { Layer::addOutputArgument(deviceId); }

protected:
  /**
   * reshape the input image sizes and input batchsize
   */
290
  virtual void reshapeInput(int& batchsize, int& height, int& width) {
291
    const Argument& input = inputLayers_[0]->getOutput();
292 293 294 295 296
    batchsize = input.getBatchSize();
    int h = input.getFrameHeight();
    int w = input.getFrameWidth();
    if (h != 0) {
      height = h;
297
    }
298 299
    if (w != 0) {
      width = w;
300 301 302 303 304 305 306 307 308 309 310 311 312 313
    }
  }

  /**
   * reshape output image sizes
   */
  virtual void 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);
    }
  }
314

T
tensor-tang 已提交
315
  /**
316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 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
   * reset MKLDNNMatrix from Matrix and internal primitive desc.
   * reset nullptr if matrix or primitive desc is empty
   */
  void resetWithMatrix(MKLDNNMatrixPtr& dnn,
                       const MatrixPtr& mat,
                       mkldnn::memory::primitive_desc pd) {
    dnn = nullptr;
    if (mat == nullptr) {
      return;
    }
    dnn = MKLDNNMatrix::create(mat, pd);
  }

  /**
   * reset input value from input MKLDNNMatrix and internal primitive desc.
   * reset both internal and external buffer and create reorder if necessary.
   */
  void resetInValue(
      MKLDNNMatrixPtr& in,
      const std::shared_ptr<mkldnn::memory::primitive_desc>& intPD = nullptr) {
    cvtInVal_ = nullptr;
    extInVal_ = nullptr;
    in = nullptr;
    CHECK_GT(bs_ * ic_ * ih_ * iw_, 0);
    auto extPD = MKLDNNMatrix::createPrimitiveDesc(
        {bs_, ic_, ih_, iw_}, mkldnn::memory::format::nchw, engine_);
    const MatrixPtr& inMat = inputLayers_[0]->getOutputValue();
    in = std::dynamic_pointer_cast<MKLDNNMatrix>(inMat);
    CHECK_EQ(inputIsOnlyMKLDNN(), in != nullptr);
    if (in == nullptr || in->getFormat() == mkldnn::memory::format::nc) {
      in = MKLDNNMatrix::create(inMat, extPD);
    }
    extInVal_ = isPaddleFormat(in->getFormat()) ? in : nullptr;
    if (in->getFormat() == mkldnn::memory::format::nc) {
      CHECK(ih_ == 1 && iw_ == 1);
    }
    if (nullptr == intPD || in->getPrimitiveDesc() == *intPD) {
      return;
    }
    // need create reorder
    in = MKLDNNMatrix::create(nullptr, *intPD);
    extInVal_ = extInVal_ ? extInVal_ : MKLDNNMatrix::create(inMat, extPD);
    cvtInVal_ = MKLDNNMatrix::createReorder(extInVal_, in);
    CHECK(cvtInVal_) << "should not be emptry";
  }

  /**
   * reset output value from internal primitive desc.
   * reset both internal and external buffer and create reorder if necessary.
   */
  void resetOutValue(MKLDNNMatrixPtr& out,
                     mkldnn::memory::primitive_desc intPD) {
    cvtOutVal_ = nullptr;
    out = MKLDNNMatrix::create(output_.value, intPD);
    extOutVal_ = out;
    if (outputIsOnlyMKLDNN() || isPaddleFormat(extOutVal_->getFormat())) {
      return;
    }
    // need create reorder
    CHECK_GT(bs_ * oc_ * oh_ * ow_, 0);
    extOutVal_ = MKLDNNMatrix::create(output_.value,
                                      {bs_, oc_, oh_, ow_},
                                      mkldnn::memory::format::nchw,
                                      engine_);
    out = MKLDNNMatrix::create(nullptr, intPD);
    cvtOutVal_ = MKLDNNMatrix::createReorder(out, extOutVal_);
    CHECK(cvtOutVal_) << "should not be empty";
  }

  /**
   * reset input grad from internal primitive desc.
   * reset both internal and external buffer and create reorder if necessary.
   */
  void resetInGrad(MKLDNNMatrixPtr& in, mkldnn::memory::primitive_desc intPD) {
    cvtInGrad_ = nullptr;
    extInGrad_ = nullptr;
    in = nullptr;
    LayerPtr& input = inputLayers_[0];
    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(inMat, intPD);
    Argument& arg = input->getOutput(this->getName());
    arg.grad = std::dynamic_pointer_cast<Matrix>(in);
    CHECK(inVal_ != nullptr && inVal_->getPrimitiveDesc() == intPD)
        << "should have internal input value and primitive desc must equal";
    if (inputIsOnlyMKLDNN()) {
      return;
    }

    extInGrad_ = in;
    if (isPaddleFormat(extInGrad_->getFormat())) {
      return;
    }
    // need create reorder
    CHECK(extInVal_ != nullptr && isPaddleFormat(extInVal_->getFormat()))
        << "should have external input value and the format must be nchw(nc)";
    extInGrad_ = MKLDNNMatrix::create(inMat, extInVal_->getPrimitiveDesc());
    CHECK(inVal_ != nullptr && inVal_->getPrimitiveDesc() == intPD)
        << "should have internal input value and primitive desc must equal";
    in = MKLDNNMatrix::create(nullptr, intPD);
    cvtInGrad_ = MKLDNNMatrix::createReorder(in, extInGrad_);
    CHECK(cvtInGrad_);
  }

  /**
   * reset output grad from internal primitive desc.
   * merge grad if necessary.
   * reset both internal and external buffer and create reorder if necessary.
   * note: about merge grad, when this layer has serval outputs,
T
tensor-tang 已提交
434 435
   *       it could not be mixed with cpu device,
   *       since it can not get memory desc from cpu device.
T
tensor-tang 已提交
436
   */
437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469
  void resetOutGrad(MKLDNNMatrixPtr& out,
                    mkldnn::memory::primitive_desc intPD) {
    cvtOutGrad_ = nullptr;
    extOutGrad_ = nullptr;
    out = nullptr;
    MatrixPtr& outMat = output_.grad;
    out = MKLDNNMatrix::create(outMat, intPD);
    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(outMat, extOutVal_->getPrimitiveDesc());
    CHECK(outVal_ != nullptr && outVal_->getPrimitiveDesc() == intPD)
        << "should have internal output value and primitive desc must equal";
    out = MKLDNNMatrix::create(nullptr, intPD);
    cvtOutGrad_ = MKLDNNMatrix::createReorder(extOutGrad_, out);
    CHECK(cvtOutGrad_);
  }

  /**
   * reset the merge grad primitive if necessary.
   * note: do not support the grads are mixed with cpu device,
   *       since it can not get memory desc from cpu device.
   */
  virtual void resetMergeGrad(MKLDNNMatrixPtr& out) {
T
tensor-tang 已提交
470
    mergeGrad_ = nullptr;
471
    pipelineMergeGrad_.clear();
472 473
    if (outputMap_.size() <= 1 || !outputIsOnlyMKLDNN()) {
      // do not merge when output is not all MKLDNN or only one output
T
tensor-tang 已提交
474 475
      return;
    }
476
    CHECK(out) << "should have reset internal ouput grad";
T
tensor-tang 已提交
477
    std::vector<double> scales(outputMap_.size(), 1.0);
T
tensor-tang 已提交
478 479 480 481 482
    std::vector<mkldnn::memory::primitive_desc> srcPDs;
    std::vector<mkldnn::primitive::at> srcs;
    for (auto it = outputMap_.begin(); it != outputMap_.end(); ++it) {
      MKLDNNMatrixPtr src =
          std::dynamic_pointer_cast<MKLDNNMatrix>(it->second->grad);
483
      VLOG(MKLDNN_BASE) << getName() << " has output grad " << it->first;
T
tensor-tang 已提交
484 485 486 487 488 489 490 491 492 493
      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]);
      }
      srcPDs.push_back(src->getPrimitiveDesc());
      srcs.push_back(*src);
    }
494 495 496 497 498

    // TODO(TJ): remove me when mkldnn sum support different formats
    for (size_t i = 1; i < srcPDs.size(); ++i) {
      CHECK(srcPDs[0] == srcPDs[i]);
    }
499
    tmpOutGrad_ = out;
500 501 502 503 504 505 506 507 508 509 510 511
    tmpCvt_ = nullptr;
    if (out->getPrimitiveDesc() != srcPDs[0]) {
      tmpOutGrad_ = MKLDNNMatrix::create(nullptr, srcPDs[0]);
      tmpCvt_ = MKLDNNMatrix::createReorder(tmpOutGrad_, out);
      CHECK(tmpCvt_);
      pipelineMergeGrad_.push_back(*tmpCvt_);
    }

    auto sumPD = mkldnn::sum::primitive_desc(
        tmpOutGrad_->getMemoryDesc(), scales, srcPDs);
    mergeGrad_.reset(new mkldnn::sum(sumPD, srcs, *tmpOutGrad_));
    pipelineMergeGrad_.insert(pipelineMergeGrad_.begin(), *mergeGrad_);
T
tensor-tang 已提交
512 513
  }

T
tensor-tang 已提交
514 515 516 517 518 519 520 521
  /**
   * print info about sizes
   */
  virtual void printSizeInfo() {
    VLOG(MKLDNN_SIZES) << getName() << ": bs: " << bs_ << ", ic: " << ic_
                       << ", ih: " << ih_ << ", iw: " << iw_ << ", oc: " << oc_
                       << ", oh: " << oh_ << ", ow: " << ow_;
  }
T
tensor-tang 已提交
522

523
  /**
524
   * print the mkldnn memory format of value
525
   */
526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543
  virtual void printValueFormat() {
    if (extInVal_) {
      VLOG(MKLDNN_FMTS) << extInVal_->getFormat() << " >>> ";
    }
    if (inVal_) {
      VLOG(MKLDNN_FMTS) << inVal_->getFormat() << " >>>";
    }
    if (outVal_) {
      VLOG(MKLDNN_FMTS) << outVal_->getFormat() << " >>> ";
    }
    if (extOutVal_) {
      VLOG(MKLDNN_FMTS) << extOutVal_->getFormat();
    }
    if (wgtVal_) {
      VLOG(MKLDNN_FMTS) << "Weight value format: " << wgtVal_->getFormat();
    }
    if (biasVal_) {
      VLOG(MKLDNN_FMTS) << "Bias value format: " << biasVal_->getFormat();
544
    }
T
tensor-tang 已提交
545
  }
T
tensor-tang 已提交
546

547
  /**
548
   * print the mkldnn memory format of grad
549
   */
550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567
  virtual void printGradFormat() {
    if (extInGrad_) {
      VLOG(MKLDNN_FMTS) << extInGrad_->getFormat() << " <<< ";
    }
    if (inGrad_) {
      VLOG(MKLDNN_FMTS) << inGrad_->getFormat() << " <<<";
    }
    if (outGrad_) {
      VLOG(MKLDNN_FMTS) << outGrad_->getFormat() << " <<< ";
    }
    if (extOutGrad_) {
      VLOG(MKLDNN_FMTS) << extOutGrad_->getFormat();
    }
    if (wgtGrad_) {
      VLOG(MKLDNN_FMTS) << "Weight grad format: " << wgtGrad_->getFormat();
    }
    if (biasGrad_) {
      VLOG(MKLDNN_FMTS) << "Bias grad format: " << biasGrad_->getFormat();
568
    }
T
tensor-tang 已提交
569 570 571
  }

protected:
572
  /**
T
rename  
tensor-tang 已提交
573
   * If input only has MKLDNN device.
T
refine  
tensor-tang 已提交
574
   * Otherwise, only support the previous layer using CPU device.
575
   */
T
rename  
tensor-tang 已提交
576
  bool inputIsOnlyMKLDNN(int index = 0) {
577 578 579 580 581 582 583 584 585 586
    int prevDevice = getPrev(index)->getDeviceId();
    if (prevDevice == MKLDNN_DEVICE) {
      return true;
    } else {
      // do not support GPU yet
      CHECK_EQ(prevDevice, CPU_DEVICE) << "Only support CPU yet";
      return false;
    }
  }

T
refine  
tensor-tang 已提交
587 588 589 590
  /**
   * If output only has MKLDNN device.
   * Otherwise, other devices should only using CPU device.
   */
T
rename  
tensor-tang 已提交
591
  bool outputIsOnlyMKLDNN() {
T
refine  
tensor-tang 已提交
592 593 594 595
    for (size_t i = 0; i < outputOtherDevice_.size(); i++) {
      CHECK_EQ(outputOtherDevice_[i].deviceId, CPU_DEVICE)
          << "Only support other device is CPU yet";
    }
596 597
    outputOnlyMKLDNN_ = outputOtherDevice_.size() == 0;
    return outputOnlyMKLDNN_;
T
refine  
tensor-tang 已提交
598 599
  }

T
tensor-tang 已提交
600 601 602 603 604
  /**
   * Set deviceId of this layer.
   */
  void setDevice(int id) { deviceId_ = id; }

605
private:
606 607 608 609 610 611 612 613 614 615 616 617 618
  /**
   * check the format is nchw or nc,
   * which is supported by Paddle default memory layout
   */
  bool isPaddleFormat(mkldnn::memory::format fmt) {
    if (fmt == mkldnn::memory::format::nchw ||
        fmt == mkldnn::memory::format::nc) {
      return true;
    } else {
      return false;
    }
  }

619 620 621 622 623 624 625 626 627 628
  /**
   * clear all grad
   */
  void clearGrads() {
    output_.grad->zeroMem();
    for (size_t i = 0; i < outputOtherDevice_.size(); i++) {
      outputOtherDevice_[i].grad->zeroMem();
    }
  }

T
tensor-tang 已提交
629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650
  /**
   * Set deviceId of the params used in this layer.
   */
  void setParamsDevice(int id, const ParameterMap& parameterMap) {
    for (auto& inputConfig : config_.inputs()) {
      if (inputConfig.has_input_parameter_name()) {
        ParameterPtr parameter;
        std::string name = inputConfig.input_parameter_name();
        CHECK(mapGet(name, parameterMap, &parameter))
            << "Cannot find input parameter " << name << " for layer "
            << getName();
        parameter->setDevice(id);
      }
    }
    if (config_.has_bias_parameter_name()) {
      ParameterPtr parameter;
      std::string name = config_.bias_parameter_name();
      CHECK(mapGet(name, parameterMap, &parameter))
          << "Cannot find bias parameter " << name << " for layer "
          << getName();
      parameter->setDevice(id);
    }
T
tensor-tang 已提交
651
  }
652

T
tensor-tang 已提交
653 654 655 656 657 658 659 660 661 662
  /**
   * Set output map of prev layers.
   */
  void setOutputMap() {
    outputMap_.clear();
    for (size_t i = 0; i < inputLayers_.size(); ++i) {
      inputLayers_[i]->setOutput(getName(), &tmpInArg_);
    }
  }

663 664 665 666 667 668 669 670 671 672 673 674 675
  /**
   * if have cpu device, share value and grad data with output_
   */
  void shareCPUDevice() {
    if (outputIsOnlyMKLDNN()) {
      return;
    }
    for (size_t i = 0; i < outputOtherDevice_.size(); i++) {
      outputOtherDevice_[i].value = output_.value;
      outputOtherDevice_[i].grad = output_.grad;
    }
  }

676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710
  /**
   * Check the cpu device number of outputOtherDevice_.
   * should have only one at most.
   */
  void checkCPUOutputsNumber(int max = 1) {
    int cnt = 0;
    for (size_t i = 0; i < outputOtherDevice_.size(); i++) {
      if (outputOtherDevice_[i].deviceId == CPU_DEVICE) {
        ++cnt;
      }
    }
    CHECK_LE(cnt, max) << "too much CPU devies";
  }

  /**
   * copy SeqInfo from input layer to this output and other output devices.
   * @note: do not use getInput(0) since it used this deviceId_,
   *        use "inputLayers_[0]->getOutput()" instead.
   */
  void copySeqInfoToOutputs() {
    if (inputLayers_.empty() || !needSequenceInfo_) {
      return;
    }
    const Argument& input = inputLayers_[0]->getOutput();
    output_.sequenceStartPositions = input.sequenceStartPositions;
    output_.subSequenceStartPositions = input.subSequenceStartPositions;
    output_.cpuSequenceDims = input.cpuSequenceDims;
    for (size_t i = 0; i < outputOtherDevice_.size(); i++) {
      outputOtherDevice_[i].sequenceStartPositions =
          output_.sequenceStartPositions;
      outputOtherDevice_[i].subSequenceStartPositions =
          output_.subSequenceStartPositions;
      outputOtherDevice_[i].cpuSequenceDims = output_.cpuSequenceDims;
    }
  }
T
tensor-tang 已提交
711 712 713
};

}  // namespace paddle