AgentLayer.cpp 8.7 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

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 "AgentLayer.h"

X
Xin Pan 已提交
17
#include "paddle/legacy/utils/Logging.h"
Z
zhangjinchao01 已提交
18

X
Xin Pan 已提交
19
#include "paddle/legacy/utils/Stat.h"
Z
zhangjinchao01 已提交
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38

namespace paddle {

REGISTER_LAYER(agent, AgentLayer);

bool AgentLayer::init(const LayerMap& layerMap,
                      const ParameterMap& parameterMap) {
  CHECK_EQ(config_.inputs_size(), 0);
  if (!Layer::init(layerMap, parameterMap)) {
    return false;
  }
  setNeedGradient(true);
  return true;
}

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

  Argument& realOutput = realLayer_->getOutput();
39 40
  int realNumSequences = realOutput.getNumSequences();
  CHECK_LE(numSamples_, realNumSequences);
Z
zhangjinchao01 已提交
41 42

  // get Arguments from real layers
43 44 45 46 47 48 49 50 51 52 53 54 55
  if (numSamples_ > 0 && numSamples_ < realNumSequences) {
    if (realOutput.hasSeq()) {
      int numRows =
          realOutput.sequenceStartPositions->getData(false)[numSamples_];
      output_.subArgFrom(realOutput,
                         /* offset */ 0,
                         numRows,
                         getSize(),
                         useGpu_,
                         /* trans */ false,
                         /* seqFlag */ true,
                         /* seqStart */ 0,
                         /* seqSize */ numSamples_ + 1);
Z
zhangjinchao01 已提交
56
    } else {
57 58
      output_.subArgFrom(
          realOutput, /* offset */ 0, numSamples_, getSize(), useGpu_);
Z
zhangjinchao01 已提交
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
    }
  } else {
    output_ = realOutput;
  }
}

bool GatherAgentLayer::init(const LayerMap& layerMap,
                            const ParameterMap& parameterMap) {
  CHECK_EQ(config_.inputs_size(), 0);
  if (!Layer::init(layerMap, parameterMap)) {
    return false;
  }
  setNeedGradient(true);
  return true;
}

75 76 77 78 79 80 81
void GatherAgentLayer::copyIdAndSequenceInfo(
    ICpuGpuVectorPtr sequenceStartPositions,
    ICpuGpuVectorPtr subSequenceStartPositions,
    const IVectorPtr& ids,
    const std::vector<int>& idIndex) {
  output_.sequenceStartPositions = sequenceStartPositions;
  output_.subSequenceStartPositions = subSequenceStartPositions;
Z
zhangjinchao01 已提交
82 83 84 85 86 87
  allIds_ = ids;
  idIndex_ = idIndex;
}

void GatherAgentLayer::forward(PassType passType) {
  Layer::forward(passType);
88 89 90 91 92 93 94
  forwardIds(passType);
  forwardValue(passType);
}

void GatherAgentLayer::forwardValue(PassType passType) {
  MatrixPtr valueReal = realLayers_[0]->getOutputValue();
  if (!valueReal) return;
Z
zhangjinchao01 已提交
95 96 97 98 99 100 101 102 103 104 105

  int height = allIds_->getSize();
  int width = this->getSize();
  resetOutput(height, width);
  idsVec_.resize(idIndex_.size());

  const MatrixPtr& outV = getOutputValue();

  for (size_t i = 0; i < realLayers_.size(); ++i) {
    const MatrixPtr& realV = realLayers_[i]->getOutputValue();
    idsVec_[i] = IVector::create(allIds_->getData() + idIndex_[i],
106 107
                                 /* size */ realV->getHeight(),
                                 useGpu_);
Z
zhangjinchao01 已提交
108 109 110 111
    realV->addToRows(*outV, *idsVec_[i]);
  }
}

X
xuwei06 已提交
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
namespace {

// dest[index[i]] <- src[i] for each i
void copyElements(const IVector& srcVec,
                  const IVector& indexVec,
                  IVector& destVec) {
  const int* src = srcVec.getData();
  const int* index = indexVec.getData();
  int* dest = destVec.getData();
  int len = indexVec.getSize();
  CHECK_EQ(srcVec.getSize(), indexVec.getSize());
  for (int i = 0; i < len; ++i) {
    dest[index[i]] = src[i];
  }
}
L
liaogang 已提交
127
}  // namespace
X
xuwei06 已提交
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145

void GatherAgentLayer::forwardIds(PassType passType) {
  IVectorPtr realId = realLayers_[0]->getOutputLabel();
  if (!realId) return;

  IVector::resizeOrCreate(output_.ids, allIds_->getSize(), useGpu_);
  IVectorPtr outId = output_.ids;
  idsVec_.resize(idIndex_.size());

  for (size_t i = 0; i < realLayers_.size(); ++i) {
    const IVectorPtr& realId = realLayers_[i]->getOutputLabel();
    idsVec_[i] = IVector::create(allIds_->getData() + idIndex_[i],
                                 /* size */ realId->getSize(),
                                 useGpu_);
    execViaCpu(&copyElements, *realId, *idsVec_[i], *outId);
  }
}

Z
zhangjinchao01 已提交
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171
void GatherAgentLayer::backward(const UpdateCallback& callback) {
  (void)callback;
  const MatrixPtr& outputGrad = getOutputGrad();

  for (size_t i = 0; i < realLayers_.size(); ++i) {
    const MatrixPtr& realG = realLayers_[i]->getOutputGrad();
    if (realG) {
      realG->selectRows(*outputGrad, *idsVec_[i]);
    }
  }
}

