CrossEntropyOverBeam.h 3.8 KB
Newer Older
C
caoying03 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
/* 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. */

#pragma once

#include "CrossEntropyOverBeam.h"
#include "Layer.h"

namespace paddle {

C
caoying03 已提交
22
/* This struct stores the beams in all search steps for a single sequence. */
C
caoying03 已提交
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
struct BeamExpansion {
  std::vector<MatrixPtr> scores;
  std::vector<IVectorPtr> seqInfo;

  std::vector<MatrixPtr> candidateIds;
  std::vector<int> gold;

  std::vector<MatrixPtr> scoreGrad;

  size_t expansionCount;

  BeamExpansion(int n) {
    expansionCount = n;
    scores.resize(expansionCount);
    seqInfo.resize(expansionCount);
    candidateIds.resize(expansionCount);
    scoreGrad.resize(expansionCount);

    gold.resize(expansionCount);
  };
};
typedef std::shared_ptr<BeamExpansion> BeamExpansionPtr;

class CostForOneSequence {
public:
  CostForOneSequence()
      : beamSize_(0), validExpansionCount_(0), goldAsExtraPath_(false) {}
  void setData(const BeamExpansionPtr bPtr, size_t beamSize) {
    beams_ = bPtr;
    beamSize_ = beamSize;

    expandedPathScores_.clear();
    expandedPathScores_.resize(beams_->expansionCount);

    goldRowIds_.clear();
    goldRowIds_.resize(beams_->expansionCount, 0);
    goldColIds_.clear();
    goldColIds_.resize(beams_->expansionCount, -1);
  }
  size_t getValidExpansionCount() { return validExpansionCount_; }

  real forward();
  void backward();

private:
  void calValidExpandStep();
  void constructTotalExpansion();
  size_t initLastExpansion();
  real globallyNormalizedScore();

  int getSeqStartPos(size_t beamId, size_t rowId) {
    CHECK_GT(beams_->seqInfo[beamId]->getSize() - 1, rowId);
    int* starts = beams_->seqInfo[beamId]->getData();
    return starts[rowId] - starts[0];
  };

  size_t beamSize_;
  size_t validExpansionCount_;
  bool goldAsExtraPath_;
  std::vector<int> goldRowIds_;
  std::vector<int> goldColIds_;

  BeamExpansionPtr beams_;
  std::vector<std::vector<int>> pathRowIdsInEachBeam_;
  std::vector<int> parentIdsInBeam_;
  size_t goldIdsInFinalExpansion_;

  std::vector<MatrixPtr> expandedPathScores_;

  MatrixPtr softmaxOut_;
};

C
caoying03 已提交
95 96 97 98 99 100 101
class CrossEntropyOverBeam : public Layer {
public:
  explicit CrossEntropyOverBeam(const LayerConfig& config) : Layer(config) {}
  bool init(const LayerMap& layerMap,
            const ParameterMap& parameterMap) override;
  void forward(PassType passType) override;
  void backward(const UpdateCallback& callback) override;
C
caoying03 已提交
102 103 104 105 106 107 108 109 110 111 112 113

private:
  void checkInputs();
  void copyInputsToCpu();
  void resizeOutput();
  void copyGradToGpu(size_t copyCount);
  void splitBatchBeams();

  size_t beamExpanCount_;
  size_t batchSize_;
  size_t beamSize_;

C
caoying03 已提交
114 115 116 117 118
  /*
   * the process of constructing beams is not friendly to GPU, currently, this
   * layer only runs on CPU, if any of its inputs is on GPU memory, then copy
   * it to CPU memory.
   */
C
caoying03 已提交
119 120 121 122 123 124 125
  std::vector<MatrixPtr> candidateScores_;
  std::vector<MatrixPtr> candidateScoreGrad_;
  std::vector<MatrixPtr> candidateInBeam_;
  std::vector<MatrixPtr> gradToInputs_;
  std::vector<IVectorPtr> goldSequence_;
  std::vector<std::vector<int>> beamSplitPos_;

C
caoying03 已提交
126 127 128 129
  /*
   * split entire bath of beams into beam per sequnence and store the result
   * into this member.
   */
C
caoying03 已提交
130
  std::vector<BeamExpansion> beamPerSeq_;
C
caoying03 已提交
131
  /* beamCosts_ is used to propagate error in one sequence. */
C
caoying03 已提交
132
  std::vector<CostForOneSequence> beamCosts_;
C
caoying03 已提交
133 134 135
};

}  // namespace paddle