KmaxSeqScoreLayer.cpp 4.2 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19

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"

namespace paddle {

class KmaxSeqScoreLayer : public Layer {
W
Wu Yi 已提交
20
 private:
21 22 23 24 25 26
  MatrixPtr scores_;
  size_t beamSize_;
  void kmaxScorePerSeq(const real* score,
                       real* sortedRes,
                       const ICpuGpuVectorPtr seqStartPos);

W
Wu Yi 已提交
27
 public:
28 29 30 31 32 33 34 35 36 37 38 39 40 41
  explicit KmaxSeqScoreLayer(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;
};

REGISTER_LAYER(kmax_seq_score, KmaxSeqScoreLayer);

bool KmaxSeqScoreLayer::init(const LayerMap& layerMap,
                             const ParameterMap& parameterMap) {
  bool ret = Layer::init(layerMap, parameterMap);
42
  CHECK_EQ(1U, inputLayers_.size());
43 44

  beamSize_ = config_.beam_size();
45
  CHECK_GE(beamSize_, 1U);
46 47

  setNeedSequenceInfo(false);
48
  setNeedGradient(false);
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
  return ret;
}

void KmaxSeqScoreLayer::kmaxScorePerSeq(const real* scores,
                                        real* sortedIds,
                                        const ICpuGpuVectorPtr seqStartPos) {
  int* starts = seqStartPos->getMutableData(false);
  std::vector<real> indices;
  for (size_t i = 0; i < seqStartPos->getSize() - 1; ++i) {
    int seqLen = starts[i + 1] - starts[i];
    int k = std::min(static_cast<int>(beamSize_), seqLen);

    indices.resize(seqLen, 0);
    std::iota(begin(indices), end(indices), 0.);
    std::vector<real> tmpScore(scores + starts[i], scores + starts[i + 1]);
    std::partial_sort(
        begin(indices),
        begin(indices) + k,
        end(indices),
        [&](size_t a, size_t b) { return tmpScore[a] > tmpScore[b]; });
    memcpy(sortedIds + (i * beamSize_), indices.data(), k * sizeof(real));
  }
}

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

  const Argument& input = getInput(0);
  const MatrixPtr inputScore = getInputValue(0);

  CHECK(input.hasSeq() || input.hasSubseq())
      << "input of " << getName()
      << " must be a sequence or a nested sequence.";
  CHECK_EQ(input.value->getWidth(), 1UL)
C
caoying03 已提交
83 84
      << "input of " << getName() << " are scores over a sequence or "
      << "a nested sequence, so its width must be 1.";
85 86

  if (useGpu_) {
C
caoying03 已提交
87 88 89 90
    /*
     * currently, this Layer only runs in CPU, if the other part of the model is
     * runing on GPU, then copy the input to this layer from GPU to CPU.
     */
91 92 93 94 95 96 97 98 99 100
    Matrix::resizeOrCreate(scores_,
                           inputScore->getHeight(),
                           1,
                           false /* trans */,
                           false /* useGpu */);
    scores_->copyFrom(*inputScore);
  } else {
    scores_ = inputScore;
  }

C
caoying03 已提交
101 102 103 104 105 106 107 108
  /*
   * TODO(caoying)
   * In PaddePaddle, currently all matrices are real number types,
   * but output of this layer which is some selected indices of the give
   * sequence are actually filled with int types so that storing int types
   * information in a real number matrix is dangerous, since real numbers will
   * be convered to int types.
   */
109 110 111 112 113 114
  Matrix::resizeOrCreate(
      output_.value,
      input.hasSubseq() ? input.getNumSubSequences() : input.getNumSequences(),
      beamSize_,
      false,
      false);
115 116
  output_.value->one();
  output_.value->mulScalar(-1.);
117

118 119 120 121
  kmaxScorePerSeq(scores_->getData(),
                  output_.value->getData(),
                  input.hasSubseq() ? input.subSequenceStartPositions
                                    : input.sequenceStartPositions);
122 123 124 125 126
}

void KmaxSeqScoreLayer::backward(const UpdateCallback& callback) {}

}  // namespace paddle