MKLDNNLayer.h 13.1 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_;

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

58
  // MKLDNNMatrixPtr with internal format
T
tensor-tang 已提交
59
  MKLDNNMatrixPtr inVal_;
T
tensor-tang 已提交
60
  MKLDNNMatrixPtr inGrad_;
T
tensor-tang 已提交
61
  MKLDNNMatrixPtr outVal_;
T
tensor-tang 已提交
62
  MKLDNNMatrixPtr outGrad_;
T
tensor-tang 已提交
63
  MKLDNNMatrixPtr wgtVal_;
T
tensor-tang 已提交
64
  MKLDNNMatrixPtr wgtGrad_;
T
tensor-tang 已提交
65
  MKLDNNMatrixPtr biasVal_;
T
tensor-tang 已提交
66
  MKLDNNMatrixPtr biasGrad_;
T
tensor-tang 已提交
67

T
tensor-tang 已提交
68 69 70 71 72
  // merge grad primitive
  std::shared_ptr<mkldnn::primitive> mergeGrad_;
  // tmp input argument to save input grad, only used to merge grad
  Argument tmpInArg_;

T
tensor-tang 已提交
73
public:
74
  explicit MKLDNNLayer(const LayerConfig& config)
T
tensor-tang 已提交
75
      : Layer(config),
76
        inputElemenCnt_(0),
T
tensor-tang 已提交
77 78 79 80 81 82 83
        bs_(0),
        ic_(0),
        ih_(0),
        iw_(0),
        oc_(0),
        oh_(0),
        ow_(0),
T
tensor-tang 已提交
84
        needResetBwd_(true),
T
tensor-tang 已提交
85
        engine_(mkldnn::engine::cpu, 0),
T
tensor-tang 已提交
86 87 88 89
        stream_(nullptr),
        fwd_(nullptr),
        bwdWgt_(nullptr),
        bwdData_(nullptr) {}
T
tensor-tang 已提交
90

91
  ~MKLDNNLayer() {}
T
tensor-tang 已提交
92

T
tensor-tang 已提交
93 94
  virtual bool init(const LayerMap& layerMap,
                    const ParameterMap& parameterMap) {
T
tensor-tang 已提交
95 96 97
    CHECK(FLAGS_use_mkldnn) << "MkldnnLayers only support use_mkldnn."
                            << "Please set WITH_MKLDNN=ON "
                            << "and set use_mkldnn=True";
T
refine  
tensor-tang 已提交
98
    CHECK(!useGpu_) << "Do not support GPU yet";
T
tensor-tang 已提交
99 100 101 102 103

    // set device id before Layer::init
    setDevice(MKLDNN_DEVICE);
    // change param device to MKLDNN device
    setParamsDevice(MKLDNN_DEVICE, parameterMap);
T
tensor-tang 已提交
104 105 106
    if (!Layer::init(layerMap, parameterMap)) {
      return false;
    }
T
tensor-tang 已提交
107
    setOutputMap();
108
    checkCPUOutputsNumber();
T
tensor-tang 已提交
109

110 111
    stream_.reset(new MKLDNNStream());
    engine_ = CPUEngine::Instance().getEngine();
T
tensor-tang 已提交
112 113
    return true;
  }
T
tensor-tang 已提交
114

