MKLDNNFcLayer.cpp 8.5 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

T
tensor-tang 已提交
18 19 20 21 22 23
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 已提交
24 25
namespace paddle {

26
REGISTER_LAYER(mkldnn_fc, MKLDNNFcLayer);
T
tensor-tang 已提交
27

28
bool MKLDNNFcLayer::init(const LayerMap& layerMap,
T
tensor-tang 已提交
29
                         const ParameterMap& parameterMap) {
30
  if (!MKLDNNLayer::init(layerMap, parameterMap)) {
T
tensor-tang 已提交
31 32 33
    return false;
  }

T
tensor-tang 已提交
34
  CHECK_EQ(inputLayers_.size(), 1) << "Only support one input layer yet";
T
tensor-tang 已提交
35 36 37 38 39 40 41
  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;
42 43
  ih_ = 1;
  iw_ = 1;
T
tensor-tang 已提交
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59

  // 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;
}

60
void MKLDNNFcLayer::convertWeightsFromPaddle() {
T
tensor-tang 已提交
61
  if (hasInitedWgt_) {
T
tensor-tang 已提交
62 63 64
    return;
  }

T
tensor-tang 已提交
65 66 67 68 69
  CHECK(wgtVal_) << "should have been initialized";
  bool hasNoSpatial_ = ih_ == 1 && iw_ == 1;
  auto targetDim = wgtVal_->getDims();
  auto srcFmt = hasNoSpatial_ ? memory::format::io : memory::format::ihwo;
  wgtVal_->reorderDataFrom(wgtVal_, srcFmt, targetDim);
T
tensor-tang 已提交
70 71 72
  hasInitedWgt_ = true;
}

73
void MKLDNNFcLayer::convertWeightsToPaddle() {
T
tensor-tang 已提交
74 75 76 77 78
  CHECK(wgtVal_) << "should have been initialized";
  bool hasNoSpatial_ = ih_ == 1 && iw_ == 1;
  auto targetDim = wgtVal_->getDims();
  auto dstFmt = hasNoSpatial_ ? memory::format::io : memory::format::ihwo;
  wgtVal_->reorderDataTo(wgtVal_, dstFmt, targetDim);
T
tensor-tang 已提交
79 80
}

81
void MKLDNNFcLayer::reshape() {
82 83
  reshapeInput();

T
tensor-tang 已提交
84 85 86 87 88
  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());

89 90
  reshapeOutput(oh_, ow_);
  resizeOutput(bs_, oc_);
T
tensor-tang 已提交
91

92
  printSizeInfo();
T
tensor-tang 已提交
93 94
}

95
void MKLDNNFcLayer::resetFwd() {
T
tensor-tang 已提交
96
  bool hasBias = biases_ && biases_->getW();
T
tensor-tang 已提交
97 98 99 100
  const MatrixPtr& wgt = weight_->getW();
  const MatrixPtr& bias = hasBias ? biases_->getW() : nullptr;
  const MatrixPtr& out = output_.value;

T
rename  
tensor-tang 已提交
101
  if (inputIsOnlyMKLDNN()) {
102
    const MatrixPtr& in = getInputValue(0);
T
tensor-tang 已提交
103 104 105
    inVal_ = std::dynamic_pointer_cast<MKLDNNMatrix>(in);
    CHECK(inVal_) << "Input should be MKLDNNMatrix";
  } else {
106 107
    CHECK_EQ(getPrev(0)->getDeviceId(), CPU_DEVICE) << "Only support CPU yet";
    const MatrixPtr& in = getInputValue(0, CPU_DEVICE);
T
tensor-tang 已提交
108
    inVal_ = MKLDNNMatrix::create(
109
        in, memory::dims{bs_, ic_, ih_, iw_}, format::nchw, engine_);
T
tensor-tang 已提交
110
  }
111
  inVal_->downSpatial();
T
tensor-tang 已提交
112
  wgtVal_ = MKLDNNMatrix::create(
113 114
      wgt, memory::dims{oc_, ic_, ih_, iw_}, format::oihw, engine_);
  wgtVal_->downSpatial();
T
tensor-tang 已提交
115 116 117 118
  biasVal_ =
      hasBias ? MKLDNNMatrix::create(bias, {oc_}, format::x, engine_) : nullptr;
  outVal_ = MKLDNNMatrix::create(out, {bs_, oc_}, format::nc, engine_);

119
  // change original output value to mkldnn output value
T
tensor-tang 已提交
120
  output_.value = std::dynamic_pointer_cast<Matrix>(outVal_);
T
rename  
tensor-tang 已提交
121
  if (!outputIsOnlyMKLDNN()) {
T
tensor-tang 已提交
122 123 124
    // fc cpu output value do not need create convert
    // just share point
    getOutput(CPU_DEVICE).value->setData(output_.value->getData());
125
  }
T
tensor-tang 已提交
126

T
tensor-tang 已提交
127
  // create forward handle
T
tensor-tang 已提交
128
  prop_kind pk = prop_kind::forward;
T
refine  
tensor-tang 已提交
129 130 131 132 133 134 135 136 137
  fc_fwd::desc fwdDesc = hasBias ? fc_fwd::desc(pk,
                                                inVal_->getMemoryDesc(),
                                                wgtVal_->getMemoryDesc(),
                                                biasVal_->getMemoryDesc(),
                                                outVal_->getMemoryDesc())
                                 : fc_fwd::desc(pk,
                                                inVal_->getMemoryDesc(),
                                                wgtVal_->getMemoryDesc(),
                                                outVal_->getMemoryDesc());
T
tensor-tang 已提交
138
  fc_fwd::primitive_desc fwdPD = fc_fwd::primitive_desc(fwdDesc, engine_);
T
tensor-tang 已提交
139
  if (hasBias) {
T
tensor-tang 已提交
140 141 142 143
    fwd_.reset(new fc_fwd(fwdPD, *inVal_, *wgtVal_, *biasVal_, *outVal_));
  } else {
    fwd_.reset(new fc_fwd(fwdPD, *inVal_, *wgtVal_, *outVal_));
  }
144 145
  printValueFormatFlow();

T
tensor-tang 已提交
146 147 148 149
  pipelineFwd_.clear();
  pipelineFwd_.push_back(*fwd_);
}

