MKLDNNActivation.h 8.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 19 20 21 22 23 24 25 26 27 28 29 30 31 32
/* 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 "ActivationFunction.h"
#include "mkldnn.hpp"
#include "paddle/gserver/layers/MKLDNNBase.h"
#include "paddle/math/MKLDNNMatrix.h"
#include "paddle/parameter/Argument.h"

namespace paddle {

/**
 * @brief Base class of MKLDNN Activation.
 * Common activation function are provieded,
 * including mkldnn_relu, mkldnn_elu, mkldnn_tanh, mkldnn_softmax
 */
class MKLDNNActivation : public ActivationFunction {
protected:
  // input value element count
  size_t cnt_;
33 34 35
  // should not merge the resetBwd into resetFwd,
  // because the grad data would be changing before backward.
  bool needResetBwd_;
T
tensor-tang 已提交
36 37 38
  // mkldnn matrix, primitive, stream and pipeline
  MKLDNNMatrixPtr val_;
  MKLDNNMatrixPtr grad_;
T
tensor-tang 已提交
39
  std::shared_ptr<mkldnn::engine> engine_;
T
tensor-tang 已提交
40 41 42 43 44 45 46
  std::shared_ptr<MKLDNNStream> stream_;
  std::shared_ptr<mkldnn::primitive> fwd_;
  std::shared_ptr<mkldnn::primitive> bwd_;
  std::vector<mkldnn::primitive> pipelineFwd_;
  std::vector<mkldnn::primitive> pipelineBwd_;

public:
47
  MKLDNNActivation() : cnt_(0), needResetBwd_(true) {}
T
tensor-tang 已提交
48 49 50 51
  ~MKLDNNActivation() {}
  static ActivationFunction* create(const std::string& type);
  static std::vector<std::string> getAllRegisteredTypes();
  virtual const std::string& getName() const = 0;
T
tensor-tang 已提交
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
  /**
   * reset the forward primitives
   */
  virtual void resetFwd(Argument& act) {
    VLOG(MKLDNN_BASE) << getName() << " reset mkldnn forward";
    cnt_ = act.value->getElementCnt();
    pipelineFwd_.clear();
    stream_.reset(new MKLDNNStream());
    engine_.reset(new mkldnn::engine(mkldnn::engine::cpu, 0));
    val_ = std::dynamic_pointer_cast<MKLDNNMatrix>(act.value);
    if (val_ == nullptr) {
      int bs = act.getBatchSize();
      int ih = act.getFrameHeight() > 0 ? act.getFrameHeight() : 1;
      int iw = act.getFrameWidth() > 0 ? act.getFrameWidth() : 1;
      int ic = cnt_ / bs / ih / iw;
      CHECK_EQ(cnt_, (size_t)bs * ic * ih * iw);
      val_ = MKLDNNMatrix::create(
          act.value, {bs, ic, ih, iw}, mkldnn::memory::format::nchw, *engine_);
      CHECK(val_);
      val_->downSpatial();
    }
  }
  /**
   * reset the backward primitives,
   * can not merge this functions into resetFwd as the grad data
   * would be changing before backward.
   */
  virtual void resetBwd(Argument& act) {}
  virtual Error __must_check forward(Argument& act) {
    resetFwd(act);
    stream_->submit(pipelineFwd_);
    return Error();
  }
  virtual Error __must_check backward(Argument& act) {
    resetBwd(act);
    stream_->submit(pipelineBwd_);
    return Error();
  }
T
tensor-tang 已提交
90 91 92 93 94 95 96 97 98 99
};

/**
 * @brief Base class of MKLDNN Eltwise Activation,
 * includes mkldnn_relu, mkldnn_elu and mkldnn_tanh.
 */
class MKLDNNEltwiseActivation : public MKLDNNActivation {
  typedef mkldnn::eltwise_forward eltwise_fwd;
  typedef mkldnn::eltwise_backward eltwise_bwd;

100 101 102 103 104 105 106 107
protected:
  // save the forward primitive desc, which can be used backward
  std::shared_ptr<eltwise_fwd::primitive_desc> fwdPD_;
  // eltwise_bwd need src input value
  MKLDNNMatrixPtr inVal_;
  // use for copy data
  std::shared_ptr<mkldnn::reorder> copyInVal_;

T
tensor-tang 已提交
108 109 110 111
public:
  MKLDNNEltwiseActivation() {}
  ~MKLDNNEltwiseActivation() {}
  virtual const std::string& getName() const = 0;
112 113 114