115 116 117 118 119 120
  void forward(PassType passType) override {
    passType_ = passType;

    {
      REGISTER_TIMER_INFO("mkldnn_FwdTimer", getName().c_str());
      CHECK(!inputLayers_.empty());
121
      copySeqInfoToOutputs();
122 123
      size_t elemenCnt = inputLayers_[0]->getOutput().value->getElementCnt();
      if (inputElemenCnt_ != elemenCnt) {
T
tensor-tang 已提交
124
        VLOG(MKLDNN_BASE) << getName() << " reset mkldnn forward";
125
        // reset when input total sizes changed, not only the batchsize
126
        inputElemenCnt_ = elemenCnt;
T
tensor-tang 已提交
127
        pipelineFwd_.clear();
128 129
        reshape(bs_, ic_, ih_, iw_, oc_, oh_, ow_);
        resetFwd(pipelineFwd_, inVal_, wgtVal_, biasVal_, outVal_);
130 131 132 133
        if (outVal_) {
          // change original output value to mkldnn output value
          output_.value = std::dynamic_pointer_cast<Matrix>(outVal_);
        }
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
        convertWeightsFromPaddle();
        needResetBwd_ = true;
      }

      if (inputLayers_[0]->getType() == "data") {
        updateInputData();
      }

      stream_->submit(pipelineFwd_);
    }

    /* activation */ {
      REGISTER_TIMER_INFO("FwActTimer", getName().c_str());
      forwardActivation();
    }
  }

  void backward(const UpdateCallback& callback) override {
T
tensor-tang 已提交
152
    if (needResetBwd_) {
T
tensor-tang 已提交
153
      VLOG(MKLDNN_BASE) << getName() << " reset mkldnn backward";
T
tensor-tang 已提交
154
      pipelineBwd_.clear();
T
tensor-tang 已提交
155 156 157 158
      resetBwd(pipelineBwd_, inGrad_, wgtGrad_, biasGrad_, outGrad_);
      needResetBwd_ = false;
    }
    {
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
      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
176
   * output channel can not be changed
177
   */
178 179
  virtual void reshape(
      int& bs, int& ic, int& ih, int& iw, int oc, int& oh, int& ow) = 0;
180 181 182 183 184

  /**
   * reset the mkldnn forward primitve and memory
   * only would be called when input size changes
   */
185 186 187 188 189
  virtual void resetFwd(std::vector<mkldnn::primitive>& pipeline,
                        MKLDNNMatrixPtr& in,
                        MKLDNNMatrixPtr& wgt,
                        MKLDNNMatrixPtr& bias,
                        MKLDNNMatrixPtr& out) = 0;
190 191 192 193 194

  /**
   * reset the mkldnn backward primitve and memory for mkldnn fc
   * only would be called when needed
   */
195 196 197 198 199
  virtual void resetBwd(std::vector<mkldnn::primitive>& pipeline,
                        MKLDNNMatrixPtr& in,
                        MKLDNNMatrixPtr& wgt,
                        MKLDNNMatrixPtr& bias,
                        MKLDNNMatrixPtr& out) = 0;
200 201 202 203 204 205 206 207 208 209 210 211

  /**
   * Update input value data when input layer is "data" type.
   * Since the input value data address might be changed.
   */
  virtual void updateInputData() {}

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

T
tensor-tang 已提交
212 213 214 215
  /**
   * convert weight from paddle format to mkldnn format
   * weight_ will be override
   */
216
  virtual void convertWeightsFromPaddle() {}
T
tensor-tang 已提交
217 218 219 220 221

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

224
  /**
225
   * add this interface as public for unit test
226
   */
227 228 229 230 231 232
  void addOutputArgument(int deviceId) { Layer::addOutputArgument(deviceId); }

protected:
  /**
   * reshape the input image sizes and input batchsize
   */
233
  virtual void reshapeInput(int& batchsize, int& height, int& width) {
234
    const Argument& input = inputLayers_[0]->getOutput();
235 236 237 238 239
    batchsize = input.getBatchSize();
    int h = input.getFrameHeight();
    int w = input.getFrameWidth();
    if (h != 0) {
      height = h;
240
    }
241 242
    if (w != 0) {
      width = w;
243 244 245 246 247 248 249 250 251 252 253 254 255 256
    }
  }

  /**
   * 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);
    }
  }
257

T
tensor-tang 已提交
258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309
  /**
   * reset the output grad matrix from primitive desc.
   * and reset the merge grad primitive if needed.
   * note: when this layer have serval output,
   *       do not support mixing with cpu device,
   *       because can not get memory desc from cpu device.
   */
  virtual void resetOutGrad(MKLDNNMatrixPtr& out,
                            mkldnn::memory::primitive_desc pd) {
    CHECK(outputIsOnlyMKLDNN()) << "only support mixed with other device yet";
    mergeGrad_ = nullptr;
    out = MKLDNNMatrix::create(output_.grad, pd);
    if (outputMap_.size() <= 1) {
      return;
    }
    std::vector<double> scales;
    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);
      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);
      scales.push_back(1.0);
    }
    auto sumPD = mkldnn::sum::primitive_desc(pd.desc(), scales, srcPDs);
    mergeGrad_.reset(new mkldnn::sum(sumPD, srcs, *out));
    pipelineBwd_.insert(pipelineBwd_.begin(), *mergeGrad_);
  }

  /**
   * reset input grad from primitive desc.
   * this function is avaiable for input is only mkldnn
   * or input do not care cpu device
   */
  virtual void resetInGrad(MKLDNNMatrixPtr& in,
                           mkldnn::memory::primitive_desc pd) {
    LayerPtr& input = inputLayers_[0];
    const MatrixPtr& grad =
        input->getOutputMapSize() > 1 ? nullptr : input->getOutput().grad;
    in = MKLDNNMatrix::create(grad, pd);
    auto arg = input->getOutput(this->getName());
    arg.grad = std::dynamic_pointer_cast<Matrix>(in);
  }

