ActivationFunction.cpp 10.2 KB
Newer Older
Z
zhangjinchao01 已提交
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) 2016 Baidu, Inc. 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 "ActivationFunction.h"

#include <algorithm>
#include <memory>
#include <iostream>
#include <type_traits>
#include <string>
#include <thread>
#include "paddle/utils/ClassRegistrar.h"
#include "paddle/parameter/Argument.h"

#include "paddle/utils/Logging.h"

namespace paddle {

static ClassRegistrar<ActivationFunction> gActivationRegistrar;
Q
qijun 已提交
31 32 33 34 35 36
/**
 * @def ACTIVATION_CLASS_NAME
 * @brief Macro for getting derived activation class name
 * @note ACTIVATION_CLASS_NAME(softmax) softmax_;
 * means softmaxActivation softmax_;
 */
Z
zhangjinchao01 已提交
37
#define ACTIVATION_CLASS_NAME(ACTIVATION_NAME) ACTIVATION_NAME##Activation
Q
qijun 已提交
38 39 40 41
/**
 * @def BEGIN_DEFINE_ACTIVATION
 * @brief Macro for defining a devried activation class
 */
Z
zhangjinchao01 已提交
42 43 44 45 46 47 48
#define BEGIN_DEFINE_ACTIVATION(ACTIVATION_NAME)                             \
  class ACTIVATION_CLASS_NAME(ACTIVATION_NAME) : public ActivationFunction { \
  private:                                                                   \
    static const std::string name;                                           \
                                                                             \
  public:                                                                    \
    const std::string& getName() const { return name; }
Q
qijun 已提交
49 50 51 52
/**
 * @def END_DEFINE_ACTIVATION
 * @brief Macro for registering a derived activation class
 */
Z
zhangjinchao01 已提交
53
#define END_DEFINE_ACTIVATION(ACTIVATION_NAME)                     \
54 55
  }                                                                \
  ;                                                                \
Z
zhangjinchao01 已提交
56 57 58
  const std::string ACTIVATION_CLASS_NAME(ACTIVATION_NAME)::name = \
      #ACTIVATION_NAME;                                            \
  static InitFunction __reg_activation__##ACTIVATION_NAME([] {     \
59 60 61
    gActivationRegistrar                                           \
        .registerClass<ACTIVATION_CLASS_NAME(ACTIVATION_NAME)>(    \
            #ACTIVATION_NAME);                                     \
Z
zhangjinchao01 已提交
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
  });

/**
 * @brief The IdentityActivation class
 *
 * Do nothing when forward/backward.
 */
class IdentityActivation : public ActivationFunction {
public:
  static const std::string name;
  void forward(Argument& act) { (void)act; }
  void backward(Argument& act) { (void)act; }
  const std::string& getName() const { return name; }
};
const std::string IdentityActivation::name = "";
static InitFunction __reg_activation__identity([] {
  gActivationRegistrar.registerClass<IdentityActivation>("");
  gActivationRegistrar.registerClass<IdentityActivation>("linear");
});

/**
Q
qijun 已提交
83 84
 * @brief Sigmoid Activation
 * \f[
Z
zhangjinchao01 已提交
85
 * f(z) = \frac{1}{1+exp(-z)}
Q
qijun 已提交
86
 * \f]
Z
zhangjinchao01 已提交
87 88 89 90 91 92 93
 */
BEGIN_DEFINE_ACTIVATION(sigmoid)
void forward(Argument& act) { act.value->sigmoid(*act.value); }
void backward(Argument& act) { act.grad->sigmoidDerivative(*act.value); }
END_DEFINE_ACTIVATION(sigmoid)

/**
Q
qijun 已提交
94 95
 * @brief Softmax Activation
 * \f[
Z
zhangjinchao01 已提交
96
 * P(y=j|x) = \frac{e^{x^Tw_j}}{\sum^K_{k=1}e^{x^Tw_k}}
Q
qijun 已提交
97
 * \f]
Z
zhangjinchao01 已提交
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
 */
BEGIN_DEFINE_ACTIVATION(softmax)
private:
MatrixPtr sftMaxSum_;
MatrixPtr sftMaxDot_;
MatrixPtr one_;

public:
void forward(Argument& act) { act.value->softmax(*act.value); }

