SequenceToBatch.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 "SequenceToBatch.h"
#include <string.h>
Y
Yu Yang 已提交
17 18 19
#include <algorithm>
#include <iostream>
#include <vector>
Z
zhangjinchao01 已提交
20 21 22

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
  } else {
174
    if (seq2batch) {
175
#ifdef PADDLE_USE_MKLML
176 177 178 179 180 181 182 183 184 185 186
      const int blockMemSize = 8 * 1024;
      const int blockSize = blockMemSize / sizeof(real);
#pragma omp parallel for collapse(2)
      for (int i = 0; i < batchCount; ++i) {
        for (int j = 0; j < seqWidth; j += blockSize) {
          memcpy(batch.rowBuf(i) + j,
                 sequence.rowBuf(idxData[i]) + j,
                 (j + blockSize > seqWidth) ? (seqWidth - j) * sizeof(real)
                                            : blockMemSize);
        }
      }
187 188 189 190 191 192 193
#else
      for (int i = 0; i < batchCount; ++i) {
        memcpy(batch.rowBuf(i),
               sequence.rowBuf(idxData[i]),
               seqWidth * sizeof(real));
      }
#endif
194 195 196 197 198
    } else {
#ifdef PADDLE_USE_MKLML
#pragma omp parallel for
#endif
      for (int i = 0; i < batchCount; ++i) {
199 200
        memcpy(sequence.rowBuf(idxData[i]),
               batch.rowBuf(i),
Z
zhangjinchao01 已提交
201 202 203 204 205 206
               seqWidth * sizeof(real));
      }
    }
  }
}

207 208 209 210
void SequenceToBatch::sequence2BatchAdd(Matrix &batch,
                                        Matrix &sequence,
                                        IVector &seq2BatchIdx,
                                        bool seq2batch) {
Z
zhangjinchao01 已提交
211 212 213 214 215 216 217
  int seqWidth = sequence.getWidth();
  int batchCount = batch.getHeight();
  real *batchData = batch.getData();
  real *seqData = sequence.getData();
  int *idxData = seq2BatchIdx.getData();

  if (useGpu_) {
218 219
    hl_sequence2batch_add(
        batchData, seqData, idxData, seqWidth, batchCount, seq2batch);
Z
zhangjinchao01 已提交
220 221 222 223 224 225 226 227 228 229 230 231
  } 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) {
232 233 234 235 236
  Matrix::resizeOrCreate(batchValue_,
                         seqValue.getHeight(),
                         seqValue.getWidth(),
                         /* trans= */ false,
                         useGpu_);
Z
zhangjinchao01 已提交
237 238 239 240 241 242 243
  sequence2BatchCopy(*batchValue_, seqValue, *seq2BatchIdx_, true);
}

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

244 245
void SequenceToBatch::copy(Matrix &seqValue,
                           Matrix &batchValue,
Z
zhangjinchao01 已提交
246 247 248 249
                           bool seq2batch) {
  sequence2BatchCopy(batchValue, seqValue, *seq2BatchIdx_, seq2batch);
}

250 251
void SequenceToBatch::add(Matrix &seqValue,
                          Matrix &batchValue,
Z
zhangjinchao01 已提交
252 253 254 255 256
                          bool seq2batch) {
  sequence2BatchAdd(batchValue, seqValue, *seq2BatchIdx_, seq2batch);
}

}  // namespace paddle