ActivationFunction.cpp 11.4 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.
Z
zhangjinchao01 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18

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 <iostream>
Y
Yu Yang 已提交
19
#include <memory>
Z
zhangjinchao01 已提交
20 21
#include <string>
#include <thread>
Y
Yu Yang 已提交
22
#include <type_traits>
Z
zhangjinchao01 已提交
23
#include "paddle/parameter/Argument.h"
Y
Yu Yang 已提交
24
#include "paddle/utils/ClassRegistrar.h"
Z
zhangjinchao01 已提交
25 26 27 28 29 30

#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
  });

/**
 * @brief The IdentityActivation class
 *
 * Do nothing when forward/backward.
 */
class IdentityActivation : public ActivationFunction {
public:
  static const std::string name;
72
  Status __must_check forward(Argument& act) {
73 74 75
    (void)act;
    return Status();
  }
76
  Status __must_check backward(Argument& act) {
77 78 79
    (void)act;
    return Status();
  }
Z
zhangjinchao01 已提交
80 81 82 83 84 85 86 87 88
  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 已提交
89 90
 * @brief Sigmoid Activation
 * \f[
Z
zhangjinchao01 已提交
91
 * f(z) = \frac{1}{1+exp(-z)}
Q
qijun 已提交
92
 * \f]
Z
zhangjinchao01 已提交
93 94
 */
BEGIN_DEFINE_ACTIVATION(sigmoid)
95
Status __must_check forward(Argument& act) {
96 97 98
  act.value->sigmoid(*act.value);
  return Status();
}
99
Status __must_check backward(Argument& act) {
100 101 102
  act.grad->sigmoidDerivative(*act.value);
  return Status();
}
Z
zhangjinchao01 已提交
103 104 105
END_DEFINE_ACTIVATION(sigmoid)

/**
Q
qijun 已提交
106 107
 * @brief Softmax Activation
 * \f[
Z
zhangjinchao01 已提交
108
 * P(y=j|x) = \frac{e^{x^Tw_j}}{\sum^K_{k=1}e^{x^Tw_k}}
Q
qijun 已提交
109
 * \f]
Z
zhangjinchao01 已提交
110 111 112 113 114 115 116 117
 */
BEGIN_DEFINE_ACTIVATION(softmax)
private:
MatrixPtr sftMaxSum_;
MatrixPtr sftMaxDot_;
MatrixPtr one_;

public:
118
Status __must_check forward(Argument& act) {
119 120 121
  act.value->softmax(*act.value);
  return Status();
}
Z
zhangjinchao01 已提交
122

123
Status __must_check backward(Argument& act) {
Z
zhangjinchao01 已提交
124 125 126 127 128 129 130
  MatrixPtr outputV = act.value;
  MatrixPtr outputG = act.grad;

  if (outputG->useGpu()) {
    outputG->softmaxBackward(*outputV);
  } else {
    SetDevice device(act.deviceId);
131 132
    Matrix::resizeOrCreate(sftMaxDot_,
                           outputG->getHeight(),
Z
zhangjinchao01 已提交
133
                           outputG->getWidth(),
134 135 136 137 138 139 140
                           /* trans */ false,
                           useGpu(act.deviceId));
    Matrix::resizeOrCreate(sftMaxSum_,
                           outputG->getHeight(),
                           1,
                           /* trans */ false,
                           useGpu(act.deviceId));
Z
zhangjinchao01 已提交
141
    if (!one_ || one_->getWidth() != outputG->getWidth()) {
142 143 144 145 146
      Matrix::resizeOrCreate(one_,
                             1,
                             outputG->getWidth(),
                             /* trans */ false,
                             useGpu(act.deviceId));
Z
zhangjinchao01 已提交
147 148 149 150 151 152 153 154
      one_->one();
    }

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

    act.grad->softmaxDerivative(*act.value, *sftMaxSum_);
  }
155
  return Status();
Z
zhangjinchao01 已提交
156 157 158
}
END_DEFINE_ACTIVATION(softmax)

Q
qijun 已提交
159 160 161 162 163
/**
 * @brief Sequence_softmax Activation
 * @note Softmax on all frames of one sequence.
 * Width of frame must be one.
 */
Z
zhangjinchao01 已提交
164 165 166 167 168 169
BEGIN_DEFINE_ACTIVATION(sequence_softmax)
private:
ACTIVATION_CLASS_NAME(softmax) softmax_;
Argument argument_;

public:
170
Status __must_check forward(Argument& act) {
171 172 173 174
  if (act.value->getWidth() != 1UL) {
    return Status(
        "Input width for each timestep of sequence softmax should be 1");
  }
Z
zhangjinchao01 已提交
175 176

  if (!argument_.value) {
177 178 179 180 181 182 183 184 185 186
    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 已提交
187 188 189 190
  }

  auto starts = act.sequenceStartPositions->getVector(useGpu(act.deviceId));
  act.value->sequenceSoftmax(*act.value, *starts);
191
  return Status();
Z
zhangjinchao01 已提交
192 193
}

194
Status __must_check backward(Argument& act) {
195 196 197 198
  if (act.value->getWidth() != 1UL) {
    return Status(
        "Input width for each timestep of sequence softmax should be 1");
  }
Z
zhangjinchao01 已提交
199 200 201 202 203 204 205 206 207 208 209

  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);

210 211
    Status status = softmax_.backward(argument_);
    if (!status.isOK()) return status;
Z
zhangjinchao01 已提交
212
  }