150
void MKLDNNFcLayer::resetBwd() {
T
tensor-tang 已提交
151 152 153 154 155 156 157
  if (!needResetBwd_) {
    return;
  }
  needResetBwd_ = false;
  bool hasBias = biases_ && biases_->getWGrad();

  /// backward weight
T
tensor-tang 已提交
158 159 160 161
  CHECK(inVal_) << "Should have input value";
  const MatrixPtr& wgt = weight_->getWGrad();
  const MatrixPtr& bias = hasBias ? biases_->getWGrad() : nullptr;

T
refine  
tensor-tang 已提交
162
  // TODO(TJ): merge outgrad
T
rename  
tensor-tang 已提交
163 164 165 166 167 168 169 170 171 172
  int device = outputIsOnlyMKLDNN() ? MKLDNN_DEVICE : CPU_DEVICE;
  // for MKLDNN device:
  // can not directly cast outputgrad to mkldnnmatrix,
  // since each layer can not write the inputgrad to mkldnn inputgrad.
  // So just create from matrix with outputvalue format.
  // for CPU device:
  // fc do not need to convert from cpu device since output is always nc format
  // only need create from cpu device
  const MatrixPtr& out = getOutput(device).grad;
  outGrad_ = MKLDNNMatrix::create(out, outVal_->getPrimitiveDesc());
T
refine  
tensor-tang 已提交
173 174 175
  wgtGrad_ = MKLDNNMatrix::create(wgt, wgtVal_->getPrimitiveDesc());
  biasGrad_ = hasBias ? MKLDNNMatrix::create(bias, biasVal_->getPrimitiveDesc())
                      : nullptr;
T
tensor-tang 已提交
176 177 178

  // create memory primitive desc
  fc_fwd::desc fwdDesc = fc_fwd::desc(prop_kind::forward,
T
refine  
tensor-tang 已提交
179 180 181
                                      inVal_->getMemoryDesc(),
                                      wgtGrad_->getMemoryDesc(),
                                      outGrad_->getMemoryDesc());
T
tensor-tang 已提交
182
  fc_fwd::primitive_desc fwdPD = fc_fwd::primitive_desc(fwdDesc, engine_);
T
refine  
tensor-tang 已提交
183 184 185 186 187 188 189 190
  fc_bwdWgt::desc bwdWgtDesc = hasBias
                                   ? fc_bwdWgt::desc(inVal_->getMemoryDesc(),
                                                     wgtGrad_->getMemoryDesc(),
                                                     biasGrad_->getMemoryDesc(),
                                                     outGrad_->getMemoryDesc())
                                   : fc_bwdWgt::desc(inVal_->getMemoryDesc(),
                                                     wgtGrad_->getMemoryDesc(),
                                                     outGrad_->getMemoryDesc());
T
tensor-tang 已提交
191 192 193
  fc_bwdWgt::primitive_desc bwdWgtPD =
      fc_bwdWgt::primitive_desc(bwdWgtDesc, engine_, fwdPD);

T
tensor-tang 已提交
194
  if (hasBias) {
T
tensor-tang 已提交
195 196 197 198 199 200 201 202 203
    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
204
  const MatrixPtr& in = inputLayers_[0]->getOutput().grad;
T
refine  
tensor-tang 已提交
205 206 207
  if (in == nullptr) {
    return;
  }
208 209
  if (getInput(0, MKLDNN_DEVICE).getAllCount() > 1) {
    // TODO(TJ): use outputMaps_ ways to get the inGrad_ when merge outgrad done
210
  } else {
T
refine  
tensor-tang 已提交
211
    inGrad_ = MKLDNNMatrix::create(in, inVal_->getPrimitiveDesc());
T
tensor-tang 已提交
212
  }
213

T
refine  
tensor-tang 已提交
214 215 216
  fc_bwdData::desc bwdDataDesc = fc_bwdData::desc(inVal_->getMemoryDesc(),
                                                  wgtGrad_->getMemoryDesc(),
                                                  outGrad_->getMemoryDesc());
T
tensor-tang 已提交
217 218
  fc_bwdData::primitive_desc bwdDataPD =
      fc_bwdData::primitive_desc(bwdDataDesc, engine_, fwdPD);
T
tensor-tang 已提交
219

T
tensor-tang 已提交
220 221
  CHECK(wgtVal_) << "Should have weight memory";
  bwdData_.reset(new fc_bwdData(bwdDataPD, *outGrad_, *wgtVal_, *inGrad_));
222
  printGradFormatFlow();
T
tensor-tang 已提交
223
  pipelineBwd_.push_back(*bwdData_);
T
tensor-tang 已提交
224 225
}

226
void MKLDNNFcLayer::updateInputData() {
227
  inVal_->setData(getInputValue(0, CPU_DEVICE)->getData());
T
tensor-tang 已提交
228 229
}

230 231 232 233
void MKLDNNFcLayer::updateWeights(const UpdateCallback& callback) {
  weight_->getParameterPtr()->incUpdate(callback);
  if (biases_ && biases_->getWGrad()) {
    biases_->getParameterPtr()->incUpdate(callback);
T
tensor-tang 已提交
234
  }
T
tensor-tang 已提交
235
}
T
tensor-tang 已提交
236
}  // namespace paddle