MultiplexLayer.cpp 5.4 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 31 32 33 34 35 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 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179
/* 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 "paddle/utils/Logging.h"
#include "Layer.h"
#include "paddle/math/Matrix.h"
#include "paddle/utils/Stat.h"

namespace paddle {

/**
 *@brief This layer multiplex multiple layers according to the index,
 * which is provided by the first input layer.
 * - Input[0]: the index of the layer to output of size batchSize.
 * - Input[1:N]; the candidate output data.
 * For each index i from 0 to batchSize -1, the output is the i-th row of the
 * (index[i] + 1)-th layer.
 *
 * For each i-th row of output:
 *
 * \f[
 *   y[i][j] = x_{x_{0}[i] + 1}[i][j], j = 0,1, ... , (x_{1}.width - 1)
 * \f]
 * where, y is output. \f$x_{k}\f$ is the k-th input layer and
 * \f$k = x_{0}[i] + 1\f$.
 */

class MultiplexLayer : public Layer {
protected:
  /**
   * @brief A struct is used to save the copy information, includes input
   * layer index and copy size.
   */
  struct CopyInfo {
    CopyInfo(int inStartIdx, int inLength, int inCopyIdx)
        : startIdx(inStartIdx), length(inLength), copyIdx(inCopyIdx) {}

    /// The start row of input.
    int startIdx;
    /// Number of rows. If the layer index in Input[0] is not consecutive,
    /// the length is one. Otherwise, the length is > 1 and copy multi rows
    /// once.
    int length;
    /// The copied layer index, which needs to add 1.
    int copyIdx;
  };

  /// A list of CopyInfo used to save copy information.
  std::vector<CopyInfo> copySchedule_;

  /// Temporary matrix pointer to point to input data.
  MatrixPtr tmpSrc_;
  /// Temporary matrix pointer to point to output data.
  MatrixPtr tmpDest_;

public:
  explicit MultiplexLayer(const LayerConfig& config) : Layer(config) {}

  ~MultiplexLayer() {}

  bool init(const LayerMap& layerMap, const ParameterMap& parameterMap);

  void forward(PassType passType);
  void backward(const UpdateCallback& callback = nullptr);

private:
  /**
   * @brief Calculate copy info for input layers.
   */
  void calculateCopySchedule(const IVectorPtr& copyIds, size_t numIns);
};

REGISTER_LAYER(multiplex, MultiplexLayer);

void MultiplexLayer::calculateCopySchedule(const IVectorPtr& copyIds,
                                           size_t numIns) {
  copySchedule_.clear();
  CopyInfo prevCopyInfo(0, 0, -1);
  for (size_t i = 0; i < copyIds->getSize(); i++) {
    int copyId = copyIds->getElement(i);
    CHECK_GE(copyId, 0);
    CHECK_LT(copyId, int(numIns));
    // copy same input layer with prevous and will copy consecutive.
    if (copyId == prevCopyInfo.copyIdx) {
      ++prevCopyInfo.length;
    } else {
      if (prevCopyInfo.copyIdx != -1) {
        copySchedule_.emplace_back(prevCopyInfo);
      }
      prevCopyInfo.startIdx = i;
      prevCopyInfo.length = 1;
      prevCopyInfo.copyIdx = copyId;
    }
  }
  if (prevCopyInfo.copyIdx != -1) {
    copySchedule_.emplace_back(prevCopyInfo);
  }
}

bool MultiplexLayer::init(const LayerMap& layerMap,
                          const ParameterMap& parameterMap) {
  Layer::init(layerMap, parameterMap);

  CHECK_GE(inputLayers_.size(), 2U);

  tmpSrc_ =
      Matrix::create(nullptr, /* height= */ 1, 1, /* trans= */ false, useGpu_);
  tmpDest_ =
      Matrix::create(nullptr, /* height= */ 1, 1, /* trans= */ false, useGpu_);
  return true;
}

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

  IVectorPtr copyIds = getInput(0).ids;
  MatrixPtr inV1 = getInputValue(1);
  CHECK_EQ(copyIds->getSize(), inV1->getHeight());
  for (size_t i = 2; i < inputLayers_.size(); i++) {
    CHECK_EQ(inV1->getHeight(), getInputValue(i)->getHeight());
    CHECK_EQ(inV1->getWidth(), getInputValue(i)->getWidth());
  }

  calculateCopySchedule(copyIds, inputLayers_.size() - 1);
  {
    REGISTER_TIMER_INFO("FwResetTimer", getName().c_str());
    reserveOutput(inV1->getHeight(), inV1->getWidth());
  }

  MatrixPtr outV = getOutputValue();
  {
    REGISTER_TIMER_INFO("FwLMultplexingTimer", getName().c_str());
    AsyncGpuBlock block;
    for (const CopyInfo& info : copySchedule_) {
      outV->subMatrix(info.startIdx, info.length, tmpDest_)
          ->copyFrom(*getInputValue(info.copyIdx + 1)
                          ->subMatrix(info.startIdx, info.length, tmpSrc_));
    }
  }

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

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

  MatrixPtr outG = getOutputGrad();

  {
    REGISTER_TIMER_INFO("BwLMultiplexTimer", getName().c_str());
    AsyncGpuBlock block;
    for (const CopyInfo& info : copySchedule_) {
      if (getInputGrad(info.copyIdx + 1)) {
        getInputGrad(info.copyIdx + 1)
            ->subMatrix(info.startIdx, info.length, tmpDest_)
            ->add(*outG->subMatrix(info.startIdx, info.length, tmpSrc_));
      }
    }
  }
}

}  // namespace paddle