AgentLayer.cpp 8.9 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.
Z
zhangjinchao01 已提交
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 34 35 36 37 38

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"

#include "paddle/utils/Logging.h"

#include "paddle/utils/Stat.h"

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 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137
    realV->addToRows(*outV, *idsVec_[i]);
  }
}

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());

138
  int width = this->getSize();
139 140 141
  if (realOutArg_.hasSeq()) {
    forwardSequence(passType);
  } else if (realOutArg_.value || realOutArg_.ids) {
142 143
    output_.subArgFrom(
        realOutArg_, /* offset */ idIndex_, idSize_, width, useGpu_);
144 145 146 147 148 149
  } else {  // used in generation
    if (realLayer_->getOutput().ids) {
      IVector::resizeOrCreate(output_.ids, ids_->getSize(), useGpu_);
      output_.ids->selectFrom(*realLayer_->getOutput().ids, *ids_);
    }
    if (realLayer_->getOutput().value) {
Z
zhangjinchao01 已提交
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167
      int height = ids_->getSize();
      resetOutput(height, width);

      const MatrixPtr& outV = getOutputValue();
      const MatrixPtr& realV = realLayer_->getOutputValue();
      outV->selectRows(*realV, *ids_);
    }
  }
}

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

  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
168
    if (handleBackward_) {
Z
zhangjinchao01 已提交
169 170 171 172 173 174 175 176
      outputGrad->addToRows(*realGrad, *ids_);
    }
  }
}

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

177
void GatherAgentLayer::forwardIds(PassType passType) {
Z
zhangjinchao01 已提交
178 179
  int height = 0;
  IVectorPtr idReal = realLayers_[0]->getOutputLabel();
180 181 182 183 184

  if (!idReal) return;

  if (output_.subSequenceStartPositions) {
    int* starts = output_.subSequenceStartPositions->getMutableData(false);
Z
zhangjinchao01 已提交
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
    // Gather generator.idsVec
    // if is beam search generation result. Get first result.
    if (idReal->getData()[idReal->getSize() - 1] == -1) {
      for (size_t i = 0; i < realLayers_.size(); ++i) {
        // The first element stores first result size
        idReal = realLayers_[i]->getOutputLabel();
        idReal->subVecFrom(*idReal, 1, idReal->getData()[0]);
      }
    }
    for (size_t i = 0; i < realLayers_.size(); ++i) {
      CHECK(realLayers_[i]->getOutputLabel());
      starts[i] = height;
      height += realLayers_[i]->getOutputLabel()->getSize();
    }
    starts[realLayers_.size()] = height;
    output_.sequenceStartPositions->getMutableData(false)[1] = height;

    IVector::resizeOrCreate(output_.ids, height, false);
    for (size_t i = 0; i < realLayers_.size(); ++i) {
      output_.ids->subVec(starts[i], starts[i + 1] - starts[i])
          ->copyFrom(*realLayers_[i]->getOutputLabel());
    }
  } else {
208
    LOG(FATAL) << "Not implemented";
Z
zhangjinchao01 已提交
209 210 211
  }
}

212
void ScatterAgentLayer::forwardSequence(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
  if (realOutArg_.value || realOutArg_.ids) {
Z
zhangjinchao01 已提交
224
    CHECK(realOutArg_.sequenceStartPositions);
225 226 227 228 229 230 231
    output_.subArgFrom(realOutArg_,
                       /* offset */ idIndex_,
                       idSize_,
                       width,
                       useGpu_,
                       /* trans */ false,
                       /* seqFlag */ true,
Z
zhangjinchao01 已提交
232 233 234
                       /* seqStart */ seqStartPosIndex_,
                       /* seqSize */ numSequences_);
  } else {
235
    // Putting the generation logic here is really an ugly hack!
Z
zhangjinchao01 已提交
236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254
    // 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());
255 256
    ICpuGpuVector::resizeOrCreate(
        output_.sequenceStartPositions, numSequences + 1, false);
Z
zhangjinchao01 已提交
257 258
    int* outStarts = output_.sequenceStartPositions->getMutableData(false);

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

Z
zhangjinchao01 已提交
262 263 264 265 266 267 268 269 270 271 272 273
    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;

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

}  // namespace paddle