213
  return Status();
Z
zhangjinchao01 已提交
214 215 216 217
}
END_DEFINE_ACTIVATION(sequence_softmax)

/**
Q
qijun 已提交
218
 * @brief Relu Activation.
Z
zhangjinchao01 已提交
219 220 221 222 223 224 225 226 227
 * forward. y = max(0, z)
 *
 * derivative of relu is:
 *
 *    1 if z > 0
 *
 *    0 otherwise.
 */
BEGIN_DEFINE_ACTIVATION(relu)
228
Status __must_check forward(Argument& act) {
229 230 231
  act.value->relu(*act.value);
  return Status();
}
Z
zhangjinchao01 已提交
232

233
Status __must_check backward(Argument& act) {
234 235 236
  act.grad->reluDerivative(*act.value);
  return Status();
}
Z
zhangjinchao01 已提交
237 238 239
END_DEFINE_ACTIVATION(relu)

/**
Q
qijun 已提交
240
 * @brief BRelu Activation.
Z
zhangjinchao01 已提交
241 242 243 244 245 246 247 248 249 250 251 252
 *
 * 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)
253
Status __must_check forward(Argument& act) {
254 255 256
  act.value->brelu(*act.value);
  return Status();
}
Z
zhangjinchao01 已提交
257

258
Status __must_check backward(Argument& act) {
259 260 261
  act.grad->breluDerivative(*act.value);
  return Status();
}
Z
zhangjinchao01 已提交
262 263 264
END_DEFINE_ACTIVATION(brelu)

/**
Q
qijun 已提交
265 266
 * @brief Tanh Activation.
 * \f[
Z
zhangjinchao01 已提交
267
 * f(z) = tanh(z)=\frac{e^z-e^{-z}}{e^z+e^{-z}}
Q
qijun 已提交
268
 * \f]
Z
zhangjinchao01 已提交
269 270
 */
BEGIN_DEFINE_ACTIVATION(tanh)
271
Status __must_check forward(Argument& act) {
272 273 274
  act.value->tanh(*act.value);
  return Status();
}
Z
zhangjinchao01 已提交
275

276
Status __must_check backward(Argument& act) {
277 278 279
  act.grad->tanhDerivative(*act.value);
  return Status();
}
Z
zhangjinchao01 已提交
280 281 282
END_DEFINE_ACTIVATION(tanh)

/**
Q
qijun 已提交
283 284
 * @brief Scaled Tanh Activation
 * \f[
Z
zhangjinchao01 已提交
285
 * f(z) = 1.7159 * tanh(2/3*z)
Q
qijun 已提交
286
 * \f]
Z
zhangjinchao01 已提交
287 288 289 290 291 292 293
 */
BEGIN_DEFINE_ACTIVATION(stanh)
private:
real a, b;

public:
ACTIVATION_CLASS_NAME(stanh)() : a(1.7159), b(2. / 3.) {}
294
Status __must_check forward(Argument& act) {
295 296 297
  act.value->scaledTanh(*act.value, a, b);
  return Status();
}
Z
zhangjinchao01 已提交
298

299
Status __must_check backward(Argument& act) {
Z
zhangjinchao01 已提交
300
  act.grad->scaledTanhDerivative(*act.value, a, b);
301
  return Status();
Z
zhangjinchao01 已提交
302 303 304 305
}
END_DEFINE_ACTIVATION(stanh)

/**
Q
qijun 已提交
306 307
 * @brief Soft Relu Activation.
 * \f[
Z
zhangjinchao01 已提交
308
 * f(z) = ln(1+e^z)
Q
qijun 已提交
309
 * \f]
Z
zhangjinchao01 已提交
310 311
 */
BEGIN_DEFINE_ACTIVATION(softrelu)
312
Status __must_check forward(Argument& act) {
313 314 315
  act.value->softrelu(*act.value);
  return Status();
}
Z
zhangjinchao01 已提交
316

