SequenceToBatch.cpp 8.1 KB
Newer Older
Z
zhangjinchao01 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
/* Copyright (c) 2016 Baidu, Inc. 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. */

#include <vector>
#include <algorithm>
#include "SequenceToBatch.h"
#include <iostream>
#include <string.h>

namespace paddle {

23 24 25 26
void SequenceToBatch::resizeOrCreateBatch(int batchSize,
                                          size_t numSequences,
                                          const int *seqStarts,
                                          bool reversed,
Z
zhangjinchao01 已提交
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
                                          bool prevBatchState) {
  CHECK_EQ(seqStarts[numSequences], batchSize);
  IVector::resizeOrCreate(seq2BatchIdx_, batchSize, useGpu_);
  if (!useGpu_) {
    cpuSeq2BatchIdx_ = seq2BatchIdx_;
  } else {
    IVector::resizeOrCreate(cpuSeq2BatchIdx_, batchSize, false);
  }

  /*
   * calculate the length of each sequence & sort sequence index by the length
   * Exampel:  Sequences = {s0, s1, s2}
   *           s0: 0 0 0 0, s1: 1 1 1 1 1, s2: 2 2 2
   *           seqStartAndLength[3] = {(4, 5, 1), (0, 4, 0), (9, 3, 2)}
   */
  struct SeqStartAndLength {
    int start_;
    int length_;
    int seqIdx_;
    SeqStartAndLength(int start, int length, int seqIdx)
        : start_(start), length_(length), seqIdx_(seqIdx) {}
  };
  std::vector<SeqStartAndLength> seqStartAndLength;
  for (size_t seqId = 0; seqId < numSequences; ++seqId) {
    int length = seqStarts[seqId + 1] - seqStarts[seqId];
    seqStartAndLength.emplace_back(seqStarts[seqId], length, seqId);
  }
54 55
  std::sort(seqStartAndLength.begin(),
            seqStartAndLength.end(),
Z
zhangjinchao01 已提交
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 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
            [](SeqStartAndLength a, SeqStartAndLength b) {
              return a.length_ > b.length_;
            });

  /*
   * calculate the start position of each batch
   * (numBatch equal the maxLength of sequences)
   * Exampel:  Sequences = {s0, s1, s2}
   *           s0: 0 0 0 0, s1: 1 1 1 1 1, s2: 2 2 2
   *           numBatch = 5,
   *           batchIndex = {b0, b1, b2, b3, b4}
   *           b0: 1 0 2, b1: 1 0 2, b2: 1 0 2, b3: 1 0, b4: 1
   *           batchStartPositions[6] = {0, 3, 6, 9, 11, 12}
   */
  numBatch_ = (size_t)seqStartAndLength[0].length_;

  IVector::resizeOrCreate(batchStartPositions_, numBatch_ + 1, false);
  int *batchStartPositions = batchStartPositions_->getData();
  batchStartPositions[0] = 0;
  for (size_t n = 0; n < numBatch_; n++) {
    int batchId = batchStartPositions[n];
    for (size_t i = 0; i < seqStartAndLength.size(); ++i) {
      size_t seqLength = seqStartAndLength[i].length_;
      int start = seqStartAndLength[i].start_;
      if (n < seqLength) {
        if (!reversed) {
          cpuSeq2BatchIdx_->getData()[batchId] = start + n;
        } else {
          cpuSeq2BatchIdx_->getData()[batchId] = start + seqLength - 1 - n;
        }
        batchId++;
      } else {
        break;
      }
    }
    batchStartPositions[n + 1] = batchId;
  }
  if (useGpu_) {
    seq2BatchIdx_->copyFrom(*cpuSeq2BatchIdx_);
  }
  if (prevBatchState) {
    IVector::resizeOrCreate(seqIdx_, numSequences, useGpu_);
    IVector::resizeOrCreate(seqEndIdxInBatch_, numSequences, useGpu_);
    if (!useGpu_) {
      cpuSeqIdx_ = seqIdx_;
      cpuSeqEndIdxInBatch_ = seqEndIdxInBatch_;
    } else {
      IVector::resizeOrCreate(cpuSeqIdx_, numSequences, false);
      IVector::resizeOrCreate(cpuSeqEndIdxInBatch_, numSequences, false);
    }
    int *seqIdx = cpuSeqIdx_->getData();
    int *seqEndIdxInBatch = cpuSeqEndIdxInBatch_->getData();
    for (size_t i = 0; i < seqStartAndLength.size(); ++i) {
      seqIdx[i] = seqStartAndLength[i].seqIdx_;
    }
    for (size_t i = 0; i < seqStartAndLength.size(); ++i) {
      if (seqStartAndLength[i].length_ > 0) {
        seqEndIdxInBatch[seqStartAndLength[i].seqIdx_] =
            batchStartPositions[seqStartAndLength[i].length_ - 1] + i;
      } else {
        seqEndIdxInBatch[seqStartAndLength[i].seqIdx_] = 0;
      }
    }
    if (useGpu_) {
      seqIdx_->copyFrom(*cpuSeqIdx_);
      seqEndIdxInBatch_->copyFrom(*cpuSeqEndIdxInBatch_);
    }
  }
}

void SequenceToBatch::resizeOrCreate(Matrix &seqValue) {
127 128 129 130 131
  Matrix::resizeOrCreate(batchValue_,
                         seqValue.getHeight(),
                         seqValue.getWidth(),
                         /* trans= */ false,
                         useGpu_);
Z
zhangjinchao01 已提交
132 133 134 135 136 137
}

MatrixPtr SequenceToBatch::getBatchValue(int batchId, int numRows) {
  return getBatchValue(*batchValue_, batchId, numRows);
}

138 139
MatrixPtr SequenceToBatch::getBatchValue(Matrix &batchValue,
                                         int batchId,
Z
zhangjinchao01 已提交
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
                                         int numRows) {
  int *batchStartPositions = batchStartPositions_->getData();
  int start = batchStartPositions[batchId];
  int maxRows = batchStartPositions[batchId + 1] - batchStartPositions[batchId];
  if (numRows == 0) {
    numRows = maxRows;
  } else {
    CHECK_LE(numRows, maxRows);
  }
  return batchValue.subMatrix(start, numRows);
}

void SequenceToBatch::prevOutput2Batch(Matrix &src, Matrix &dst) {
  sequence2BatchCopy(dst, src, *seqIdx_, true);
}

void SequenceToBatch::getSeqOutputFromBatch(Matrix &sequence, Matrix &batch) {
  sequence2BatchCopy(sequence, batch, *seqEndIdxInBatch_, true);
}

160 161
void SequenceToBatch::sequence2BatchCopy(Matrix &batch,
                                         Matrix &sequence,
Z
zhangjinchao01 已提交
162 163 164 165 166 167 168 169 170
                                         IVector &seq2BatchIdx,
                                         bool seq2batch) {
  int seqWidth = sequence.getWidth();
  int batchCount = batch.getHeight();
  real *batchData = batch.getData();
  real *seqData = sequence.getData();
  int *idxData = seq2BatchIdx.getData();

  if (useGpu_) {
171 172
    hl_sequence2batch_copy(
        batchData, seqData, idxData, seqWidth, batchCount, seq2batch);
Z
zhangjinchao01 已提交
173 174 175
  } else {
    for (int i = 0; i < batchCount; ++i) {
      if (seq2batch) {
176 177
        memcpy(batch.rowBuf(i),
               sequence.rowBuf(idxData[i]),
Z
zhangjinchao01 已提交
178 179
               seqWidth * sizeof(real));
      } else {
180 181
        memcpy(sequence.rowBuf(idxData[i]),
               batch.rowBuf(i),
Z
zhangjinchao01 已提交
182 183 184 185 186 187
               seqWidth * sizeof(real));
      }
    }
  }
}

188 189 190 191
void SequenceToBatch::sequence2BatchAdd(Matrix &batch,
                                        Matrix &sequence,
                                        IVector &seq2BatchIdx,
                                        bool seq2batch) {
Z
zhangjinchao01 已提交
192 193 194 195 196 197 198
  int seqWidth = sequence.getWidth();
  int batchCount = batch.getHeight();
  real *batchData = batch.getData();
  real *seqData = sequence.getData();
  int *idxData = seq2BatchIdx.getData();

  if (useGpu_) {
199 200
    hl_sequence2batch_add(
        batchData, seqData, idxData, seqWidth, batchCount, seq2batch);
Z
zhangjinchao01 已提交
201 202 203 204 205 206 207 208 209 210 211 212
  } else {
    for (int i = 0; i < batchCount; ++i) {
      if (seq2batch) {
        batch.subMatrix(i, 1)->add(*sequence.subMatrix(idxData[i], 1));
      } else {
        sequence.subMatrix(idxData[i], 1)->add(*batch.subMatrix(i, 1));
      }
    }
  }
}

void SequenceToBatch::copyFromSeq(Matrix &seqValue) {
213 214 215 216 217
  Matrix::resizeOrCreate(batchValue_,
                         seqValue.getHeight(),
                         seqValue.getWidth(),
                         /* trans= */ false,
                         useGpu_);
Z
zhangjinchao01 已提交
218 219 220 221 222 223 224
  sequence2BatchCopy(*batchValue_, seqValue, *seq2BatchIdx_, true);
}

void SequenceToBatch::copyBackSeq(Matrix &seqValue) {
  sequence2BatchCopy(*batchValue_, seqValue, *seq2BatchIdx_, false);
}

225 226
void SequenceToBatch::copy(Matrix &seqValue,
                           Matrix &batchValue,
Z
zhangjinchao01 已提交
227 228 229 230
                           bool seq2batch) {
  sequence2BatchCopy(batchValue, seqValue, *seq2BatchIdx_, seq2batch);
}

231 232
void SequenceToBatch::add(Matrix &seqValue,
                          Matrix &batchValue,
Z
zhangjinchao01 已提交
233 234 235 236 237
                          bool seq2batch) {
  sequence2BatchAdd(batchValue, seqValue, *seq2BatchIdx_, seq2batch);
}

}  // namespace paddle