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:
C
caoying03 已提交
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
  /*
   * This functions generates the indices of rows in a batch according to the
   * indices of selected sub-sequence in each sequence.
   *
   * Examples:
   * selectedIndices:
   *   [
   *     [0, 1, -1],
   *     [0, 1, 2],
   *     [0, -1, -1],
   *     [0, 2, 3],
   *   ]
   * inputSeqInfo:
   *   [
   *     [0,3,4],
   *     [4,5,7,10,15],
   *     [15,20],
   *     [20,22,23,25,28]
   *   ]
   *
   * ths output is saved to private member rowIndice_;
C
caoying03 已提交
55
   * [0,1,2,3,4,5,6,7,8,9,15,16,17,18,19,20,21,23,24,25,26,27]
C
caoying03 已提交
56
   */
57

C
caoying03 已提交
58
  void calSelectedRows(const MatrixPtr selectedIndices,
C
caoying03 已提交
59
                       const std::vector<std::vector<int>>& inputSeqInfo);
60

61 62
  // if the second input of this layer is on GPU memory, copy it to CPU memory.
  MatrixPtr selIdsCpu_;
C
caoying03 已提交
63 64

  // reorganized sequenceStartPositions and subSequenceStartPositions
65
  // into a 2d vector to facilitate the sequence selection process.
C
caoying03 已提交
66
  std::vector<std::vector<int>> inputSeqInfoVec_;
67

C
caoying03 已提交
68
  // the final selected row indices in a batch,
C
caoying03 已提交
69
  // rowIndice_ and selectedRows_ actually share a same memory.
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
  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;
}

C
caoying03 已提交
85
void SubNestedSequenceLayer::calSelectedRows(
86
    const MatrixPtr selectedIndices,
C
caoying03 已提交
87
    const std::vector<std::vector<int>>& inputSeqInfo) {
88
  selectedRows_.clear();
C
caoying03 已提交
89 90 91

  std::vector<int> outSeqStartInfo(1, 0);
  std::vector<int> outSubSeqStartInfo(1, 0);
92 93 94 95 96 97

  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;
C
caoying03 已提交
98 99 100 101 102
      // TODO(caoying)
      // Here selSubSeqIdx is automatically converted from real to int
      // This is very dangerous if user fill this matrix himself, invalid data
      // may occur. The selected indices should be stored in
      // CpuSparseMatrix with SparseValueType set to NO_VALUE.
103
      int selSubSeqIdx = selectedIndices->getElement(i, j);
C
caoying03 已提交
104
      CHECK_GT(inputSeqInfoVec_[i].size() - 1, selSubSeqIdx);
105

C
caoying03 已提交
106 107
      size_t subSeqLen = inputSeqInfoVec_[i][selSubSeqIdx + 1] -
                         inputSeqInfoVec_[i][selSubSeqIdx];
108
      for (size_t k = 0; k < subSeqLen; ++k)
C
caoying03 已提交
109 110
        selectedRows_.push_back(inputSeqInfoVec_[i][selSubSeqIdx] + k);
      outSubSeqStartInfo.push_back(outSubSeqStartInfo.back() + subSeqLen);
111
    }
C
caoying03 已提交
112
    outSeqStartInfo.push_back(outSubSeqStartInfo.back());
113
  }
114

C
caoying03 已提交
115 116 117 118 119 120 121
  if (useGpu_) {
    rowIndice_ = IVector::create(selectedRows_.size(), useGpu_);
    rowIndice_->copyFrom(selectedRows_.data(), selectedRows_.size());
  } else {
    rowIndice_ =
        IVector::create(selectedRows_.data(), selectedRows_.size(), useGpu_);
  }
122

C
caoying03 已提交
123
  // create the sequence information for the output.
124
  ICpuGpuVector::resizeOrCreate(
C
caoying03 已提交
125 126 127
      output_.sequenceStartPositions, outSeqStartInfo.size(), false);
  output_.sequenceStartPositions->copyFrom(
      outSeqStartInfo.data(), outSeqStartInfo.size(), false);
128 129

  ICpuGpuVector::resizeOrCreate(
C
caoying03 已提交
130 131 132
      output_.subSequenceStartPositions, outSubSeqStartInfo.size(), false);
  output_.subSequenceStartPositions->copyFrom(
      outSubSeqStartInfo.data(), outSubSeqStartInfo.size(), false);
133 134 135 136
}

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

138
  const Argument& inputSeq = getInput(0);
C
caoying03 已提交
139 140
  CHECK(inputSeq.hasSubseq()) << "The first input of SubNestSequence layer "
                              << "must be a nested sequence.";
141 142 143 144 145
  const MatrixPtr selectedIndices = getInputValue(1);
  CHECK_EQ(inputSeq.getNumSequences(), selectedIndices->getHeight());

  if (dynamic_cast<GpuMatrix*>(selectedIndices.get())) {
    /*
C
caoying03 已提交
146
     * Currently, the second input for this layer is generated by
147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162
     * 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;
  }
163

C
caoying03 已提交
164 165 166
  Argument::reorganizeSeqInfo(inputSeq.sequenceStartPositions,
                              inputSeq.subSequenceStartPositions,
                              inputSeqInfoVec_);
C
caoying03 已提交
167
  calSelectedRows(selIdsCpu_, inputSeqInfoVec_);
168

C
caoying03 已提交
169
  resetOutput(selectedRows_.size(), getSize());
170 171 172 173
  getOutputValue()->selectRows(*getInputValue(0), *rowIndice_);
}

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

C
caoying03 已提交
177
  if (inputSeqGrad) outputGrad->addToRows(*inputSeqGrad, *rowIndice_);
178 179 180
}

}  // namespace paddle