void backward(Argument& act) {
  MatrixPtr outputV = act.value;
  MatrixPtr outputG = act.grad;

  if (outputG->useGpu()) {
    outputG->softmaxBackward(*outputV);
  } else {
    SetDevice device(act.deviceId);
116 117
    Matrix::resizeOrCreate(sftMaxDot_,
                           outputG->getHeight(),
Z
zhangjinchao01 已提交
118
                           outputG->getWidth(),
119 120 121 122 123 124 125
                           /* trans */ false,
                           useGpu(act.deviceId));
    Matrix::resizeOrCreate(sftMaxSum_,
                           outputG->getHeight(),
                           1,
                           /* trans */ false,
                           useGpu(act.deviceId));
Z
zhangjinchao01 已提交
126
    if (!one_ || one_->getWidth() != outputG->getWidth()) {
127 128 129 130 131
      Matrix::resizeOrCreate(one_,
                             1,
                             outputG->getWidth(),
                             /* trans */ false,
                             useGpu(act.deviceId));
Z
zhangjinchao01 已提交
132 133 134 135 136 137 138 139 140 141 142
      one_->one();
    }

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

    act.grad->softmaxDerivative(*act.value, *sftMaxSum_);
  }
}
END_DEFINE_ACTIVATION(softmax)

Q
qijun 已提交
143 144 145 146 147
/**
 * @brief Sequence_softmax Activation
 * @note Softmax on all frames of one sequence.
 * Width of frame must be one.
 */
Z
zhangjinchao01 已提交
148 149 150 151 152 153 154 155 156 157
BEGIN_DEFINE_ACTIVATION(sequence_softmax)
private:
ACTIVATION_CLASS_NAME(softmax) softmax_;
Argument argument_;

public:
void forward(Argument& act) {
  CHECK_EQ(act.value->getWidth(), 1UL);

  if (!argument_.value) {
158 159 160 161 162 163 164 165 166 167
    argument_.value = Matrix::create(nullptr,
                                     /* height= */ 1,
                                     1,
                                     /* trans= */ false,
                                     useGpu(act.deviceId));
    argument_.grad = Matrix::create(nullptr,
                                    /* height= */ 1,
                                    1,
                                    /* trans= */ false,
                                    useGpu(act.deviceId));
Z
zhangjinchao01 已提交
168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192
  }

  auto starts = act.sequenceStartPositions->getVector(useGpu(act.deviceId));
  act.value->sequenceSoftmax(*act.value, *starts);
}

void backward(Argument& act) {
  CHECK_EQ(act.grad->getWidth(), 1UL);

  size_t numSequences = act.getNumSequences();
  const int* starts = act.sequenceStartPositions->getData(false);

  for (size_t i = 0; i < numSequences; ++i) {
    // TODO(Dangqingqing) optimization for GPU
    size_t offset = starts[i];
    size_t size = starts[i + 1] - starts[i];
    argument_.value->setData(act.value->getData() + offset, 1UL, size);
    argument_.grad->setData(act.grad->getData() + offset, 1UL, size);

    softmax_.backward(argument_);
  }
}
END_DEFINE_ACTIVATION(sequence_softmax)

/**
Q
qijun 已提交
193
 * @brief Relu Activation.
Z
zhangjinchao01 已提交
194 195 196 197 198 199 200 201 202 203 204 205 206 207 208
 * forward. y = max(0, z)
 *
 * derivative of relu is:
 *
 *    1 if z > 0
 *
 *    0 otherwise.
 */
BEGIN_DEFINE_ACTIVATION(relu)
void forward(Argument& act) { act.value->relu(*act.value); }

void backward(Argument& act) { act.grad->reluDerivative(*act.value); }
END_DEFINE_ACTIVATION(relu)

/**
Q
qijun 已提交
209
 * @brief BRelu Activation.
Z
zhangjinchao01 已提交
210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
 *
 * forward. y = min(24, max(0, z))
 *
 * derivative of brelu is:
 *
 *    1 if 0 < z < 24
 *
 *    0 otherwise.
 *
 * TODO(yuyang18): Remove magic number 24 or make it configuable.
 */
BEGIN_DEFINE_ACTIVATION(brelu)
void forward(Argument& act) { act.value->brelu(*act.value); }

void backward(Argument& act) { act.grad->breluDerivative(*act.value); }
END_DEFINE_ACTIVATION(brelu)

/**
Q
qijun 已提交
228 229
 * @brief Tanh Activation.
 * \f[
Z
zhangjinchao01 已提交
230
 * f(z) = tanh(z)=\frac{e^z-e^{-z}}{e^z+e^{-z}}
Q
qijun 已提交
231
 * \f]
Z
zhangjinchao01 已提交
232 233 234 235 236 237 238 239
 */
BEGIN_DEFINE_ACTIVATION(tanh)
void forward(Argument& act) { act.value->tanh(*act.value); }

void backward(Argument& act) { act.grad->tanhDerivative(*act.value); }
END_DEFINE_ACTIVATION(tanh)

/**
Q
qijun 已提交
240 241
 * @brief Scaled Tanh Activation
 * \f[
Z
zhangjinchao01 已提交
242
 * f(z) = 1.7159 * tanh(2/3*z)
Q
qijun 已提交
243
 * \f]
Z
zhangjinchao01 已提交
244 245 246 247 248 249 250 251 252 253 254 255 256 257 258
 */
BEGIN_DEFINE_ACTIVATION(stanh)
private:
real a, b;

