Layer.h 13.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

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

Y
Yu Yang 已提交
17 18 19
#include <functional>
#include <memory>
#include "ModelConfig.pb.h"
H
hedaoyuan 已提交
20
#include "paddle/function/Function.h"
Y
Yu Yang 已提交
21
#include "paddle/gserver/activations/ActivationFunction.h"
Z
zhangjinchao01 已提交
22
#include "paddle/math/CpuSparseMatrix.h"
Y
Yu Yang 已提交
23
#include "paddle/parameter/Argument.h"
Z
zhangjinchao01 已提交
24
#include "paddle/parameter/Parameter.h"
Y
Yu Yang 已提交
25
#include "paddle/parameter/Weight.h"
Y
Yu Yang 已提交
26
#include "paddle/utils/ClassRegistrar.h"
Z
zhangjinchao01 已提交
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
#include "paddle/utils/Util.h"

/// Macro for registering a layer type.
/// Example: REGISTER_LAYER(crf_error, CRFDecodingErrorLayer);
#define REGISTER_LAYER(__type_name, __class_name) \
  static InitFunction __reg_type_##__type_name(   \
      []() { Layer::registrar_.registerClass<__class_name>(#__type_name); })

#define REGISTER_LAYER_CREATE_FUNC(__type_name, createFunction) \
  static InitFunction __reg_type_##__type_name(                 \
      []() { Layer::registrar_.registerClass(#__type_name, createFunction); })

namespace paddle {

class Layer;
typedef std::shared_ptr<Layer> LayerPtr;
typedef std::map<std::string, LayerPtr> LayerMap;
class NeuralNetwork;

/// layer state, used for RNN and LSTM layers
struct LayerState {
  std::vector<MatrixPtr> value;
};
typedef std::shared_ptr<LayerState> LayerStatePtr;

52 53 54 55 56 57
/// Paddle device ID, MKLDNN is -2, CPU is -1
enum PADDLE_DEVICE_ID {
  MKLDNN_DEVICE = -2,
  CPU_DEVICE = -1,
};

Z
zhangjinchao01 已提交
58 59 60 61 62 63 64 65 66 67
/**
 * @brief Base class for layer.
 * Define necessary variables and functions for every layer.
 */
class Layer {
protected:
  /// Layer config
  LayerConfig config_;
  /// whether to use GPU
  bool useGpu_;
T
tensor-tang 已提交
68
  /// Device Id. MKLDNN is -2, CPU is -1, and GPU is 0, 1, 2 ...
Z
zhangjinchao01 已提交
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
  int deviceId_;
  /// Input layers
  std::vector<LayerPtr> inputLayers_;
  /// Argument of input layers
  std::vector<std::string> inputArgument_;

  /// Parameter for each input layer.
  /// Parameters_[i] is nullptr if inputLayers_[i] does not need parameter.
  std::vector<ParameterPtr> parameters_;

  /// nullptr if bias is not needed.
  ParameterPtr biasParameter_;

  /// Output
  Argument output_;
  /// Several outputs stored on different devices, used in 'parallel_nn' case,
  /// and record them by deviceId_.
86
  /// Also used in 'use_mkldnn' case.
Z
zhangjinchao01 已提交
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
  std::vector<Argument> outputOtherDevice_;
  /// If there are several outputs, map them by each name.
  std::map<std::string, Argument*> outputMap_;
  /// Used to merge grad on different devices.
  MatrixPtr tmpGrad_;

  std::unique_ptr<ActivationFunction> activation_;

  /// Current passType, PASS_TRAIN or PASS_TEST
  PassType passType_;

  /// Random 0-1 matrix for dropOut
  MatrixPtr dropOutMask_;

  /// Whether the layer need to compute gradient
  bool needGradient_;
  /// Whether the layer need to compute re-sequence information
  bool needSequenceInfo_;

  /// Mark input grad in(true) or out(false) of backward function.
  std::vector<bool> markInBackward_;

H
hedaoyuan 已提交
109
  /// Layer forward function
H
hedaoyuan 已提交
110
  std::vector<std::shared_ptr<FunctionBase>> forward_;
H
hedaoyuan 已提交
111
  /// Layer backward function
H
hedaoyuan 已提交
112
  std::vector<std::shared_ptr<FunctionBase>> backward_;
H
hedaoyuan 已提交
113

Z
zhangjinchao01 已提交
114 115
public:
  /**
L
liaogang 已提交
116 117 118
   * Wait until all input value ready.
   * Called before Layer::forward() function.
   */
Z
zhangjinchao01 已提交
119 120 121
  virtual void waitInputValue();

  /**
122
   * Copy layer's output_ to other device.
Z
zhangjinchao01 已提交
123 124 125 126 127
   * If output layer is in other device, called after Layer::forward() function.
   */
  virtual void copyOutputToOtherDevice();

  /**
L
liaogang 已提交
128 129 130
   * Wait until all output grad ready and merge them to output_.grad.
   * Called before Layer::backward() function.
   */
Z
zhangjinchao01 已提交
131 132 133 134 135 136 137 138 139
  virtual void waitAndMergeOutputGrad();

  /**
   * Notify previous layer the output grad ready.
   * Called after Layer::backward() function.
   */
  virtual void markAllInputGrad();

protected:
H
hedaoyuan 已提交
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
  /**
   * Create layer function. Function is called in forward or backward.
   * \param function, Layer::forward_ or Layer::backward_
   * \param name, function name
   * \param config, initialization configuration for the function
   */
  void createFunction(std::vector<std::shared_ptr<FunctionBase>>& function,
                      const std::string& name,
                      const FuncConfig& config) {
    if (useGpu_) {
      function.emplace_back(
          FunctionBase::funcRegistrar_.createByType(name + "-GPU"));
    } else {
      function.emplace_back(
          FunctionBase::funcRegistrar_.createByType(name + "-CPU"));
    }
    auto& func = function.back();
    func->init(config);
  }

Z
zhangjinchao01 已提交
160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
  /**
   * Notify specified layer the output grad ready.
   * Called in the backward function.
   * If do mark input grad in the backward function, you should to ensure
   * that all input grad will be marked in the backward function.
   */
  void markInputGrad(int inputIndex);

  /**
   * Get the argument of input layer.
   */
  const Argument& getInput(size_t inputIndex) const {
    return inputLayers_[inputIndex]->getOutput(deviceId_);
  }

  /**
   * Get the argument of input layer.
   */
  const Argument& getInput(const Layer& inputLayer) const {
    return inputLayer.getOutput(deviceId_);
  }

182 183 184 185 186 187 188
  /**
   * Get the argument of input layer with deviceId.
   */
  const Argument& getInput(size_t inputIndex, int deviceId) const {
    return inputLayers_[inputIndex]->getOutput(deviceId);
  }

Z
zhangjinchao01 已提交
189 190 191 192 193 194 195 196 197 198 199 200 201 202
  /**
   * Get the forward-input value.
   */
  const MatrixPtr& getInputValue(int inputIndex) {
    return inputLayers_[inputIndex]->getOutput(deviceId_).value;
  }

  /**
   * Get the forward-input value.
   */
  const MatrixPtr& getInputValue(const Layer& inputLayer) {
    return inputLayer.getOutput(deviceId_).value;
  }

203 204 205 206 207 208 209
  /**
   * Get the forward-input value with deviceId.
   */
  const MatrixPtr& getInputValue(int inputIndex, int deviceId) {
    return inputLayers_[inputIndex]->getOutput(deviceId).value;
  }

Z
zhangjinchao01 已提交
210 211 212 213 214 215 216 217 218 219 220 221 222 223
  /**
   * Get the forward-input grad.
   */
  const MatrixPtr& getInputGrad(int inputIndex) {
    return inputLayers_[inputIndex]->getOutput(deviceId_).grad;
  }

  /**
   * Get the forward-input grad.
   */
  const MatrixPtr& getInputGrad(const Layer& inputLayer) {
    return inputLayer.getOutput(deviceId_).grad;
  }

224 225 226 227 228 229 230
  /**
   * Get the forward-input grad.
   */
  const MatrixPtr& getInputGrad(int inputIndex, int deviceId) {
    return inputLayers_[inputIndex]->getOutput(deviceId).grad;
  }

Z
zhangjinchao01 已提交
231 232 233 234 235 236 237 238 239 240 241 242
  /**
   * Get the forward-input label.
   */
  const IVectorPtr& getInputLabel(const Layer& inputLayer) {
    return inputLayer.getOutput(deviceId_).ids;
  }

  /**
   * Change the size of output (value, grad).
   * Reset to value zero if isValueClean = true,
   * Reset to grad zero if isGradClean = true.
   */
243 244 245 246 247
  void resetSpecifyOutput(Argument& output,
                          size_t height,
                          size_t width,
                          bool isValueClean,
                          bool isGradClean);
Z
zhangjinchao01 已提交
248 249 250 251 252 253 254 255 256 257 258 259 260

  /**
   * Add output argument to other devices.
   */
  void addOutputArgument(int deviceId);

public:
  explicit Layer(const LayerConfig& config, bool useGpu = FLAGS_use_gpu);
  virtual ~Layer() {}

  /// Register a Layer
  static ClassRegistrar<Layer, LayerConfig> registrar_;

261
  /**
Z
zhangjinchao01 已提交
262 263 264 265
   * Get the flag whether layer need to compute gradient.
   */
  bool needGradient() const { return needGradient_; }

266
  /**
Z
zhangjinchao01 已提交
267 268 269 270
   * Set the flag whether layer need to compute gradient.
   */
  void setNeedGradient(bool need) { needGradient_ = need; }

271
  /**
Z
zhangjinchao01 已提交
272 273 274 275 276
   * Set the flag whether layer need to re-compute sequence information,
   * which includes sequenceStartPositions or subSequenceStartPositions.
   */
  void setNeedSequenceInfo(bool need) { needSequenceInfo_ = need; }

277
  /**
Z
zhangjinchao01 已提交
278 279 280 281
   * Get layer's name.
   */
  const std::string& getName() const { return config_.name(); }

282
  /**
Z
zhangjinchao01 已提交
283 284 285 286
   * Get layer's type.
   */
  const std::string& getType() const { return config_.type(); }

287
  /**
Z
zhangjinchao01 已提交
288 289 290 291
   * Get layer's size.
   */
  size_t getSize() const { return config_.size(); }

292
  /**
Z
zhangjinchao01 已提交
293 294 295 296
   * Get layer's deviceId.
   */
  int getDeviceId() const { return deviceId_; }

297
  /**
Z
zhangjinchao01 已提交
298 299 300 301
   * Add the inputLayer.
   */
  void addPrev(LayerPtr l) { inputLayers_.push_back(l); }

302
  /**
Z
zhangjinchao01 已提交
303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321
   * Get the size of inputLayer[i].
   */
  const LayerPtr& getPrev(size_t i) { return inputLayers_[i]; }

  /**
   * Get the forward-output value.
   */
  const MatrixPtr& getOutputValue() { return output_.value; }

  /**
   * Get the forward-output label.
   */
  const IVectorPtr& getOutputLabel() { return output_.ids; }

  /**
   * Get the backward-Loss value.
   */
  const MatrixPtr& getOutputGrad() { return output_.grad; }
  /**
322
   * If layer has multi-output, set output into outputMap_.
Z
zhangjinchao01 已提交
323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339
   */
  void setOutput(const std::string& name, Argument* output) {
    outputMap_[name] = output;
  }

  /**
   * Get the output based on layer's name.
   */
  Argument& getOutput(const std::string& str = "") {
    if (str == "") {
      return output_;
    } else {
      auto output = outputMap_.find(str);
      if (output != outputMap_.end()) {
        return *output->second;
      } else {
        LOG(FATAL) << "No specific output " << str;
340
        return *((Argument*)nullptr);
Z
zhangjinchao01 已提交
341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408
      }
    }
  }

  /**
   * Get the output based on deviceId.
   */
  const Argument& getOutput(int deviceId) const {
    if (deviceId == getDeviceId()) {
      return output_;
    } else {
      for (size_t i = 0; i < outputOtherDevice_.size(); i++) {
        if (outputOtherDevice_[i].deviceId == deviceId) {
          return outputOtherDevice_[i];
        }
      }

      LOG(FATAL) << "No specific device output ";
      return *((Argument*)nullptr);
    }
  }

  /**
   * Get layer's parameters.
   */
  const std::vector<ParameterPtr>& getParameters() { return parameters_; }

  /**
   * Get layer's bias-parameters.
   */
  const ParameterPtr& getBiasParameter() { return biasParameter_; }

  /**
   * Create pointer of layer.
   */
  static LayerPtr create(const LayerConfig& config);

  /**
   * Resize the output matrix size.
   */
  void resizeOutput(size_t height, size_t width);

  /**
   * Resize the output matrix size,
   * and reset value to zero.
   */
  void reserveOutput(size_t height, size_t width);

  /**
   * Resize the output matrix size,
   * and reset value and grad to zero.
   */
  void resetOutput(size_t height, size_t width);

  /**
   * Clear the gradient of output.
   */
  void zeroGrad();

  /**
   * Intialization.
   * For example, adding input layers from layerMap and parameterMap.
   */
  virtual bool init(const LayerMap& layerMap, const ParameterMap& parameterMap);

  /**
   * Intialization for sub network if there has sub network.
   * @param rootNetwork root network
409 410
   * @param config model config
   * @param parameterTypes parameter's type
Z
zhangjinchao01 已提交
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 442 443 444 445 446 447 448
   * @param useGpu whether to use gpu or not
   */
  virtual void initSubNetwork(NeuralNetwork* rootNetwork,
                              const ModelConfig& config,
                              const std::vector<ParameterType>& parameterTypes,
                              bool useGpu) {}

  /**
   * @brief Access SubNetwork Object.
   *        If subnetwork exists, then invoke callback with subnetwrk.
   * @param callback if sub-network is exist, the callback is invoked.
   */
  virtual void accessSubNetwork(
      const std::function<void(NeuralNetwork&)>& callback) {}

  /**
   * If use sparse row matrix as parameter,
   * prefetch feature ids in input label.
   */
  virtual void prefetch() {}

  /**
   * Forward propagation.
   * All inherited implementation should call Layer::foward() function.
   */
  virtual void forward(PassType passType) {
    passType_ = passType;
    if (!inputLayers_.empty() && needSequenceInfo_) {
      const Argument& input = getInput(0);
      output_.sequenceStartPositions = input.sequenceStartPositions;
      output_.subSequenceStartPositions = input.subSequenceStartPositions;
      output_.cpuSequenceDims = input.cpuSequenceDims;
    }
  }

  /**
   * Reset the internal state variables.
   * Allocate them if they have not been allocated.
449 450
   * This function need to called before Layer::forward() for generating
   * sequence.
Z
zhangjinchao01 已提交
451 452 453 454 455 456 457 458 459 460 461 462 463 464 465
   *
   * This is used for sequence generation. When generating sequence, the
   * calculation at current timestamp depends on the state from previous
   * timestamp. The model needs to keep the information about the previous
   * timestamp in the state variables. Layers such as RecurrentLayer,
   * LstmLayer and ContextLayer have state variables.
   */
  virtual void resetState() {}

  /**
   * Set layer state.
   */
  virtual void setState(LayerStatePtr state) {}

  /**
466
   * Get layer state.
Z
zhangjinchao01 已提交
467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506
   * @return A copy of internal state.
   */
  virtual LayerStatePtr getState() { return nullptr; }

  /**
   * Show output state.
   */
  void showOutputStats();

  /**
   * Backward propagation.
   * Should only be called after Layer::forward() function.
   */
  virtual void backward(const UpdateCallback& callback = nullptr) = 0;

  /**
   * One pass is finished.
   */
  virtual void onPassEnd() {}

protected:
  /**
   * Forward of activation function.
   */
  void forwardActivation();
  /**
   * Backward of activation function.
   */
  void backwardActivation();
  /**
   * Forward of dropOut.
   */
  void forwardDropOut();
  /**
   * Initilize the needGradient_ flag.
   */
  void initNeedFlags();
};

}  // namespace paddle