AgentLayer.h 5.6 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
Z
zhangjinchao01 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17

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 "Layer.h"
X
Xin Pan 已提交
18
#include "paddle/legacy/math/Matrix.h"
Z
zhangjinchao01 已提交
19 20 21 22 23 24 25 26 27 28
#include "paddle/utils/ThreadLocal.h"

namespace paddle {

/**
 * AgentLayer use as a virtual input of another layer in config,
 * before execute forward/backward, setRealLayer() should be
 * called to set one and only one real layer
 */
class AgentLayer : public Layer {
W
Wu Yi 已提交
29
 protected:
Z
zhangjinchao01 已提交
30 31 32
  LayerPtr realLayer_;
  int numSamples_;

W
Wu Yi 已提交
33
 public:
Z
zhangjinchao01 已提交
34 35 36 37
  explicit AgentLayer(const LayerConfig& config) : Layer(config) {}

  ~AgentLayer() {}

Y
Yu Yang 已提交
38 39
  bool init(const LayerMap& layerMap,
            const ParameterMap& parameterMap) override;
Z
zhangjinchao01 已提交
40 41 42 43 44 45 46 47

  // if *numSamples* set,
  // real layer output will only use first *numSamples* rows
  void setRealLayer(LayerPtr layer, int numSamples = 0) {
    realLayer_ = layer;
    numSamples_ = numSamples;
  }

Y
Yu Yang 已提交
48 49
  void forward(PassType passType) override;
  void backward(const UpdateCallback& callback = nullptr) override {}
Z
zhangjinchao01 已提交
50 51 52 53 54 55 56 57
};

/**
 * Like AgentLayer, but it can gather many real layers. Each real
 * layer give a few rows of a sequence, after gather all real layers,
 * GatherAgentLayer collect a complete sequence.
 */
class GatherAgentLayer : public Layer {
W
Wu Yi 已提交
58
 protected:
Z
zhangjinchao01 已提交
59 60 61 62 63 64
  std::vector<LayerPtr> realLayers_;
  std::vector<IVectorPtr> idsVec_;
  // we don't clear idsVec_ vector to aviod IVector alloc/free
  IVectorPtr allIds_;
  std::vector<int> idIndex_;

W
Wu Yi 已提交
65
 public:
Z
zhangjinchao01 已提交
66 67 68 69
  explicit GatherAgentLayer(const LayerConfig& config) : Layer(config) {}

  virtual ~GatherAgentLayer() {}

Y
Yu Yang 已提交
70 71
  bool init(const LayerMap& layerMap,
            const ParameterMap& parameterMap) override;
Z
zhangjinchao01 已提交
72 73

  // call before addRealLayer
74 75 76 77
  void clearRealLayers() { realLayers_.clear(); }

  void copyIdAndSequenceInfo(ICpuGpuVectorPtr sequenceStartPositions,
                             ICpuGpuVectorPtr subSequenceStartPositions,
78
                             const IVectorPtr& allIds,
Z
zhangjinchao01 已提交
79 80 81 82 83
                             const std::vector<int>& idIndex);

  // add one real layer, can call many times
  void addRealLayer(LayerPtr layer) { realLayers_.push_back(layer); }

Y
Yu Yang 已提交
84 85
  void forward(PassType passType) override;
  void backward(const UpdateCallback& callback) override;
86 87
  void forwardValue(PassType passType);
  void forwardIds(PassType passType);
Z
zhangjinchao01 已提交
88 89 90 91 92 93 94 95 96 97
};

/**
 * Like AgentLayer, but only select a few rows in real layer.
 * [idIndex, idIndex + idSize) of *ids* in setRealLayerAndOutput()
 * are the selected row ids. It's used to scatter one layer's output
 * to many small submodels. ScatterAgentLayer can support ids real layer,
 * if it is, the agent will select a few ids in real layer.
 */
class ScatterAgentLayer : public Layer {
W
Wu Yi 已提交
98
 protected:
Z
zhangjinchao01 已提交
99 100 101 102 103 104 105 106
  LayerPtr realLayer_;
  IVectorPtr ids_;
  IVectorPtr cpuIds_;
  Argument realOutArg_;
  int idIndex_;
  int idSize_;
  int seqStartPosIndex_;
  int numSequences_;  // number of sequences in this scatterAgentLayer
107 108 109 110 111
  bool handleBackward_;

  // use to store expanded cpuStartPositions or subSequenceStartPositions
  // of real layer.
  ICpuGpuVectorPtr inputStartPos_;
Z
zhangjinchao01 已提交
112

113 114 115
  // true for setRealLayer, false for setRealLayerAndOutput
  bool selectionMode_;

W
Wu Yi 已提交
116
 public:
Z
zhangjinchao01 已提交
117 118 119 120
  explicit ScatterAgentLayer(const LayerConfig& config) : Layer(config) {}

  virtual ~ScatterAgentLayer() {}

Y
Yu Yang 已提交
121 122
  bool init(const LayerMap& layerMap,
            const ParameterMap& parameterMap) override;
Z
zhangjinchao01 已提交
123 124 125 126 127 128

  /**
   * @brief set real layer in generation
   *
   * @param layer[input]    realLayer
   * @param ids[input]      row id in real layer
129 130
   * @param copyId[input]   whether to copy a cpu version of ids,
   *                        false(default) in ScatterAgentLayer, and
Z
zhangjinchao01 已提交
131 132
   *                        true in SequenceScatterAgentLayer.
   */
133
  void setRealLayer(LayerPtr layer, const std::vector<int>& ids) {
Z
zhangjinchao01 已提交
134 135 136
    realLayer_ = layer;
    IVector::resizeOrCreate(ids_, ids.size(), useGpu_);
    ids_->copyFrom(ids.data(), ids.size());
137 138 139 140 141
    if (useGpu_) {
      IVector::resizeOrCreate(cpuIds_, ids.size(), false);
      cpuIds_->copyFrom(ids.data(), ids.size());
    } else {
      cpuIds_ = ids_;
Z
zhangjinchao01 已提交
142
    }
143
    selectionMode_ = true;
Z
zhangjinchao01 已提交
144 145 146 147
  }

  // set real layer and output, [idIndex, idIndex + idSize) of *ids*
  // are selected row for realOutArg in realLayer
148 149 150 151
  void setRealLayerAndOutput(LayerPtr layer,
                             const Argument& outArg,
                             const IVectorPtr& ids,
                             int idIndex,
152 153
                             int idSize,
                             bool handleBackward) {
Z
zhangjinchao01 已提交
154 155 156 157 158
    realLayer_ = layer;
    realOutArg_ = outArg;
    ids_ = ids;
    idIndex_ = idIndex;
    idSize_ = idSize;
159
    handleBackward_ = handleBackward;
160
    selectionMode_ = false;
Z
zhangjinchao01 已提交
161 162
  }

163 164 165
  void setSequenceStartPositions(const ICpuGpuVectorPtr& sequenceStartPositions,
                                 int seqStartPosIndex,
                                 int numSequences) {
Z
zhangjinchao01 已提交
166 167 168 169 170
    realOutArg_.sequenceStartPositions = sequenceStartPositions;
    seqStartPosIndex_ = seqStartPosIndex;
    numSequences_ = numSequences;
  }

Y
Yu Yang 已提交
171 172
  void forward(PassType passType) override;
  void backward(const UpdateCallback& callback) override;
Z
zhangjinchao01 已提交
173

174
  void forwardWithSelection(PassType passType);
Z
zhangjinchao01 已提交
175 176 177
};

}  // namespace paddle