public:
ACTIVATION_CLASS_NAME(stanh)() : a(1.7159), b(2. / 3.) {}
void forward(Argument& act) { act.value->scaledTanh(*act.value, a, b); }

void backward(Argument& act) {
  act.grad->scaledTanhDerivative(*act.value, a, b);
}
END_DEFINE_ACTIVATION(stanh)

/**
Q
qijun 已提交
259 260
 * @brief Soft Relu Activation.
 * \f[
Z
zhangjinchao01 已提交
261
 * f(z) = ln(1+e^z)
Q
qijun 已提交
262
 * \f]
Z
zhangjinchao01 已提交
263 264 265 266 267 268 269 270
 */
BEGIN_DEFINE_ACTIVATION(softrelu)
void forward(Argument& act) { act.value->softrelu(*act.value); }

void backward(Argument& act) { act.grad->softreluDerivative(*act.value); }
END_DEFINE_ACTIVATION(softrelu)

/**
Q
qijun 已提交
271
 * @brief Abs Activation.
Z
zhangjinchao01 已提交
272 273 274 275 276 277 278 279 280 281 282 283 284
 * Forward: f(z) = abs(z)
 *
 * Derivative:
 *
 *     1   if z>0
 *
 *    -1   if z<0
 *
 *     0   if z=0
 */
BEGIN_DEFINE_ACTIVATION(abs)
void forward(Argument& act) {
  SetDevice device(act.deviceId);
285 286 287 288 289
  Matrix::resizeOrCreate(act.in,
                         act.value->getHeight(),
                         act.value->getWidth(),
                         /* trans */ false,
                         useGpu(act.deviceId));
Z
zhangjinchao01 已提交
290 291

  act.in->copyFrom(*act.value);
H
hedaoyuan 已提交
292
  act.value->abs2(*act.value);
Z
zhangjinchao01 已提交
293 294 295 296 297 298
}

void backward(Argument& act) { act.grad->absDerivative(*act.in); }
END_DEFINE_ACTIVATION(abs)

/**
Q
qijun 已提交
299 300
 * @brief Square Activation.
 * \f[
Z
zhangjinchao01 已提交
301
 * f(z) = z^2.
Q
qijun 已提交
302
 * \f]
Z
zhangjinchao01 已提交
303 304 305 306
 */
BEGIN_DEFINE_ACTIVATION(square)
void forward(Argument& act) {
  SetDevice device(act.deviceId);
307 308 309 310 311
  Matrix::resizeOrCreate(act.in,
                         act.value->getHeight(),
                         act.value->getWidth(),
                         /* trans */ false,
                         useGpu(act.deviceId));
Z
zhangjinchao01 已提交
312 313

  act.in->copyFrom(*act.value);
H
hedaoyuan 已提交
314
  act.value->square2(*act.value);
Z
zhangjinchao01 已提交
315 316 317 318
}

void backward(Argument& act) { act.grad->squareDerivative(*act.in); }
END_DEFINE_ACTIVATION(square)
319

Q
qijun 已提交
320 321 322 323 324 325
/**
 * @brief Exponential Activation.
 * \f[
 * f(z) = e^z
 * \f]
 */
Z
zhangjinchao01 已提交
326
BEGIN_DEFINE_ACTIVATION(exponential)
H
hedaoyuan 已提交
327
void forward(Argument& act) { act.value->exp2(*act.value); }
Z
zhangjinchao01 已提交
328 329 330 331

void backward(Argument& act) { act.grad->expDerivative(*act.value); }
END_DEFINE_ACTIVATION(exponential)

332 333 334 335 336 337 338 339 340
/**
 * @brief Logarithm Activation.
 * \f[
 * f(z) = log(z)
 * \f]
 */
BEGIN_DEFINE_ACTIVATION(log)
void forward(Argument& act) {
  SetDevice device(act.deviceId);
341 342 343 344 345
  Matrix::resizeOrCreate(act.in,
                         act.value->getHeight(),
                         act.value->getWidth(),
                         /* trans */ false,
                         useGpu(act.deviceId));
346 347 348 349 350 351 352 353

  act.in->copyFrom(*act.value);
  act.value->log(*act.value);
}

void backward(Argument& act) { act.grad->dotDiv(*act.grad, *act.in); }
END_DEFINE_ACTIVATION(log)

Z
zhangjinchao01 已提交
354 355 356 357
ActivationFunction* ActivationFunction::create(const std::string& type) {
  return gActivationRegistrar.createByType(type);
}

358 359
std::vector<std::string> ActivationFunction::getAllRegisteredTypes() {
  std::vector<std::string> types;
360 361
  gActivationRegistrar.forEachType(
      [&](const std::string& type) { types.push_back(type); });
362 363 364
  return types;
}

Z
zhangjinchao01 已提交
365
}  // namespace paddle