  // in common, the alpha of forward and backward should be equal.
  // but for relu, to avoid negative value, they should be opposite
T
tensor-tang 已提交
115
  virtual float getAlpha() const = 0;
116
  virtual float getBwdAlpha() const = 0;
T
tensor-tang 已提交
117
  virtual float getBeta() const { return 0.f; }
118 119 120 121 122 123 124 125 126 127 128 129
  virtual mkldnn::algorithm getAlgo(const std::string& type) const {
    if (type == "mkldnn_relu") {
      return mkldnn::algorithm::eltwise_relu;
    } else if (type == "mkldnn_tanh") {
      return mkldnn::algorithm::eltwise_tanh;
    } else if (type == "mkldnn_elu") {
      return mkldnn::algorithm::eltwise_elu;
    } else {
      LOG(FATAL) << "Unkown eltwise activation type: " << type;
    }
    return (mkldnn::algorithm)0;
  }
T
tensor-tang 已提交
130

T
tensor-tang 已提交
131
  void resetFwd(Argument& act) override {
T
tensor-tang 已提交
132 133 134
    if (cnt_ == act.value->getElementCnt()) {
      return;
    }
T
tensor-tang 已提交
135
    MKLDNNActivation::resetFwd(act);
T
tensor-tang 已提交
136 137 138
    // note: alpha represents the NegativeSlope when used in relu.
    float alpha = getAlpha();
    float beta = getBeta();
T
tensor-tang 已提交
139
    mkldnn::algorithm algo = getAlgo(this->getName());
T
tensor-tang 已提交
140 141 142 143 144
    auto fwdDesc = eltwise_fwd::desc(mkldnn::prop_kind::forward_training,
                                     algo,
                                     val_->getMemoryDesc(),
                                     alpha,
                                     beta);
T
tensor-tang 已提交
145
    fwdPD_.reset(new eltwise_fwd::primitive_desc(fwdDesc, *engine_));
146 147
    // use inplace for forward but save input value before submit
    inVal_ = val_;
148 149 150
    copyInVal_ = nullptr;
    if (act.grad && algo == mkldnn::algorithm::eltwise_tanh) {
      // tanh need save src input for backward
151 152 153 154 155 156
      inVal_ = MKLDNNMatrix::create(nullptr, val_->getPrimitiveDesc());
      copyInVal_ = std::make_shared<mkldnn::reorder>(*val_, *inVal_);
      CHECK(copyInVal_) << "should not be emptry";
      pipelineFwd_.push_back(*copyInVal_);
    }
    fwd_.reset(new eltwise_fwd(*fwdPD_, *val_, *val_));
T
tensor-tang 已提交
157
    pipelineFwd_.push_back(*fwd_);
158 159
    needResetBwd_ = true;
  }
T
tensor-tang 已提交
160

T
tensor-tang 已提交
161
  void resetBwd(Argument& act) override {
162
    if (!needResetBwd_) {
T
tensor-tang 已提交
163 164
      return;
    }
T
tensor-tang 已提交
165
    VLOG(MKLDNN_BASE) << getName() << " reset mkldnn backward";
166 167 168 169
    needResetBwd_ = false;
    mkldnn::algorithm algo = getAlgo(this->getName());
    float alpha = getBwdAlpha();
    float beta = getBeta();
T
tensor-tang 已提交
170
    grad_ = MKLDNNMatrix::create(act.grad, val_->getPrimitiveDesc());
171
    auto eng = CPUEngine::Instance().getEngine();
T
tensor-tang 已提交
172 173
    auto bwdDesc = eltwise_bwd::desc(
        algo, grad_->getMemoryDesc(), val_->getMemoryDesc(), alpha, beta);
174 175 176
    auto bwdPD = eltwise_bwd::primitive_desc(bwdDesc, eng, *fwdPD_);
    CHECK(inVal_);
    bwd_.reset(new eltwise_bwd(bwdPD, *inVal_, *grad_, *grad_));
T
tensor-tang 已提交
177 178 179
    pipelineBwd_.clear();
    pipelineBwd_.push_back(*bwd_);
  }
T
tensor-tang 已提交
180
};
T
tensor-tang 已提交
181

T
tensor-tang 已提交
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
/**
 * @brief Base class of MKLDNN softmax Activation,
 * only have mkldnn forward, use cpu implement for backward.
 */
class MKLDNNSoftmaxActivation : public MKLDNNActivation {
  typedef mkldnn::softmax_forward softmax_fwd;

private:
  // for backward
  MatrixPtr sftMaxSum_;
  MatrixPtr sftMaxDot_;

public:
  MKLDNNSoftmaxActivation() {}
  ~MKLDNNSoftmaxActivation() {}
  virtual const std::string& getName() const = 0;
  void resetFwd(Argument& act) override {
    if (cnt_ == act.value->getElementCnt()) {
      return;
    }
    MKLDNNActivation::resetFwd(act);
    int axis = 1;
    auto fwdDesc = softmax_fwd::desc(
        mkldnn::prop_kind::forward_scoring, val_->getMemoryDesc(), axis);
    auto fwdPD = softmax_fwd::primitive_desc(fwdDesc, *engine_);
    fwd_.reset(new softmax_fwd(fwdPD, *val_, *val_));
    pipelineFwd_.push_back(*fwd_);
T
tensor-tang 已提交
209 210
  }

T
tensor-tang 已提交
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
  Error __must_check backward(Argument& act) override {
    MatrixPtr outputV = act.value;
    MatrixPtr outputG = act.grad;

    if (outputG->useGpu()) {
      outputG->softmaxBackward(*outputV);
    } else {
      SetDevice device(act.deviceId);
      Matrix::resizeOrCreate(sftMaxDot_,
                             outputG->getHeight(),
                             outputG->getWidth(),
                             /* trans */ false,
                             useGpu(act.deviceId));
      Matrix::resizeOrCreate(sftMaxSum_,
                             outputG->getHeight(),
                             1,
                             /* trans */ false,
                             useGpu(act.deviceId));

      sftMaxDot_->dotMul(*outputG, *outputV);
      sftMaxSum_->colMerge(*sftMaxDot_);

      act.grad->softmaxDerivative(*act.value, *sftMaxSum_);
    }
T
tensor-tang 已提交
235 236 237 238 239
    return Error();
  }
};

}  // namespace paddle