ConcatenateLayer.cpp 5.8 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 "Layer.h"
#include "Projection.h"
X
Xin Pan 已提交
17
#include "paddle/legacy/utils/Stat.h"
Z
zhangjinchao01 已提交
18 19 20 21 22 23 24 25

namespace paddle {

/**
 * A concatenate layer has multiple input layers. It concatenates rows of
 * each input as one row for the output of this layer and apply activation.
 */
class ConcatenateLayer : public Layer {
W
Wu Yi 已提交
26
 public:
Z
zhangjinchao01 已提交
27 28 29 30
  explicit ConcatenateLayer(const LayerConfig& config) : Layer(config) {}

  ~ConcatenateLayer() {}

Y
Yu Yang 已提交
31 32
  bool init(const LayerMap& layerMap,
            const ParameterMap& parameterMap) override;
Z
zhangjinchao01 已提交
33

Y
Yu Yang 已提交
34 35
  void forward(PassType passType) override;
  void backward(const UpdateCallback& callback = nullptr) override;
Z
zhangjinchao01 已提交
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 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 90 91 92 93 94 95 96 97 98 99
};

REGISTER_LAYER(concat, ConcatenateLayer);

bool ConcatenateLayer::init(const LayerMap& layerMap,
                            const ParameterMap& parameterMap) {
  /* Initialize the basic parent class */
  if (!Layer::init(layerMap, parameterMap)) return false;

  CHECK(!biasParameter_);

  return true;
}

void ConcatenateLayer::forward(PassType passType) {
  Layer::forward(passType);

  int batchSize = getInput(0).getBatchSize();
  int size = getSize();
  reserveOutput(batchSize, size);

  const MatrixPtr& out = getOutputValue();
  int offset = 0;

  for (size_t i = 0; i != inputLayers_.size(); ++i) {
    const MatrixPtr& in = getInputValue(i);
    size_t inSize = in->getWidth();
    out->assignAtOffset(*in, offset);
    offset += inSize;
  }
  CHECK_EQ(size, offset);

  /* activation */ {
    REGISTER_TIMER_INFO("FwAtvTimer", getName().c_str());
    forwardActivation();
  }
}

void ConcatenateLayer::backward(const UpdateCallback& callback) {
  (void)callback;

  /* Do activation */ {
    REGISTER_TIMER_INFO("BpAvtTimer", getName().c_str());
    backwardActivation();
  }

  const MatrixPtr& out = getOutputGrad();
  int offset = 0;

  for (size_t i = 0; i != inputLayers_.size(); ++i) {
    const MatrixPtr& in = getInputGrad(i);
    size_t inSize = getInputValue(i)->getWidth();
    if (in) {
      in->addAtOffset(*out, offset);
    }
    offset += inSize;
  }
}

/**
 * concat2 layer is like concat layer, but each input layer was
 * processed by a Projection.
 */
class ConcatenateLayer2 : public Layer {
W
Wu Yi 已提交
100
 public:
101
  explicit ConcatenateLayer2(const LayerConfig& config) : Layer(config) {}
Z
zhangjinchao01 已提交
102 103 104

  ~ConcatenateLayer2() {}

Y
Yu Yang 已提交
105 106
  bool init(const LayerMap& layerMap,
            const ParameterMap& parameterMap) override;
Z
zhangjinchao01 已提交
107

Y
Yu Yang 已提交
108 109
  void forward(PassType passType) override;
  void backward(const UpdateCallback& callback = nullptr) override;
Z
zhangjinchao01 已提交
110

W
Wu Yi 已提交
111
 protected:
Z
zhangjinchao01 已提交
112 113 114
  std::vector<std::unique_ptr<Projection>> projections_;
  std::vector<Argument> projOutput_;
  std::vector<std::pair<size_t, size_t>> projCol_;
115 116
  bool sharedBias_;
  std::unique_ptr<Weight> biases_;
Z
zhangjinchao01 已提交
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
};

REGISTER_LAYER(concat2, ConcatenateLayer2);

bool ConcatenateLayer2::init(const LayerMap& layerMap,
                             const ParameterMap& parameterMap) {
  /* Initialize the basic parent class */
  if (!Layer::init(layerMap, parameterMap)) return false;

  CHECK_EQ(inputLayers_.size(), parameters_.size());
  projections_.reserve(inputLayers_.size());
  projCol_.reserve(inputLayers_.size());
  projOutput_.resize(inputLayers_.size());

  size_t startCol = 0;
  size_t endCol = 0;
  for (size_t i = 0; i < inputLayers_.size(); i++) {
134 135
    projections_.emplace_back(Projection::create(
        config_.inputs(i).proj_conf(), parameters_[i], useGpu_));
Z
zhangjinchao01 已提交
136 137 138 139 140 141 142

    endCol += projections_[i]->getOutputSize();
    projCol_.push_back(std::make_pair(startCol, endCol));
    startCol = endCol;
  }
  CHECK_EQ(getSize(), endCol);

143 144 145 146 147 148 149
  /* initialize biases_ */
  if (biasParameter_.get() != NULL) {
    sharedBias_ = config_.shared_biases();
    size_t psize = config_.bias_size();
    biases_ = std::unique_ptr<Weight>(new Weight(1, psize, biasParameter_));
  }

Z
zhangjinchao01 已提交
150 151 152 153 154 155 156 157 158 159 160 161 162 163
  return true;
}

void ConcatenateLayer2::forward(PassType passType) {
  Layer::forward(passType);

  int batchSize = getInput(0).getBatchSize();
  int size = getSize();
  resetOutput(batchSize, size);

  for (size_t i = 0; i < projections_.size(); i++) {
    size_t startCol = projCol_[i].first;
    size_t endCol = projCol_[i].second;
    projOutput_[i].value = output_.value->subColMatrix(startCol, endCol);
D
dangqingqing 已提交
164 165 166
    if (output_.grad) {
      projOutput_[i].grad = output_.grad->subColMatrix(startCol, endCol);
    }
Z
zhangjinchao01 已提交
167 168
  }

169 170 171 172 173 174 175 176 177 178 179
  {
    AsyncGpuBlock block;
    for (size_t i = 0; i != inputLayers_.size(); ++i) {
      projections_[i]->forward(&getInput(i), &projOutput_[i], passType);
    }
  }

  /* add the bias-vector */
  if (biases_) {
    REGISTER_TIMER_INFO("FwBiasTimer", getName().c_str());
    output_.value->addBias(*(biases_->getW()), 1, sharedBias_);
Z
zhangjinchao01 已提交
180 181 182 183 184 185 186 187 188 189 190 191 192 193
  }

  /* activation */ {
    REGISTER_TIMER_INFO("FwAtvTimer", getName().c_str());
    forwardActivation();
  }
}

void ConcatenateLayer2::backward(const UpdateCallback& callback) {
  /* Do activation */ {
    REGISTER_TIMER_INFO("BpAvtTimer", getName().c_str());
    backwardActivation();
  }

194 195 196 197 198 199 200
  AsyncGpuBlock block;
  if (biases_ && biases_->getWGrad()) {
    REGISTER_TIMER_INFO("Concat2BpBiasTimer", getName().c_str());
    biases_->getWGrad()->collectBias(*getOutputGrad(), 1, sharedBias_);
    biases_->getParameterPtr()->incUpdate(callback);
  }

Z
zhangjinchao01 已提交
201 202 203 204 205 206 207 208
  for (size_t i = 0; i != inputLayers_.size(); ++i) {
    if (projections_[i]) {
      projections_[i]->backward(callback);
    }
  }
}

}  // namespace paddle