AverageLayer.cpp 2.0 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
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. */

#include "AverageLayer.h"

X
Xin Pan 已提交
17
#include "paddle/legacy/utils/Logging.h"
Z
zhangjinchao01 已提交
18

X
Xin Pan 已提交
19
#include "paddle/legacy/utils/Stat.h"
Z
zhangjinchao01 已提交
20 21 22 23 24 25 26

namespace paddle {

REGISTER_LAYER(average, AverageLayer);

bool AverageLayer::init(const LayerMap& layerMap,
                        const ParameterMap& parameterMap) {
27
  SequencePoolLayer::init(layerMap, parameterMap);
Z
zhangjinchao01 已提交
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42

  // average strategy
  if (config_.average_strategy() == "average") {
    mode_ = kAverage;
  } else if (config_.average_strategy() == "sum") {
    mode_ = kSum;
  } else if (config_.average_strategy() == "squarerootn") {
    mode_ = kAverageSquareRootN;
  } else {
    LOG(FATAL) << "Unknown average strategy: " << config_.average_strategy();
  }
  return true;
}

void AverageLayer::forward(PassType passType) {
43
  SequencePoolLayer::forward(passType);
Z
zhangjinchao01 已提交
44 45

  MatrixPtr inputValue = getInputValue(0);
46 47
  getOutputValue()->sequenceAvgForward(
      *inputValue, *startPositions_->getVector(useGpu_), mode_);
Z
zhangjinchao01 已提交
48 49 50 51 52 53 54 55 56 57 58

  /* add the bias-vector AFTER average operation */
  if (biases_.get() != NULL) {
    MatrixPtr outV = getOutputValue();
    outV->addBias(*(biases_->getW()), 1);
  }

  /* activation */ { forwardActivation(); }
}

void AverageLayer::backward(const UpdateCallback& callback) {
59
  SequencePoolLayer::backward(callback);
Z
zhangjinchao01 已提交
60

L
Luo Tao 已提交
61 62 63
  if (getInputGrad(0)) {
    getInputGrad(0)->sequenceAvgBackward(
        *getOutputGrad(), *startPositions_->getVector(useGpu_), mode_);
Z
zhangjinchao01 已提交
64 65 66 67
  }
}

}  // namespace paddle