T
tensor-tang 已提交
310 311 312 313 314 315 316 317
  /**
   * 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 已提交
318

319 320 321 322 323
  /**
   * Print the mkldnn memory format flow of value
   */
  virtual void printValueFormatFlow() {
    if (inVal_ && outVal_) {
324 325
      VLOG(MKLDNN_FMTS) << inVal_->getFormat() << " >>> "
                        << outVal_->getFormat();
326
    }
T
tensor-tang 已提交
327
  }
T
tensor-tang 已提交
328

329 330 331 332 333
  /**
   * Print the mkldnn memory format flow of grad
   */
  virtual void printGradFormatFlow() {
    if (inGrad_ && outGrad_) {
334 335
      VLOG(MKLDNN_FMTS) << inGrad_->getFormat() << " <<< "
                        << outGrad_->getFormat();
336
    }
T
tensor-tang 已提交
337 338 339
  }

protected:
340
  /**
T
rename  
tensor-tang 已提交
341
   * If input only has MKLDNN device.
T
refine  
tensor-tang 已提交
342
   * Otherwise, only support the previous layer using CPU device.
343
   */
T
rename  
tensor-tang 已提交
344
  bool inputIsOnlyMKLDNN(int index = 0) {
345 346 347 348 349 350 351 352 353 354
    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 已提交
355 356 357 358
  /**
   * If output only has MKLDNN device.
   * Otherwise, other devices should only using CPU device.
   */
T
rename  
tensor-tang 已提交
359
  bool outputIsOnlyMKLDNN() {
T
refine  
tensor-tang 已提交
360 361 362 363 364 365 366
    for (size_t i = 0; i < outputOtherDevice_.size(); i++) {
      CHECK_EQ(outputOtherDevice_[i].deviceId, CPU_DEVICE)
          << "Only support other device is CPU yet";
    }
    return outputOtherDevice_.size() == 0;
  }

T
tensor-tang 已提交
367 368 369 370 371
  /**
   * Set deviceId of this layer.
   */
  void setDevice(int id) { deviceId_ = id; }

372
private:
T
tensor-tang 已提交
373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394
  /**
   * 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 已提交
395
  }
396

T
tensor-tang 已提交
397 398 399 400 401 402 403 404 405 406
  /**
   * Set output map of prev layers.
   */
  void setOutputMap() {
    outputMap_.clear();
    for (size_t i = 0; i < inputLayers_.size(); ++i) {
      inputLayers_[i]->setOutput(getName(), &tmpInArg_);
    }
  }

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
  /**
   * 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 已提交
442 443 444
};

}  // namespace paddle