bool ScatterAgentLayer::init(const LayerMap& layerMap,
                             const ParameterMap& parameterMap) {
  CHECK_EQ(config_.inputs_size(), 0);
  if (!Layer::init(layerMap, parameterMap)) {
    return false;
  }
  setNeedGradient(true);
  return true;
}

void ScatterAgentLayer::forward(PassType passType) {
  Layer::forward(passType);
  CHECK_EQ(realLayer_->getDeviceId(), this->getDeviceId());

172
  int width = this->getSize();
173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
  if (selectionMode_) {
    forwardWithSelection(passType);
  } else {
    if (realOutArg_.hasSeq()) {
      output_.subArgFrom(realOutArg_,
                         /* offset */ idIndex_,
                         idSize_,
                         width,
                         useGpu_,
                         /* trans */ false,
                         /* seqFlag */ true,
                         /* seqStart */ seqStartPosIndex_,
                         /* seqSize */ numSequences_);
    } else {
      output_.subArgFrom(
          realOutArg_, /* offset */ idIndex_, idSize_, width, useGpu_);
Z
zhangjinchao01 已提交
189 190 191 192 193 194 195
    }
  }
}

void ScatterAgentLayer::backward(const UpdateCallback& callback) {
  (void)callback;

196 197
  CHECK(!selectionMode_);

Z
zhangjinchao01 已提交
198 199 200 201 202
  const MatrixPtr& outputGrad = realOutArg_.grad;
  const MatrixPtr& realGrad = realLayer_->getOutputGrad();
  if (realGrad) {
    // for agent in inFrameLines and memoryFrameLines,
    // only first scatterAgentLayer should do addToRows in backward
203
    if (handleBackward_) {
Z
zhangjinchao01 已提交
204 205 206 207 208 209 210 211
      outputGrad->addToRows(*realGrad, *ids_);
    }
  }
}

REGISTER_LAYER(gather_agent, GatherAgentLayer);
REGISTER_LAYER(scatter_agent, ScatterAgentLayer);

212
void ScatterAgentLayer::forwardWithSelection(PassType passType) {
Z
zhangjinchao01 已提交
213 214 215 216
  Layer::forward(passType);
  CHECK_EQ(realLayer_->getDeviceId(), this->getDeviceId());

  const Argument& input = realLayer_->getOutput();
217
  CHECK_EQ(realLayer_->getSize(), this->getSize());
Z
zhangjinchao01 已提交
218 219 220 221 222
  int width = this->getSize();

  AsyncGpuBlock asyncGpuBlock;
  REGISTER_TIMER_INFO("SequenceAgentLayerForward", getName().c_str());

223 224 225 226 227 228 229 230 231 232 233 234 235
  if (!input.hasSeq()) {
    if (realLayer_->getOutput().ids) {
      IVector::resizeOrCreate(output_.ids, ids_->getSize(), useGpu_);
      output_.ids->selectFrom(*realLayer_->getOutput().ids, *ids_);
    }
    if (realLayer_->getOutput().value) {
      int height = ids_->getSize();
      resetOutput(height, width);

      const MatrixPtr& outV = getOutputValue();
      const MatrixPtr& realV = realLayer_->getOutputValue();
      outV->selectRows(*realV, *ids_);
    }
Z
zhangjinchao01 已提交
236
  } else {
237
    // Putting the generation logic here is really an ugly hack!
Z
zhangjinchao01 已提交
238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256
    // used in generation
    int height = 0;
    size_t numSequences = ids_->getSize();
    const int* starts = input.getCpuStartPositions();
    size_t size = input.hasSubseq() ? input.getNumSubSequences()
                                    : input.getNumSequences();
    const int* cpuIds = cpuIds_->getData();

    for (size_t i = 0; i < numSequences; ++i) {
      size_t seqId = cpuIds[i];
      CHECK_LT(seqId, size);
      height += starts[seqId + 1] - starts[seqId];
    }
    reserveOutput(height, width);

    const MatrixPtr& outputValue = getOutputValue();

    CHECK_NE(input.sequenceStartPositions.get(),
             output_.sequenceStartPositions.get());
257 258
    ICpuGpuVector::resizeOrCreate(
        output_.sequenceStartPositions, numSequences + 1, false);
Z
zhangjinchao01 已提交
259 260
    int* outStarts = output_.sequenceStartPositions->getMutableData(false);

261 262 263
    ICpuGpuVector::resizeOrCreate(inputStartPos_, height, false);
    int* inStarts = inputStartPos_->getMutableData(false);

Z
zhangjinchao01 已提交
264 265 266 267 268 269 270 271 272 273 274 275
    size_t offsetOut = 0;
    for (size_t i = 0; i < numSequences; ++i) {
      outStarts[i] = offsetOut;
      size_t seqId = cpuIds[i];
      int size = starts[seqId + 1] - starts[seqId];
      for (int j = 0; j < size; j++) {
        inStarts[offsetOut + j] = starts[seqId] + j;
      }
      offsetOut += size;
    }
    outStarts[numSequences] = offsetOut;

276 277
    outputValue->copyByRowIndex(*input.value,
                                *inputStartPos_->getVector(useGpu_));
Z
zhangjinchao01 已提交
278 279 280 281
  }
}

}  // namespace paddle