SubNestedSequenceLayer.cpp 6.3 KB
Newer Older
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
/* Copyright (c) 2016 PaddlePaddle Authors. 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 "Layer.h"
#include "paddle/math/Matrix.h"
#include "paddle/math/Vector.h"
#include "paddle/utils/Logging.h"
#include "paddle/utils/Stat.h"

namespace paddle {

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

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

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

private:
34 35 36 37
  void reorganizeSeqInfo(const ICpuGpuVectorPtr seqStartPos,
                         const ICpuGpuVectorPtr subSeqStartPos);
  void calSelectedCols(const MatrixPtr selectedIndices,
                       const std::vector<std::vector<int>> inputSeqInfo);
38 39 40 41 42
  void buildOutputSeqInfo();

  std::vector<int> outSeqStartInfo_;
  std::vector<int> outSubSeqStartInfo_;

43 44 45 46 47
  // if the second input of this layer is on GPU memory, copy it to CPU memory.
  MatrixPtr selIdsCpu_;
  // reorganize sequenceStartPositions and subSequenceStartPositions altogether
  // into a 2d vector to facilitate the sequence selection process.
  std::vector<std::vector<int>> inputSeqInfo_;
48

49
  // the final seleted row indices in a batch,
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
  // rowIdx_ and selectedRows_ actually share a same memory.
  IVectorPtr rowIndice_;
  std::vector<int> selectedRows_;
};

REGISTER_LAYER(sub_nested_seq, SubNestedSequenceLayer);

bool SubNestedSequenceLayer::init(const LayerMap& layerMap,
                                  const ParameterMap& parameterMap) {
  /* Initialize the basic parent class */
  Layer::init(layerMap, parameterMap);
  CHECK_EQ(2U, inputLayers_.size());
  setNeedSequenceInfo(false);
  return true;
}

66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
void SubNestedSequenceLayer::reorganizeSeqInfo(
    const ICpuGpuVectorPtr seqStartPos, const ICpuGpuVectorPtr subSeqStartPos) {
  int* seqStarts = seqStartPos->getMutableData(false);
  int* subSeqStarts = subSeqStartPos->getMutableData(false);

  int seqNum = seqStartPos->getSize() - 1;
  inputSeqInfo_.resize(seqNum, std::vector<int>());
  int seqIdx = 0;
  for (size_t i = 0; i < subSeqStartPos->getSize(); ++i) {
    inputSeqInfo_[seqIdx].push_back(subSeqStarts[i]);
    if (subSeqStarts[i] == seqStarts[seqIdx + 1]) {
      seqIdx++;
      if (seqIdx == seqNum) return;
      inputSeqInfo_[seqIdx].push_back(subSeqStarts[i]);
    }
  }
}

void SubNestedSequenceLayer::calSelectedCols(
    const MatrixPtr selectedIndices,
    const std::vector<std::vector<int>> inputSeqInfo) {
87 88 89
  selectedRows_.clear();
  outSubSeqStartInfo_.resize(1, 0);
  outSeqStartInfo_.resize(1, 0);
90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106

  size_t seqNum = selectedIndices->getHeight();
  size_t beamSize = selectedIndices->getWidth();
  for (size_t i = 0; i < seqNum; ++i) {
    for (size_t j = 0; j < beamSize; ++j) {
      if (selectedIndices->getElement(i, j) == -1.) break;
      int selSubSeqIdx = selectedIndices->getElement(i, j);
      CHECK_GT(inputSeqInfo_[i].size() - 1, selSubSeqIdx);

      size_t subSeqLen =
          inputSeqInfo_[i][selSubSeqIdx + 1] - inputSeqInfo_[i][selSubSeqIdx];
      for (size_t k = 0; k < subSeqLen; ++k)
        selectedRows_.push_back(inputSeqInfo_[i][selSubSeqIdx] + k);
      outSubSeqStartInfo_.push_back(outSubSeqStartInfo_.back() + subSeqLen);
    }
    outSeqStartInfo_.push_back(outSubSeqStartInfo_.back());
  }
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
}

void SubNestedSequenceLayer::buildOutputSeqInfo() {
  Argument& output = getOutput();

  ICpuGpuVector::resizeOrCreate(
      output.sequenceStartPositions, outSeqStartInfo_.size(), false);
  output.sequenceStartPositions->copyFrom(
      outSeqStartInfo_.data(), outSeqStartInfo_.size(), false);

  ICpuGpuVector::resizeOrCreate(
      output.subSequenceStartPositions, outSubSeqStartInfo_.size(), false);
  output.subSequenceStartPositions->copyFrom(
      outSubSeqStartInfo_.data(), outSubSeqStartInfo_.size(), false);
}

void SubNestedSequenceLayer::forward(PassType passType) {
  Layer::forward(passType);
C
caoying03 已提交
125

126
  const Argument& inputSeq = getInput(0);
C
caoying03 已提交
127 128
  CHECK(inputSeq.hasSubseq()) << "The first input of SubNestSequence layer "
                              << "must be a nested sequence.";
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
  const MatrixPtr selectedIndices = getInputValue(1);
  CHECK_EQ(inputSeq.getNumSequences(), selectedIndices->getHeight());

  if (dynamic_cast<GpuMatrix*>(selectedIndices.get())) {
    /*
     * Currently, the second input for this layer generated by
     * kmax_sequence_score_layer whose output is always stored on CPU,
     * or a data_layer which canbe on GPU.
     *
     * If the second input is on GPU, copy it to CPU memory, because this
     * input always uses very few memory, and operations related to it are
     * all logic control, not computations.
     */
    Matrix::resizeOrCreate(selIdsCpu_,
                           selectedIndices->getHeight(),
                           selectedIndices->getWidth(),
                           false /* trans */,
                           false /* useGpu */);
    selIdsCpu_->copyFrom(*selectedIndices);
  } else {
    selIdsCpu_ = selectedIndices;
  }
151

152 153 154
  reorganizeSeqInfo(inputSeq.sequenceStartPositions,
                    inputSeq.subSequenceStartPositions);
  calSelectedCols(selIdsCpu_, inputSeqInfo_);
155 156 157 158 159 160 161 162 163 164
  resetOutput(selectedRows_.size(), getSize());

  if (useGpu_) {
    rowIndice_ = IVector::create(selectedRows_.size(), useGpu_);
    rowIndice_->copyFrom(selectedRows_.data(), selectedRows_.size());
  } else {
    rowIndice_ =
        IVector::create(selectedRows_.data(), selectedRows_.size(), useGpu_);
  }

165
  buildOutputSeqInfo();
166 167 168 169
  getOutputValue()->selectRows(*getInputValue(0), *rowIndice_);
}

void SubNestedSequenceLayer::backward(const UpdateCallback& callback) {
C
caoying03 已提交
170
  MatrixPtr inputSeqGrad = getInputGrad(0);
171 172
  MatrixPtr outputGrad = getOutputGrad();

C
caoying03 已提交
173
  if (inputSeqGrad) outputGrad->addToRows(*inputSeqGrad, *rowIndice_);
174 175 176
}

}  // namespace paddle