Argument.cpp 24.1 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

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 "Argument.h"
16
#include "paddle/math/SparseMatrix.h"
Z
zhangjinchao01 已提交
17 18 19 20

#include <algorithm>

namespace paddle {
21 22 23
static void resizeAndCopy(MatrixPtr& dest,
                          const MatrixPtr& src,
                          bool useGpu,
Z
zhangjinchao01 已提交
24 25
                          hl_stream_t stream) {
  if (src) {
26 27 28 29 30 31
    if (!dest) {
      dest = src->clone(0, 0, useGpu);
    } else {
      CHECK_EQ(dest->useGpu(), useGpu);
      dest->resize(src->getHeight(), src->getWidth());
    }
Z
zhangjinchao01 已提交
32 33 34 35 36 37
    dest->copyFrom(*src, stream);
  } else {
    dest.reset();
  }
}

38 39 40
static void resizeAndCopy(IVectorPtr& dest,
                          const IVectorPtr& src,
                          bool useGpu,
Z
zhangjinchao01 已提交
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
                          hl_stream_t stream) {
  if (src) {
    IVector::resizeOrCreate(dest, src->getSize(), useGpu);
    dest->copyFrom(*src, stream);
  } else {
    dest.reset();
  }
}

static void resizeAndCopy(ICpuGpuVectorPtr& dest,
                          const ICpuGpuVectorPtr& src,
                          bool useGpu,
                          hl_stream_t stream) {
  if (src) {
    ICpuGpuVector::resizeOrCreate(dest, src->getSize(), useGpu);
    dest->copyFrom(*src, stream);
  } else {
    dest.reset();
  }
}

62 63 64 65 66
static void resizeAndCopy(MatrixPtr& dest,
                          const MatrixPtr& src,
                          int32_t startRow,
                          int32_t copySize,
                          bool useGpu,
Z
zhangjinchao01 已提交
67 68 69 70 71
                          hl_stream_t stream = HPPL_STREAM_DEFAULT) {
  if (src) {
    CHECK_LE((size_t)startRow + copySize, src->getHeight());
    int height = copySize;
    int width = src->getWidth();
72 73 74 75 76 77
    if (!dest) {
      dest = src->clone(height, width, useGpu);
    } else {
      CHECK_EQ(dest->useGpu(), useGpu);
      dest->resize(height, width);
    }
Z
zhangjinchao01 已提交
78
    MatrixPtr submat = src->subMatrix(startRow, copySize);
79 80 81 82 83 84 85 86 87
    if (dynamic_cast<GpuSparseMatrix*>(dest.get())) {
      // copy a subMatrix of CpuSparseMatrix to GpuSparseMatrix.
      // First copy it to CPU, and then copy it to the GPU.
      MatrixPtr tmp = src->clone(height, width, false);
      tmp->copyFrom(*submat, stream);
      dest->copyFrom(*tmp, stream);
    } else {
      dest->copyFrom(*submat, stream);
    }
Z
zhangjinchao01 已提交
88 89 90 91 92
  } else {
    dest.reset();
  }
}

93 94 95 96 97
static void resizeAndCopy(IVectorPtr& dest,
                          const IVectorPtr& src,
                          int32_t startPos,
                          int32_t copySize,
                          bool useGpu,
Z
zhangjinchao01 已提交
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
                          hl_stream_t stream = HPPL_STREAM_DEFAULT) {
  if (src) {
    CHECK_LE((size_t)startPos + copySize, src->getSize());

    int height = copySize;
    IVector::resizeOrCreate(dest, height, useGpu);
    dest->copyFrom(src->getData() + startPos, height, stream);
  } else {
    dest.reset();
  }
}

static void resizeAndCopy(ICpuGpuVectorPtr& dest,
                          const ICpuGpuVectorPtr& src,
                          int32_t startPos,
                          int32_t copySize,
                          bool useGpu,
                          hl_stream_t stream = HPPL_STREAM_DEFAULT) {
  if (src) {
    CHECK_LE((size_t)startPos + copySize, src->getSize());

    ICpuGpuVector::resizeOrCreate(dest, copySize, useGpu);
    dest->copyFrom(*src, startPos, copySize, useGpu, stream);
  } else {
    dest.reset();
  }
}

126 127 128
static void resizeAndCopy(SVectorPtr& dest,
                          const SVectorPtr& src,
                          bool useGpu,
Z
zhangjinchao01 已提交
129 130 131 132 133 134 135 136 137 138 139 140 141 142
                          hl_stream_t stream) {
  if (src) {
    size_t height = src->size();
    if (!dest) {
      dest = std::make_shared<std::vector<std::string>>(height);
    } else {
      dest->resize(height);
    }
    std::copy_n(src->begin(), height, dest->begin());
  } else {
    dest.reset();
  }
}

143 144 145 146 147
static void resizeAndCopy(SVectorPtr& dest,
                          const SVectorPtr& src,
                          int32_t startPos,
                          int32_t copySize,
                          bool useGpu,
Z
zhangjinchao01 已提交
148 149 150 151 152 153 154 155 156 157 158 159 160 161 162
                          hl_stream_t stream = HPPL_STREAM_DEFAULT) {
  if (src) {
    CHECK_LE((size_t)startPos + copySize, src->size());
    size_t height = copySize;
    if (!dest) {
      dest = std::make_shared<std::vector<std::string>>(height);
    } else {
      dest->resize(height);
    }
    std::copy_n(src->begin() + startPos, height, dest->begin());
  } else {
    dest.reset();
  }
}

163
void Argument::resizeAndCopyFrom(const Argument& src, bool useGpu) {
164 165
  resizeAndCopyFrom(src, useGpu, HPPL_STREAM_DEFAULT);
  hl_stream_synchronize(HPPL_STREAM_DEFAULT);
166 167
}

168 169
void Argument::resizeAndCopyFrom(const Argument& src,
                                 bool useGpu,
Z
zhangjinchao01 已提交
170 171 172 173 174 175
                                 hl_stream_t stream) {
  dataId = src.dataId;
  resizeAndCopy(value, src.value, useGpu, stream);
  resizeAndCopy(grad, src.grad, useGpu, stream);
  resizeAndCopy(in, src.in, useGpu, stream);
  resizeAndCopy(ids, src.ids, useGpu, stream);
176 177 178 179
  resizeAndCopy(sequenceStartPositions,
                src.sequenceStartPositions,
                false /* useGpu */,
                stream);
Z
zhangjinchao01 已提交
180 181
  if (src.hasSubseq()) {
    resizeAndCopy(subSequenceStartPositions,
182 183 184
                  src.subSequenceStartPositions,
                  false /* useGpu */,
                  stream);
Z
zhangjinchao01 已提交
185 186
  }
  resizeAndCopy(strs, src.strs, useGpu, stream);
L
Luo Tao 已提交
187 188
  frameWidth = src.frameWidth;
  frameHeight = src.frameHeight;
189
  frameDepth = src.frameDepth;
Z
zhangjinchao01 已提交
190 191
}

192 193 194 195 196 197 198 199
int32_t Argument::resizeAndCopyFrom(const Argument& src,
                                    int32_t startSeq,
                                    int32_t copySize,
                                    bool useGpu) {
  int32_t size =
      resizeAndCopyFrom(src, startSeq, copySize, useGpu, HPPL_STREAM_DEFAULT);
  hl_stream_synchronize(HPPL_STREAM_DEFAULT);
  return size;
200 201
}

202 203 204 205
int32_t Argument::resizeAndCopyFrom(const Argument& src,
                                    int32_t startSeq,
                                    int32_t copySize,
                                    bool useGpu,
Z
zhangjinchao01 已提交
206 207
                                    hl_stream_t stream) {
  dataId = src.dataId;
208 209
  frameWidth = src.frameWidth;
  frameHeight = src.frameHeight;
210
  frameDepth = src.frameDepth;
Z
zhangjinchao01 已提交
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230

  if (!src.sequenceStartPositions) {
    // non-sequence input, copy samples directly
    int32_t startRow = startSeq;
    resizeAndCopy(in, src.in, startRow, copySize, useGpu, stream);
    resizeAndCopy(value, src.value, startRow, copySize, useGpu, stream);
    resizeAndCopy(grad, src.grad, startRow, copySize, useGpu, stream);
    resizeAndCopy(ids, src.ids, startRow, copySize, useGpu, stream);
    resizeAndCopy(strs, src.strs, startRow, copySize, useGpu, stream);
    return copySize;
  } else {
    // sequence input
    const int* sequence = src.sequenceStartPositions->getData(false);
    int32_t startRow = sequence[startSeq];           // sample start from here
    int32_t endRow = sequence[startSeq + copySize];  // sample end
    int32_t copyFeatureSize = endRow - startRow;     // num of samples
    resizeAndCopy(in, src.in, startRow, copyFeatureSize, useGpu, stream);
    resizeAndCopy(value, src.value, startRow, copyFeatureSize, useGpu, stream);
    resizeAndCopy(grad, src.grad, startRow, copyFeatureSize, useGpu, stream);
    resizeAndCopy(ids, src.ids, startRow, copyFeatureSize, useGpu, stream);
231 232 233 234 235 236
    resizeAndCopy(sequenceStartPositions,
                  src.sequenceStartPositions,
                  startSeq,
                  copySize + 1,
                  false,
                  stream);
Z
zhangjinchao01 已提交
237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259
    // modify new sequenceStartPositions
    int* destSequences = sequenceStartPositions->getMutableData(false);
    for (int i = 0; i < copySize + 1; i++) {
      destSequences[i] -= startRow;
    }
    CHECK_EQ(destSequences[0], 0);
    CHECK_EQ(destSequences[copySize], copyFeatureSize);
    if (src.hasSubseq()) {
      // sequence has sub-sequence
      int* subSequence = src.subSequenceStartPositions->getMutableData(false);
      int32_t subStartSeq = 0;
      int32_t subEndSeq = 0;
      int numSubSequences = src.getNumSubSequences();
      for (int i = 0; i < numSubSequences + 1; i++) {
        if (subSequence[i] == startRow) {
          subStartSeq = i;
        } else if (subSequence[i] == endRow) {
          subEndSeq = i;
          break;
        }
      }
      int32_t copySubSize = subEndSeq - subStartSeq;
      resizeAndCopy(subSequenceStartPositions,
260 261 262 263 264
                    src.subSequenceStartPositions,
                    subStartSeq,
                    copySubSize + 1,
                    false,
                    stream);
Z
zhangjinchao01 已提交
265 266 267 268 269 270 271 272 273 274 275 276 277 278 279
      // modify new subSequenceStartPositions
      int* destSubSequences = subSequenceStartPositions->getMutableData(false);
      for (int i = 0; i < copySubSize + 1; i++) {
        destSubSequences[i] -= startRow;
      }
      CHECK_EQ(destSubSequences[0], 0);
      CHECK_EQ(destSubSequences[copySubSize], copyFeatureSize);
    }
    resizeAndCopy(strs, src.strs, startRow, copySize, useGpu, stream);
    return copyFeatureSize;
  }
}

void Argument::concat(const std::vector<Argument>& args,
                      const std::vector<int>& selectRows,
280
                      const std::vector<int>& seqStartPos,
281
                      const std::vector<int>& copySize,
282 283 284
                      bool useGpu,
                      hl_stream_t stream,
                      PassType passType) {
285
  CHECK(!subSequenceStartPositions)
286
      << "undefined behavior for subsequence positions";
287

288 289 290 291
  size_t batchSize = 0;
  for (size_t i = 0; i < copySize.size(); ++i)
    batchSize += copySize[i] * (seqStartPos[i + 1] - seqStartPos[i]);

292 293
  auto copyArg = [batchSize, stream](MatrixPtr& dst,
                                     MatrixPtr src,
294 295
                                     int desStartRow,
                                     int srcStartRow,
296
                                     int size,
Z
zhangjinchao01 已提交
297 298 299 300 301 302 303 304 305 306 307 308
                                     bool useGpu) {
    if (!src) {
      dst.reset();
      return;
    }
    size_t width = src->getWidth();
    if (!dst) {
      dst = src->clone(batchSize, width, useGpu);
    } else {
      dst->resize(batchSize, width);
    }

309 310
    MatrixPtr tmpMatrix = dst->subMatrix(desStartRow, size);
    tmpMatrix->copyFrom(*src->subMatrix(srcStartRow, size), stream);
Z
zhangjinchao01 已提交
311 312
  };

313 314
  auto copyIds = [batchSize, stream](IVectorPtr& dst,
                                     const IVectorPtr& src,
315 316
                                     int desStartRow,
                                     int srcStartRow,
317
                                     int size,
Z
zhangjinchao01 已提交
318 319 320 321 322 323
                                     bool useGpu) {
    if (!src) {
      dst.reset();
      return;
    }
    IVector::resizeOrCreate(dst, batchSize, useGpu);
324 325
    dst->subVec(desStartRow, size)
        ->copyFrom(*src->subVec(srcStartRow, size), stream);
Z
zhangjinchao01 已提交
326 327
  };

328 329
  auto copyStrs = [batchSize, stream](SVectorPtr& dst,
                                      const SVectorPtr& src,
330 331
                                      int desStartRow,
                                      int srcStartRow,
332
                                      int size,
Z
zhangjinchao01 已提交
333 334 335 336 337 338 339 340 341 342
                                      bool useGpu) {
    if (!src) {
      dst.reset();
      return;
    }
    if (!dst) {
      dst = std::make_shared<std::vector<std::string>>(batchSize);
    } else {
      dst->resize(batchSize);
    }
343 344 345
    std::copy(src->begin() + srcStartRow,
              src->begin() + srcStartRow + size,
              dst->begin() + desStartRow);
Z
zhangjinchao01 已提交
346 347 348 349
  };

  dataId = args[0].dataId;
  CHECK_NE(seqStartPos.size(), 0UL);
350 351
  int desStartRow = 0;
  for (size_t i = 0; i < copySize.size(); ++i) {
Z
zhangjinchao01 已提交
352 353 354 355 356
    int startPos = seqStartPos[i];
    int endPos = seqStartPos[i + 1];
    CHECK_GE(args.size(), static_cast<size_t>(endPos - startPos));
    for (int j = startPos; j < endPos; ++j) {
      const Argument& arg = args[j - startPos];
C
caoying03 已提交
357 358
      CHECK_EQ(arg.dataId, dataId) << "Arguments to concatenate should have "
                                   << "the same dataId.";
359 360 361
      const int srcStartRow = selectRows[j];
      copyArg(in, arg.in, desStartRow, srcStartRow, copySize[i], useGpu);
      copyArg(value, arg.value, desStartRow, srcStartRow, copySize[i], useGpu);
Z
zhangjinchao01 已提交
362
      if (passType != PASS_TEST) {
363
        copyArg(grad, arg.grad, desStartRow, srcStartRow, copySize[i], useGpu);
Z
zhangjinchao01 已提交
364
      }
365 366 367
      copyIds(ids, arg.ids, desStartRow, srcStartRow, copySize[i], useGpu);
      copyStrs(strs, arg.strs, desStartRow, srcStartRow, copySize[i], useGpu);
      desStartRow += copySize[i];
Z
zhangjinchao01 已提交
368 369
    }
  }
370 371 372 373
  ICpuGpuVector::resizeOrCreate(
      sequenceStartPositions, seqStartPos.size(), useGpu);
  sequenceStartPositions->copyFrom(
      seqStartPos.data(), seqStartPos.size(), useGpu);
Z
zhangjinchao01 已提交
374 375
}

376 377 378 379
void Argument::concat(const std::vector<Argument>& args,
                      bool useGpu,
                      hl_stream_t stream,
                      PassType passType) {
Z
zhangjinchao01 已提交
380 381
  int32_t batchSize = 0;
  int64_t numSequences = 0;
382
  int64_t numSubSequences = 0;
Z
zhangjinchao01 已提交
383 384 385
  for (auto& arg : args) {
    batchSize += arg.getBatchSize();
    numSequences += arg.getNumSequences();
386
    numSubSequences += arg.getNumSubSequences();
Z
zhangjinchao01 已提交
387 388
  }

389 390
  auto copyArg = [batchSize, stream](
      MatrixPtr& dst, MatrixPtr src, int startRow, bool useGpu) {
Z
zhangjinchao01 已提交
391 392 393 394 395 396 397 398 399 400 401 402 403 404 405
    if (!src) {
      dst.reset();
      return;
    }
    size_t width = src->getWidth();
    if (!dst) {
      dst = src->clone(batchSize, width, useGpu);
    } else {
      dst->resize(batchSize, width);
    }

    MatrixPtr tmpMatrix = dst->subMatrix(startRow, src->getHeight());
    tmpMatrix->copyFrom(*src, stream);
  };

406 407
  auto copyIds = [batchSize, stream](
      IVectorPtr& dst, const IVectorPtr& src, int startRow, bool useGpu) {
Z
zhangjinchao01 已提交
408 409 410 411 412 413 414 415
    if (!src) {
      dst.reset();
      return;
    }
    IVector::resizeOrCreate(dst, batchSize, useGpu);
    dst->subVec(startRow, src->getSize())->copyFrom(*src, stream);
  };

416 417
  auto copyStrs = [batchSize, stream](
      SVectorPtr& dst, const SVectorPtr& src, int startRow, bool useGpu) {
Z
zhangjinchao01 已提交
418 419 420 421 422 423 424 425 426 427 428 429
    if (!src) {
      dst.reset();
      return;
    }
    if (!dst) {
      dst = std::make_shared<std::vector<std::string>>(batchSize);
    } else {
      dst->resize(batchSize);
    }
    std::copy(src->begin(), src->end(), dst->begin() + startRow);
  };

430 431 432 433 434 435 436 437 438 439 440 441
  auto copySequencePos = [](ICpuGpuVectorPtr& dstSeq,
                            const ICpuGpuVectorPtr& srcSeq,
                            int dstNumSequences,
                            int srcNumSequences,
                            int& startSequences,
                            int startRow) {
    if (srcSeq) {
      ICpuGpuVector::resizeOrCreate(dstSeq, dstNumSequences + 1, false);
      const int* src = srcSeq->getData(false);
      int* dest = dstSeq->getMutableData(false);
      for (int i = 0; i < srcNumSequences + 1; ++i) {
        dest[i + startSequences] = src[i] + startRow;
442
      }
443 444 445 446
      startSequences += srcNumSequences;
    } else {
      dstSeq.reset();
    }
447 448
  };

Z
zhangjinchao01 已提交
449 450
  int startRow = 0;
  int startSequences = 0;
451
  int startSubSequences = 0;
Z
zhangjinchao01 已提交
452 453 454 455 456 457 458 459
  dataId = args[0].dataId;
  for (auto& arg : args) {
    CHECK_EQ(arg.dataId, dataId) << "Arguments in concat should have"
                                 << " same dataId";
    copyArg(in, arg.in, startRow, useGpu);
    copyArg(value, arg.value, startRow, useGpu);
    if (passType != PASS_TEST) copyArg(grad, arg.grad, startRow, useGpu);
    copyIds(ids, arg.ids, startRow, useGpu);
460 461 462 463 464 465 466 467 468 469 470 471
    copySequencePos(sequenceStartPositions,
                    arg.sequenceStartPositions,
                    numSequences,
                    arg.getNumSequences(),
                    startSequences,
                    startRow);
    copySequencePos(subSequenceStartPositions,
                    arg.subSequenceStartPositions,
                    numSubSequences,
                    arg.getNumSubSequences(),
                    startSubSequences,
                    startRow);
Z
zhangjinchao01 已提交
472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496
    copyStrs(strs, arg.strs, startRow, useGpu);
    startRow += arg.getBatchSize();
  }
}

void Argument::splitByDataId(const std::vector<Argument>& argus,
                             std::vector<std::vector<Argument>>* arguGroups) {
  arguGroups->clear();
  int lastDataId = -1;
  for (const auto& argu : argus) {
    if (argu.dataId == -1) {
      // is -1, then create a new group
      arguGroups->emplace_back();
      lastDataId = -1;
    } else if (argu.dataId != lastDataId) {
      // not -1, also not equal to last Argument, then create a new group
      arguGroups->emplace_back();
      lastDataId = argu.dataId;
    } else {
      // not -1, and equal to last Argument, do nothing
    }
    arguGroups->back().push_back(argu);
  }
}

497
void Argument::getSeqInfo(std::vector<SeqInfo>* seqInfo) const {
Z
zhangjinchao01 已提交
498
  const int* starts = sequenceStartPositions->getData(false);
499 500
  const int* subStarts =
      hasSubseq() ? subSequenceStartPositions->getData(false) : nullptr;
501 502 503 504 505 506 507 508 509 510 511 512
  size_t numSequences = getNumSequences();
  seqInfo->reserve(numSequences);
  int subSeqEnd = 0;
  for (size_t i = 0; i < numSequences; ++i) {
    SeqInfo info;
    info.seqStart = starts[i];
    info.subLevelLength = starts[i + 1] - starts[i];
    info.seqId = i;
    if (hasSubseq()) {
      info.subSeqStart = subSeqEnd;
      while (subStarts[subSeqEnd] < starts[i + 1]) {
        ++subSeqEnd;
Z
zhangjinchao01 已提交
513
      }
514 515 516 517
      info.topLevelLength = subSeqEnd - info.subSeqStart;
    } else {
      info.topLevelLength = info.subLevelLength;
      info.subSeqStart = 0;  // not used
Z
zhangjinchao01 已提交
518
    }
519
    seqInfo->push_back(info);
Z
zhangjinchao01 已提交
520
  }
Y
Yu Yang 已提交
521 522 523 524
  std::sort(
      seqInfo->begin(), seqInfo->end(), [](const SeqInfo& a, const SeqInfo& b) {
        return a.topLevelLength > b.topLevelLength;
      });
Z
zhangjinchao01 已提交
525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550
}

void Argument::checkSubset() const {
  if (getNumSequences() > getNumSubSequences()) {
    LOG(FATAL) << "numSubSequences is less than numSequences ("
               << getNumSubSequences() << " vs. " << getNumSequences() << ")";
  }
  const int* start = sequenceStartPositions->getData(false);
  const int* subStart = subSequenceStartPositions->getData(false);
  int seqId = 0;
  int subSeqId = 0;
  while (seqId < getNumSequences() && subSeqId < getNumSubSequences()) {
    if (start[seqId] > subStart[subSeqId]) {
      ++subSeqId;
    } else if (start[seqId] == subStart[subSeqId]) {
      ++subSeqId;
      ++seqId;
    } else {
      LOG(FATAL) << "seqStartPositions is not subset of subSeqStartPositions";
    }
  }
  if (seqId < getNumSequences()) {
    LOG(FATAL) << "seqStartPositions is not subset of subSeqStartPositions";
  }
}

551
void Argument::degradeSequence(const Argument& input) {
Z
zhangjinchao01 已提交
552 553 554
  CHECK_EQ(input.hasSubseq(), 1UL);
  size_t numSequences = input.getNumSequences();
  size_t numSubSequences = input.getNumSubSequences();
555 556
  ICpuGpuVector::resizeOrCreate(
      sequenceStartPositions, numSequences + 1, false);
Z
zhangjinchao01 已提交
557 558 559 560 561 562 563 564 565 566 567 568 569
  int* tgtBuf = sequenceStartPositions->getMutableData(false);
  const int* starts = input.sequenceStartPositions->getData(false);
  const int* subStarts = input.subSequenceStartPositions->getData(false);
  int seqId = 0;
  for (size_t subSeqId = 0; subSeqId < numSubSequences; ++subSeqId) {
    if (subStarts[subSeqId] == starts[seqId]) {
      tgtBuf[seqId] = subSeqId;
      seqId++;
    }
  }
  tgtBuf[numSequences] = numSubSequences;
}

570 571
void Argument::poolSequenceWithStride(const Argument& input,
                                      size_t stride,
572
                                      ICpuGpuVectorPtr* stridePostions,
L
Luo Tao 已提交
573
                                      bool reversed) {
L
Luo Tao 已提交
574 575 576 577 578
  // If input.sequenceStartPositions = [0, 9, 14, 17, 30] and stride = 5,
  // then sequenceStartPositions = [0, 2, 3, 4, 7].
  // If reversed = false, stridePostions = [0, 5, 9, 14, 17, 22, 27, 30];
  // else reversed = true, stridePostions = [0, 4, 9, 14, 17, 20, 25, 30]

579 580
  CHECK(input.sequenceStartPositions);
  CHECK_EQ(input.hasSubseq(), 0UL);
Y
Yu Yang 已提交
581
  CHECK_GT(stride, 0UL) << "stride must larger than 0";
582 583 584 585 586 587 588
  size_t numSequences = input.getNumSequences();
  ICpuGpuVector::resizeOrCreate(
      sequenceStartPositions, numSequences + 1, false);
  const int* starts = input.sequenceStartPositions->getData(false);
  int* tgtBuf = sequenceStartPositions->getMutableData(false);
  // first index of target sequence and stride positions are both 0
  tgtBuf[0] = 0;
589
  std::vector<int> stridePos;
590 591
  for (size_t seqId = 0; seqId < numSequences; ++seqId) {
    size_t seqLength = starts[seqId + 1] - starts[seqId];
592
    stridePos.emplace_back(starts[seqId]);
593 594 595 596
    if (seqLength == 0) {
      // empty sequence
      tgtBuf[seqId + 1] = tgtBuf[seqId];
    } else {
L
Luo Tao 已提交
597 598
      int size = ceil((float)seqLength / stride);
      tgtBuf[seqId + 1] = tgtBuf[seqId] + size;
L
Luo Tao 已提交
599
      for (int i = 0; i < size - 1; ++i) {
L
Luo Tao 已提交
600 601 602
        int cur = reversed ? starts[seqId + 1] - (size - 1 - i) * stride
                           : stridePos.back() + stride;
        stridePos.emplace_back(cur);
603 604 605
      }
    }
  }
606 607 608
  stridePos.emplace_back(starts[numSequences]);
  int size = stridePos.size();
  CHECK_EQ(size - 1, tgtBuf[numSequences]);
609 610
  ICpuGpuVector::resizeOrCreate(*stridePostions, size, false);
  (*stridePostions)->getMutableVector(false)->copyFrom(stridePos.data(), size);
611 612
}

613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638
void Argument::getValueString(
    std::unordered_map<std::string, std::string>* out) const {
  if (value) {
    std::ostringstream os;
    value->print(os);
    out->insert({"value", os.str()});
  }
  if (ids) {
    std::ostringstream os;
    ids->print(os, ids->getSize());
    out->insert({"ids", os.str()});
  }
  if (sequenceStartPositions) {
    std::ostringstream os;
    sequenceStartPositions->getVector(false)->print(
        os, sequenceStartPositions->getSize());
    out->insert({"sequence pos", os.str()});
  }
  if (subSequenceStartPositions) {
    std::ostringstream os;
    subSequenceStartPositions->getVector(false)->print(
        os, subSequenceStartPositions->getSize());
    out->insert({"sub-sequence pos", os.str()});
  }
}

639 640 641 642
void Argument::printValueString(std::ostream& stream,
                                const std::string& prefix) const {
  std::unordered_map<std::string, std::string> out;
  getValueString(&out);
643
  for (auto field : {"value", "ids", "sequence pos", "sub-sequence pos"}) {
644 645 646 647 648 649 650
    auto it = out.find(field);
    if (it != out.end()) {
      stream << prefix << field << ":\n" << it->second;
    }
  }
}

651 652 653 654 655 656 657 658 659
void Argument::subArgFrom(const Argument& input,
                          size_t offset,
                          size_t height,
                          size_t width,
                          bool useGpu,
                          bool trans,
                          bool seqFlag,
                          size_t seqStart,
                          size_t seqSize) {
660
  if (input.value) {
661 662
    value = Matrix::create(
        input.value->getData() + offset * width, height, width, trans, useGpu);
663 664 665 666
  }
  if (input.ids) {
    ids = IVector::create(input.ids->getData() + offset, height, useGpu);
  }
Z
zhangjinchao01 已提交
667
  if (input.grad) {
668 669
    grad = Matrix::create(
        input.grad->getData() + offset * width, height, width, trans, useGpu);
Z
zhangjinchao01 已提交
670 671 672
  }
  if (seqFlag) {
    sequenceStartPositions = std::make_shared<ICpuGpuVector>(
673
        *(input.sequenceStartPositions), seqStart, seqSize);
Z
zhangjinchao01 已提交
674 675 676
  }
}

C
caoying03 已提交
677 678 679 680
void Argument::reorganizeSeqInfo(
    const ICpuGpuVectorPtr seqStartPos,
    const ICpuGpuVectorPtr subSeqStartPos,
    std::vector<std::vector<int>>& reorganizedSeqInfo) {
C
caoying03 已提交
681
  CHECK(seqStartPos);
C
caoying03 已提交
682
  reorganizedSeqInfo.clear();
C
caoying03 已提交
683 684

  int seqNum = seqStartPos->getSize() - 1;
C
caoying03 已提交
685 686 687 688 689 690 691
  int* seqStarts = seqStartPos->getMutableData(false);

  if (subSeqStartPos) {
    int* subSeqStarts = subSeqStartPos->getMutableData(false);
    reorganizedSeqInfo.resize(seqNum, std::vector<int>());
    int seqIdx = 0;
    for (size_t i = 0; i < subSeqStartPos->getSize(); ++i) {
C
caoying03 已提交
692
      reorganizedSeqInfo[seqIdx].push_back(subSeqStarts[i]);
C
caoying03 已提交
693 694 695 696 697
      if (subSeqStarts[i] == seqStarts[seqIdx + 1]) {
        seqIdx++;
        if (seqIdx == seqNum) return;
        reorganizedSeqInfo[seqIdx].push_back(subSeqStarts[i]);
      }
C
caoying03 已提交
698
    }
C
caoying03 已提交
699 700 701 702 703
  } else {
    reorganizedSeqInfo.resize(1, std::vector<int>(seqNum + 1, 0));
    memcpy(reorganizedSeqInfo[0].data(),
           seqStarts,
           sizeof(int) * seqStartPos->getSize());
C
caoying03 已提交
704 705 706
  }
}

Z
zhangjinchao01 已提交
707
}  // namespace paddle