317
Status __must_check backward(Argument& act) {
318 319 320
  act.grad->softreluDerivative(*act.value);
  return Status();
}
Z
zhangjinchao01 已提交
321 322 323
END_DEFINE_ACTIVATION(softrelu)

/**
Q
qijun 已提交
324
 * @brief Abs Activation.
Z
zhangjinchao01 已提交
325 326 327 328 329 330 331 332 333 334 335
 * Forward: f(z) = abs(z)
 *
 * Derivative:
 *
 *     1   if z>0
 *
 *    -1   if z<0
 *
 *     0   if z=0
 */
BEGIN_DEFINE_ACTIVATION(abs)
336
Status __must_check forward(Argument& act) {
Z
zhangjinchao01 已提交
337
  SetDevice device(act.deviceId);
338 339 340 341 342
  Matrix::resizeOrCreate(act.in,
                         act.value->getHeight(),
                         act.value->getWidth(),
                         /* trans */ false,
                         useGpu(act.deviceId));
Z
zhangjinchao01 已提交
343 344

  act.in->copyFrom(*act.value);
H
hedaoyuan 已提交
345
  act.value->abs2(*act.value);
346
  return Status();
Z
zhangjinchao01 已提交
347 348
}

349
Status __must_check backward(Argument& act) {
350 351 352
  act.grad->absDerivative(*act.in);
  return Status();
}
Z
zhangjinchao01 已提交
353 354 355
END_DEFINE_ACTIVATION(abs)

/**
Q
qijun 已提交
356 357
 * @brief Square Activation.
 * \f[
Z
zhangjinchao01 已提交
358
 * f(z) = z^2.
Q
qijun 已提交
359
 * \f]
Z
zhangjinchao01 已提交
360 361
 */
BEGIN_DEFINE_ACTIVATION(square)
362
Status __must_check forward(Argument& act) {
Z
zhangjinchao01 已提交
363
  SetDevice device(act.deviceId);
364 365 366 367 368
  Matrix::resizeOrCreate(act.in,
                         act.value->getHeight(),
                         act.value->getWidth(),
                         /* trans */ false,
                         useGpu(act.deviceId));
Z
zhangjinchao01 已提交
369 370

  act.in->copyFrom(*act.value);
H
hedaoyuan 已提交
371
  act.value->square2(*act.value);
372
  return Status();
Z
zhangjinchao01 已提交
373 374
}

375
Status __must_check backward(Argument& act) {
376 377 378
  act.grad->squareDerivative(*act.in);
  return Status();
}
Z
zhangjinchao01 已提交
379
END_DEFINE_ACTIVATION(square)
380

Q
qijun 已提交
381 382 383 384 385 386
/**
 * @brief Exponential Activation.
 * \f[
 * f(z) = e^z
 * \f]
 */
Z
zhangjinchao01 已提交
387
BEGIN_DEFINE_ACTIVATION(exponential)
388
Status __must_check forward(Argument& act) {
389 390 391
  act.value->exp2(*act.value);
  return Status();
}
Z
zhangjinchao01 已提交
392

393
Status __must_check backward(Argument& act) {
394 395 396
  act.grad->expDerivative(*act.value);
  return Status();
}
Z
zhangjinchao01 已提交
397 398
END_DEFINE_ACTIVATION(exponential)

399 400 401 402 403 404 405
/**
 * @brief Logarithm Activation.
 * \f[
 * f(z) = log(z)
 * \f]
 */
BEGIN_DEFINE_ACTIVATION(log)
406
Status __must_check forward(Argument& act) {
407
  SetDevice device(act.deviceId);
408 409 410 411 412
  Matrix::resizeOrCreate(act.in,
                         act.value->getHeight(),
                         act.value->getWidth(),
                         /* trans */ false,
                         useGpu(act.deviceId));
413 414

  act.in->copyFrom(*act.value);
H
hedaoyuan 已提交
415
  act.value->log2(*act.value);
416
  return Status();
417 418
}

419
Status __must_check backward(Argument& act) {
420 421 422
  act.grad->dotDiv(*act.grad, *act.in);
  return Status();
}
423 424
END_DEFINE_ACTIVATION(log)

Z
zhangjinchao01 已提交
425 426 427 428
ActivationFunction* ActivationFunction::create(const std::string& type) {
  return gActivationRegistrar.createByType(type);
}

429 430
std::vector<std::string> ActivationFunction::getAllRegisteredTypes() {
  std::vector<std::string> types;
431 432
  gActivationRegistrar.forEachType(
      [&](const std::string& type) { types.push_back(type); });
433 434 435
  return types;
}

Z
zhangjinchao01 已提交
436
}  // namespace paddle