test_matrixCompare.cpp 44.2 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

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. */

#ifndef PADDLE_ONLY_CPU
/// This unittest checks GpuMatrix/CpuMatrix get same result, so disable when
/// only cpu version.

#include <gtest/gtest.h>
Y
Yu Yang 已提交
20 21 22
#include "TensorCheck.h"
#include "paddle/math/Matrix.h"
#include "paddle/math/SparseMatrix.h"
23
#include "paddle/testing/TestUtil.h"
L
liaogang 已提交
24
#include "paddle/utils/DynamicLoader.h"
25
#include "paddle/utils/Stat.h"
Y
Yu Yang 已提交
26
#include "paddle/utils/Util.h"
27

Z
zhangjinchao01 已提交
28 29
using namespace paddle;  // NOLINT
using namespace std;     // NOLINT
30 31
using autotest::TensorCheckEqual;
using autotest::TensorCheckErr;
L
liaogang 已提交
32

Z
zhangjinchao01 已提交
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
void testMatrixMaxSequence(int batchSize, int inputDim) {
  // forward
  MatrixPtr cpuInput = std::make_shared<CpuMatrix>(batchSize, inputDim);
  MatrixPtr gpuInput = std::make_shared<GpuMatrix>(batchSize, inputDim);
  cpuInput->randomizeUniform();
  gpuInput->copyFrom(*cpuInput);

  IVectorPtr cpuSequence;
  generateSequenceStartPositions(batchSize, cpuSequence);
  IVectorPtr gpuSequence = IVector::create(cpuSequence->getSize(), true);
  gpuSequence->copyFrom(*cpuSequence);

  int newBatchSize = cpuSequence->getSize() - 1;
  MatrixPtr cpuOutput = std::make_shared<CpuMatrix>(newBatchSize, inputDim);
  MatrixPtr gpuOutput = std::make_shared<GpuMatrix>(newBatchSize, inputDim);
  cpuOutput->zero();
  gpuOutput->zero();

  IVectorPtr cpuIndex = nullptr;
  IVectorPtr gpuIndex = nullptr;
  IVector::resizeOrCreate(cpuIndex, newBatchSize * inputDim, false);
  IVector::resizeOrCreate(gpuIndex, newBatchSize * inputDim, true);
  cpuIndex->zeroMem();
  gpuIndex->zeroMem();

  cpuOutput->maxSequenceForward(*cpuInput, *cpuSequence, *cpuIndex);
  gpuOutput->maxSequenceForward(*gpuInput, *gpuSequence, *gpuIndex);

61 62
  TensorCheckEqual(*cpuOutput, *gpuOutput);
  TensorCheckEqual(*cpuIndex, *gpuIndex);
Z
zhangjinchao01 已提交
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77

  // backward
  MatrixPtr cpuOutputGrad = std::make_shared<CpuMatrix>(newBatchSize, inputDim);
  MatrixPtr gpuOutputGrad = std::make_shared<GpuMatrix>(newBatchSize, inputDim);
  cpuOutputGrad->randomizeUniform();
  gpuOutputGrad->copyFrom(*cpuOutputGrad);

  MatrixPtr cpuInputGrad = std::make_shared<CpuMatrix>(batchSize, inputDim);
  MatrixPtr gpuInputGrad = std::make_shared<GpuMatrix>(batchSize, inputDim);
  cpuInputGrad->randomizeUniform();
  gpuInputGrad->copyFrom(*cpuInputGrad);

  cpuInputGrad->maxSequenceBackward(*cpuOutputGrad, *cpuSequence, *cpuIndex);
  gpuInputGrad->maxSequenceBackward(*gpuOutputGrad, *gpuSequence, *gpuIndex);

78
  TensorCheckEqual(*cpuInputGrad, *gpuInputGrad);
Z
zhangjinchao01 已提交
79 80 81
}

TEST(Matrix, maxSequence) {
Y
Yi Wang 已提交
82 83
  for (auto batchSize : {1, 3, 997}) {   // prime numbers close to 1, 4, 1024
    for (auto inputDim : {1, 7, 131}) {  // prime numbers close to 1, 8, 128
Z
zhangjinchao01 已提交
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
      VLOG(3) << " batchSize=" << batchSize << " inputDim=" << inputDim;
      testMatrixMaxSequence(batchSize, inputDim);
    }
  }
}

void testMatrixGetSum(int height, int width) {
  MatrixPtr cpuInput = std::make_shared<CpuMatrix>(height, width);
  MatrixPtr gpuInput = std::make_shared<GpuMatrix>(height, width);
  cpuInput->randomizeUniform();
  gpuInput->copyFrom(*cpuInput);

#ifndef PADDLE_TYPE_DOUBLE
  int x = log10(height * width);
  real err = 1e-6 * pow(10, x);
#else
  real err = 1e-8;
#endif

  real cpuSum = cpuInput->getSum();
  real gpuSum = gpuInput->getSum();

  EXPECT_LE(fabs(cpuSum - gpuSum), err);
}

109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
void testMatrixGetMinMax(int height, int width) {
  MatrixPtr cpuInput = std::make_shared<CpuMatrix>(height, width);
  MatrixPtr gpuInput = std::make_shared<GpuMatrix>(height, width);
  cpuInput->randomizeUniform();
  gpuInput->copyFrom(*cpuInput);

  real cpuMin = cpuInput->getMin();
  real gpuMin = gpuInput->getMin();
  real cpuMax = cpuInput->getMax();
  real gpuMax = gpuInput->getMax();

  EXPECT_EQ(cpuMin, gpuMin);
  EXPECT_EQ(cpuMax, gpuMax);
}

Z
zhangjinchao01 已提交
124 125 126 127 128 129 130 131 132 133 134 135
void testMatrixZeroAtOffset(int height, int width) {
  MatrixPtr cpuA = std::make_shared<CpuMatrix>(height, width);
  MatrixPtr gpuA = std::make_shared<GpuMatrix>(height, width);
  MatrixPtr cpuTest = std::make_shared<CpuMatrix>(height, width);

  cpuA->randomizeUniform();
  gpuA->copyFrom(*cpuA);
  cpuTest->copyFrom(*cpuA);

  int columnOffset = rand() % width;  // NOLINT we just use rand() for test.
  int numColumns = rand() % (width - columnOffset);  // NOLINT

136 137
  if (numColumns == 0) return;

Z
zhangjinchao01 已提交
138 139 140 141 142 143 144 145 146 147 148
  cpuA->zeroAtOffset(columnOffset, numColumns);
  gpuA->zeroAtOffset(columnOffset, numColumns);

  /* cpuTest */
  real* a = cpuTest->getData() + columnOffset;
  for (int64_t i = 0; i < height; ++i) {
    for (int64_t j = 0; j < numColumns; ++j) {
      a[i * width + j] = 0;
    }
  }

149 150
  TensorCheckEqual(*cpuA, *gpuA);
  TensorCheckEqual(*cpuA, *cpuTest);
Z
zhangjinchao01 已提交
151 152
}

X
xutianbing 已提交
153 154 155 156 157 158 159 160 161 162 163 164 165 166
void testMatrixDeepSwap(int height, int width) {
  MatrixPtr cpuA = std::make_shared<CpuMatrix>(height, width);
  MatrixPtr cpuB = std::make_shared<CpuMatrix>(height, width);
  MatrixPtr cpuCopyA = std::make_shared<CpuMatrix>(height, width);
  MatrixPtr cpuCopyB = std::make_shared<CpuMatrix>(height, width);

  cpuA->randomizeUniform();
  cpuB->randomizeUniform();
  cpuCopyA->copyFrom(*cpuA);
  cpuCopyB->copyFrom(*cpuB);

  // swap matrix cpuA and cpuB
  cpuA->deepSwap(*cpuB);

H
hedaoyuan 已提交
167 168
  TensorCheckEqual(*cpuA, *cpuCopyB);
  TensorCheckEqual(*cpuB, *cpuCopyA);
X
xutianbing 已提交
169 170
}

Z
zhangjinchao01 已提交
171 172 173 174 175 176 177 178 179
void testMatrixTranspose(int height, int width) {
  MatrixPtr cpu = std::make_shared<CpuMatrix>(height, width);
  MatrixPtr gpu = std::make_shared<GpuMatrix>(height, width);
  MatrixPtr cpuT = std::make_shared<CpuMatrix>(width, height);
  MatrixPtr gpuT = std::make_shared<GpuMatrix>(width, height);

  cpu->randomizeUniform();
  gpu->copyFrom(*cpu);
  cpu->transpose(cpuT, false);
H
Haonan 已提交
180
  gpu->transpose(gpuT, true);
Z
zhangjinchao01 已提交
181

182
  TensorCheckEqual(*cpuT, *gpuT);
Z
zhangjinchao01 已提交
183 184
}

H
Haonan 已提交
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202
void testMatrixRotate(int height, int width) {
  MatrixPtr cpu = std::make_shared<CpuMatrix>(height, width);
  MatrixPtr gpu = std::make_shared<GpuMatrix>(height, width);
  MatrixPtr cpuR = std::make_shared<CpuMatrix>(width, height);
  MatrixPtr gpuR = std::make_shared<GpuMatrix>(width, height);

  cpu->randomizeUniform();
  gpu->copyFrom(*cpu);

  cpu->rotate(cpuR, false, true);
  gpu->rotate(gpuR, true, true);
  TensorCheckEqual(*cpuR, *gpuR);

  cpu->rotate(cpuR, true, false);
  gpu->rotate(gpuR, false, false);
  TensorCheckEqual(*cpuR, *gpuR);
}

L
lzhao4ever 已提交
203 204 205 206 207 208
void testMatrixInverse(int height) {
  MatrixPtr cpu = std::make_shared<CpuMatrix>(height, height);
  MatrixPtr gpu = std::make_shared<GpuMatrix>(height, height);
  MatrixPtr cpuI = std::make_shared<CpuMatrix>(height, height);
  MatrixPtr gpuI = std::make_shared<GpuMatrix>(height, height);

209
  /* Make matrix well conditioned: cpu * cpuT + Identity */
L
lzhao4ever 已提交
210
  cpu->randomizeUniform();
211 212
  MatrixPtr cpuT = cpu->getTranspose();
  MatrixPtr outputCheck = std::make_shared<CpuMatrix>(height, height);
213
  outputCheck->mul(*cpu, *cpuT);
214 215 216
  cpu->setDiag(1.0);
  cpu->add(*outputCheck);

L
lzhao4ever 已提交
217
  gpu->copyFrom(*cpu);
218
  cpu->inverse(cpuI, true);
L
lzhao4ever 已提交
219 220
  gpu->inverse(gpuI, false);

221
  TensorCheckErr(*cpuI, *gpuI);
L
lzhao4ever 已提交
222

223
  outputCheck->mul(*cpu, *cpuI);
224
  cpu->setDiag(1.0);
225
  TensorCheckErr(*cpu, *outputCheck);
L
lzhao4ever 已提交
226 227
}

Z
zhangjinchao01 已提交
228
TEST(Matrix, unary) {
L
lzhao4ever 已提交
229 230
  for (auto height : {1, 3, 11, 73, 128, 200, 330}) {
    for (auto width : {1, 3, 32, 100, 512, 1000, 3210}) {
Z
zhangjinchao01 已提交
231 232
      VLOG(3) << " height=" << height << " width=" << width;

233
      testMatrixDeepSwap(height, width);
234
      testMatrixZeroAtOffset(height, width);
Z
zhangjinchao01 已提交
235 236
      testMatrixGetSum(height, width);
      testMatrixTranspose(height, width);
H
Haonan 已提交
237
      testMatrixRotate(height, width);
Z
zhangjinchao01 已提交
238
    }
L
liaogang 已提交
239
#ifdef LAPACK_FOUND
L
liaogang 已提交
240
    // inverse matrix
241
    testMatrixInverse(height);
L
liaogang 已提交
242
#else
Y
Yi Wang 已提交
243 244 245 246
    LOG(WARNING) << "This version of PaddlePaddle was not built with LAPACK"
                 << "support so we cannot test matrix inverse. To test "
                 << "matrix inverse, please install LAPACKE "
                 << "and MKL/Openblas/ATLAS, and re-build PaddlePaddle.";
L
liaogang 已提交
247
#endif
Z
zhangjinchao01 已提交
248 249 250
  }
}

251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
void testMatrixSoftmax(int height, int width) {
  MatrixPtr cpuInput = std::make_shared<CpuMatrix>(height, width);
  MatrixPtr cpuOutput = std::make_shared<CpuMatrix>(height, width);
  MatrixPtr gpuInput = std::make_shared<GpuMatrix>(height, width);
  MatrixPtr gpuOutput = std::make_shared<GpuMatrix>(height, width);

  cpuInput->randomizeUniform();
  gpuInput->copyFrom(*cpuInput);
  cpuOutput->zero();
  gpuOutput->zero();
  cpuInput->softmax(*cpuOutput);
  gpuInput->softmax(*gpuOutput);

  TensorCheckErr(*cpuOutput, *gpuOutput);
}

Z
zhangjinchao01 已提交
267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
void testSequenceSoftmax(int batchSize) {
  // forward
  int inputDim = 1;
  MatrixPtr cpuInput = std::make_shared<CpuMatrix>(batchSize, inputDim);
  MatrixPtr gpuInput = std::make_shared<GpuMatrix>(batchSize, inputDim);
  cpuInput->randomizeUniform();
  gpuInput->copyFrom(*cpuInput);

  IVectorPtr cpuSequence;
  generateSequenceStartPositions(batchSize, cpuSequence);
  IVectorPtr gpuSequence = IVector::create(cpuSequence->getSize(), true);
  gpuSequence->copyFrom(*cpuSequence);

  cpuInput->sequenceSoftmax(*cpuInput, *cpuSequence);
  gpuInput->sequenceSoftmax(*gpuInput, *gpuSequence);

283
  TensorCheckErr(*cpuInput, *gpuInput);
Z
zhangjinchao01 已提交
284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
}

void testMatrixSoftmaxThreshold(int height, int width) {
  MatrixPtr cpuInput = std::make_shared<CpuMatrix>(height, width);
  MatrixPtr cpuOutput = std::make_shared<CpuMatrix>(height, width);
  MatrixPtr gpuInput = std::make_shared<GpuMatrix>(height, width);
  MatrixPtr gpuOutput = std::make_shared<GpuMatrix>(height, width);

  cpuInput->randomizeUniform();
  cpuInput->getData()[0] = 100.0;
  gpuInput->copyFrom(*cpuInput);
  cpuOutput->zero();
  gpuOutput->zero();
  cpuInput->softmax(*cpuOutput);
  gpuInput->softmax(*gpuOutput);

  MatrixPtr outputCheck = std::make_shared<CpuMatrix>(height, width);
  outputCheck->copyFrom(*gpuOutput);
  // check output zero
  int cpuCount = 0;
  int gpuCount = 0;
  auto zeroNum = [](MatrixPtr out, int& count) {
    for (size_t i = 0; i < out->getHeight(); i++) {
      for (size_t j = 0; j < out->getWidth(); j++) {
        if (out->getElement(i, j) == 0) count++;
      }
    }
  };
  zeroNum(cpuOutput, cpuCount);
  zeroNum(outputCheck, gpuCount);
  EXPECT_EQ(cpuCount, 0) << "Cpu softmax output value 0";
  EXPECT_EQ(gpuCount, 0) << "Gpu softmax output value 0";
}

void testMatrixSoftmaxBp(int height, int width) {
  MatrixPtr cpuInput = std::make_shared<CpuMatrix>(height, width);
  MatrixPtr cpuOutput = std::make_shared<CpuMatrix>(height, width);
  MatrixPtr gpuInput = std::make_shared<GpuMatrix>(height, width);
  MatrixPtr gpuOutput = std::make_shared<GpuMatrix>(height, width);

  cpuInput->randomizeUniform();
  gpuInput->copyFrom(*cpuInput);
  cpuOutput->randomizeUniform();
  gpuOutput->copyFrom(*cpuOutput);
  gpuOutput->softmaxBackward(*gpuInput);

  MatrixPtr sftMaxSum = std::make_shared<CpuMatrix>(height, 1);
  MatrixPtr sftMaxDot = std::make_shared<CpuMatrix>(height, width);
  sftMaxDot->dotMul(*cpuOutput, *cpuInput);
  sftMaxSum->colMerge(*sftMaxDot);
  cpuOutput->softmaxDerivative(*cpuInput, *sftMaxSum);

336
  TensorCheckErr(*cpuOutput, *gpuOutput);
Z
zhangjinchao01 已提交
337 338 339
}

TEST(Matrix, softmax) {
Y
Yi Wang 已提交
340 341
  for (auto height : {1, 3, 131}) {    // prime numbers close to 1, 4, 127
    for (auto width : {1, 17, 251}) {  // prime numbers close to 1, 16, 256
Z
zhangjinchao01 已提交
342 343
      VLOG(3) << " height=" << height << " width=" << width;

344
      testMatrixSoftmax(height, width);
Z
zhangjinchao01 已提交
345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372
      testMatrixSoftmaxBp(height, width);
      testMatrixSoftmaxThreshold(height, width);
    }
    testSequenceSoftmax(height);
  }
}

void testMatrixAddToRows(int numSamples, int tableSize, int inputDim) {
  MatrixPtr cpuTable = std::make_shared<CpuMatrix>(tableSize, inputDim);
  MatrixPtr gpuTable = std::make_shared<GpuMatrix>(tableSize, inputDim);
  cpuTable->randomizeUniform();
  gpuTable->copyFrom(*cpuTable);

  IVectorPtr cpuIds;
  IVectorPtr gpuIds;
  cpuIds = VectorT<int>::create(numSamples, false);
  gpuIds = VectorT<int>::create(numSamples, true);
  cpuIds->rand(tableSize);
  gpuIds->copyFrom(*cpuIds);

  MatrixPtr cpuOutput = std::make_shared<CpuMatrix>(numSamples, inputDim);
  MatrixPtr gpuOutput = std::make_shared<GpuMatrix>(numSamples, inputDim);
  cpuOutput->randomizeUniform();
  gpuOutput->copyFrom(*cpuOutput);

  cpuOutput->addToRows(*cpuTable, *cpuIds);
  gpuOutput->addToRows(*gpuTable, *gpuIds);

373
  TensorCheckErr(*cpuTable, *gpuTable);
Z
zhangjinchao01 已提交
374 375 376 377 378 379 380
}

TEST(Matrix, tableProjection) {
  for (auto numSamples : {10, 100, 1000, 10000, 80000}) {
    for (auto tableSize : {10, 100}) {
      for (auto inputDim : {20, 50}) {
        VLOG(3) << " numSamples=" << numSamples << " tableSize=" << tableSize
381
                << " inputDim=" << inputDim;
Z
zhangjinchao01 已提交
382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411
        testMatrixAddToRows(numSamples, tableSize, inputDim);
      }
    }
  }
}

void testMatrixMul(bool transa, bool transb, int dimM, int dimN, int dimK) {
  int heightA = transa == false ? dimM : dimK;
  int widthA = transa == false ? dimK : dimM;
  int heightB = transb == false ? dimK : dimN;
  int widthB = transb == false ? dimN : dimK;
  int heightC = dimM;
  int widthC = dimN;

  MatrixPtr cpuA = std::make_shared<CpuMatrix>(heightA, widthA, transa);
  MatrixPtr cpuB = std::make_shared<CpuMatrix>(heightB, widthB, transb);
  MatrixPtr cpuC = std::make_shared<CpuMatrix>(heightC, widthC);
  MatrixPtr gpuA = std::make_shared<GpuMatrix>(heightA, widthA, transa);
  MatrixPtr gpuB = std::make_shared<GpuMatrix>(heightB, widthB, transb);
  MatrixPtr gpuC = std::make_shared<GpuMatrix>(heightC, widthC);

  real alpha = 1.5;
  real beta = 2.0;
  cpuA->randomizeUniform();
  cpuB->randomizeUniform();
  cpuC->randomizeUniform();
  gpuA->copyFrom(*cpuA);
  gpuB->copyFrom(*cpuB);
  gpuC->copyFrom(*cpuC);

412 413
  cpuC->mul(*cpuA, *cpuB, alpha, beta);
  gpuC->mul(*gpuA, *gpuB, alpha, beta);
Z
zhangjinchao01 已提交
414

415
  TensorCheckErr(*cpuC, *gpuC);
Z
zhangjinchao01 已提交
416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452
}

void testSubMatrixMul(bool transa, bool transb, int dimM, int dimN, int dimK) {
  int heightA = transa == false ? dimM : dimK;
  int widthA = transa == false ? dimK : dimM;
  int heightB = transb == false ? dimK : dimN;
  int widthB = transb == false ? dimN : dimK;
  int heightC = dimM;
  int widthC = dimN;

  MatrixPtr cpuA = std::make_shared<CpuMatrix>(heightA, widthA, transa);
  MatrixPtr cpuB = std::make_shared<CpuMatrix>(heightB, widthB, transb);
  MatrixPtr cpuC = std::make_shared<CpuMatrix>(heightC, widthC);
  MatrixPtr gpuA = std::make_shared<GpuMatrix>(heightA, widthA, transa);
  MatrixPtr gpuB = std::make_shared<GpuMatrix>(heightB, widthB, transb);
  MatrixPtr gpuC = std::make_shared<GpuMatrix>(heightC, widthC);

  real alpha = 1.5;
  real beta = 2.0;
  cpuA->randomizeUniform();
  cpuB->randomizeUniform();
  cpuC->randomizeUniform();
  gpuA->copyFrom(*cpuA);
  gpuB->copyFrom(*cpuB);
  gpuC->copyFrom(*cpuC);

  auto subSize = [](int& start, int& end, int dim) {
    if (dim == 1) {
      start = 0;
      end = dim;
    } else {
      int subDim = rand() % (dim - 1) + 1;  // NOLINT
      start = rand() % (dim - subDim);      // NOLINT
      end = start + subDim;
    }
  };

453 454 455 456 457 458
  auto subMatrix = [](MatrixPtr& sub,
                      MatrixPtr matrix,
                      size_t startRow,
                      size_t endRow,
                      size_t startCol,
                      size_t endCol) {
Z
zhangjinchao01 已提交
459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483
    if (!matrix->isTransposed()) {
      sub = matrix->subMatrix(startRow, endRow, startCol, endCol);
    } else {
      sub = matrix->subMatrix(startCol, endCol, startRow, endRow);
    }
  };

  int startM, endM;
  int startN, endN;
  int startK, endK;
  subSize(startM, endM, dimM);
  subSize(startN, endN, dimN);
  subSize(startK, endK, dimK);

  MatrixPtr subCpuA;
  MatrixPtr subCpuB;
  MatrixPtr subGpuA;
  MatrixPtr subGpuB;
  subMatrix(subCpuA, cpuA, startM, endM, startK, endK);
  subMatrix(subGpuA, gpuA, startM, endM, startK, endK);
  subMatrix(subCpuB, cpuB, startK, endK, startN, endN);
  subMatrix(subGpuB, gpuB, startK, endK, startN, endN);
  MatrixPtr subCpuC = cpuC->subMatrix(startM, endM, startN, endN);
  MatrixPtr subGpuC = gpuC->subMatrix(startM, endM, startN, endN);

484 485
  subCpuC->mul(*subCpuA, *subCpuB, alpha, beta);
  subGpuC->mul(*subGpuA, *subGpuB, alpha, beta);
Z
zhangjinchao01 已提交
486

487
  TensorCheckErr(*cpuC, *gpuC);
Z
zhangjinchao01 已提交
488 489 490 491 492 493 494 495 496 497 498 499
}

TEST(Matrix, mul) {
  for (auto transa : {false, true}) {
    for (auto transb : {false, true}) {
      for (auto dimM : {1, 9, 53, 127, 345, 1023, 2135}) {
        for (auto dimN : {1, 5, 37, 256, 1024}) {
          for (auto dimK : {8, 45, 346, 784, 1025}) {
            if (true == transa && true == transb) {
              continue;
            }
            VLOG(3) << setiosflags(ios::left) << setfill(' ')
500 501 502
                    << " transa=" << transa << " transb=" << transb
                    << " dimM=" << setw(5) << dimM << " dimN=" << setw(5)
                    << dimN << " dimK=" << setw(5) << dimK;
Z
zhangjinchao01 已提交
503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525

            testMatrixMul(transa, transb, dimM, dimN, dimK);
            testSubMatrixMul(transa, transb, dimM, dimN, dimK);
          }
        }
      }
    }
  }
}

void testVectorRowFunc(int size) {
  CpuVectorPtr cpu = std::make_shared<CpuVectorT<real>>(size);
  GpuVectorPtr gpu = std::make_shared<GpuVectorT<real>>(size);

  cpu->rand();
  gpu->copyFrom(*cpu);

  EXPECT_EQ(cpu->getMax(), gpu->getMax());
  EXPECT_EQ(cpu->getMin(), gpu->getMin());
  EXPECT_EQ(cpu->getAbsMax(), gpu->getAbsMax());
}

TEST(Vector, rowFunc) {
Y
Yi Wang 已提交
526
  for (auto size : {1, 3, 997}) {  // prime numbers close to 1, 4, 1024
Z
zhangjinchao01 已提交
527 528 529 530 531
    VLOG(3) << " size=" << size;
    testVectorRowFunc(size);
  }
}

532
template <class T>
Z
zhangjinchao01 已提交
533 534 535 536 537 538 539 540
void testVectorReset(int size) {
  std::shared_ptr<CpuVectorT<T>> cpu = std::make_shared<CpuVectorT<T>>(size);
  std::shared_ptr<GpuVectorT<T>> gpu = std::make_shared<GpuVectorT<T>>(size);

  T value = (T)((int)rand() % 100 + 1.0f / ((int)rand() % 100));
  cpu->reset(value);
  gpu->reset(value);

541
  TensorCheckEqual(*cpu, *gpu);
Z
zhangjinchao01 已提交
542 543
}

544
template <class T>
Z
zhangjinchao01 已提交
545 546 547
void testVecortSelectFrom(int size) {
  std::shared_ptr<CpuVectorT<T>> cpuDst = std::make_shared<CpuVectorT<T>>(size);
  std::shared_ptr<GpuVectorT<T>> gpuDst = std::make_shared<GpuVectorT<T>>(size);
548 549 550 551
  std::shared_ptr<CpuVectorT<T>> cpuSrc =
      std::make_shared<CpuVectorT<T>>(size * 2);
  std::shared_ptr<GpuVectorT<T>> gpuSrc =
      std::make_shared<GpuVectorT<T>>(size * 2);
Z
zhangjinchao01 已提交
552 553 554 555 556 557 558 559 560 561 562 563 564 565 566
  CpuIVectorPtr cpuIds = std::make_shared<CpuVectorT<int>>(size);
  GpuIVectorPtr gpuIds = std::make_shared<GpuVectorT<int>>(size);

  if (std::is_same<T, real>::value) {
    cpuSrc->rand();
  } else {
    cpuSrc->rand(100000);
  }
  gpuSrc->copyFrom(*cpuSrc);
  cpuIds->rand(size);
  gpuIds->copyFrom(*cpuIds);

  cpuDst->selectFrom(*cpuSrc, *cpuIds);
  gpuDst->selectFrom(*gpuSrc, *gpuIds);

567
  TensorCheckEqual(*cpuDst, *gpuDst);
Z
zhangjinchao01 已提交
568 569
}

570
template <class T>
Z
zhangjinchao01 已提交
571 572 573 574 575 576 577
void testVecotrZeroMem(int size) {
  std::shared_ptr<CpuVectorT<T>> cpu = std::make_shared<CpuVectorT<T>>(size);
  std::shared_ptr<GpuVectorT<T>> gpu = std::make_shared<GpuVectorT<T>>(size);

  cpu->zeroMem();
  gpu->zeroMem();

578
  TensorCheckEqual(*cpu, *gpu);
Z
zhangjinchao01 已提交
579 580
}

581
template <class T>
Z
zhangjinchao01 已提交
582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598
void testVectorIsEqual(int size) {
  std::shared_ptr<CpuVectorT<T>> cpuA = std::make_shared<CpuVectorT<T>>(size);
  std::shared_ptr<CpuVectorT<T>> cpuB = std::make_shared<CpuVectorT<T>>(size);
  std::shared_ptr<GpuVectorT<T>> gpuA = std::make_shared<GpuVectorT<T>>(size);
  std::shared_ptr<GpuVectorT<T>> gpuB = std::make_shared<GpuVectorT<T>>(size);

  if (std::is_same<T, real>::value) {
    cpuB->rand();
  } else {
    cpuB->rand(100000);
  }
  gpuB->copyFrom(*cpuB);

  T value = (T)((int)rand() % 100 + 1.0f / ((int)rand() % 100));
  cpuA->isEqualTo(*cpuB, value);
  gpuA->isEqualTo(*gpuB, value);

599
  TensorCheckEqual(*cpuA, *gpuA);
Z
zhangjinchao01 已提交
600 601 602
}

TEST(Vector, Equal) {
Y
Yi Wang 已提交
603
  for (auto size : {1, 3, 997}) {  // prime numbers close to 1, 4, 1024
Z
zhangjinchao01 已提交
604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629
    VLOG(3) << " size=" << size;
    testVectorReset<int>(size);
    testVectorReset<real>(size);
    testVecortSelectFrom<int>(size);
    testVecortSelectFrom<real>(size);
    testVecotrZeroMem<int>(size);
    testVecotrZeroMem<real>(size);
    testVectorIsEqual<int>(size);
    testVectorIsEqual<real>(size);
  }
}

void testMatrixTopK(int samples, int dim, int beamSize) {
  MatrixPtr cpuSrc = std::make_shared<CpuMatrix>(samples, dim);
  MatrixPtr gpuSrc = std::make_shared<GpuMatrix>(samples, dim);
  MatrixPtr cpuVal = std::make_shared<CpuMatrix>(samples, beamSize);
  MatrixPtr gpuVal = std::make_shared<GpuMatrix>(samples, beamSize);
  IVectorPtr cpuIds = std::make_shared<CpuIVector>(samples * beamSize);
  IVectorPtr gpuIds = std::make_shared<GpuIVector>(samples * beamSize);

  cpuSrc->randomizeUniform();
  gpuSrc->copyFrom(*cpuSrc);

  cpuSrc->rowMax(*cpuIds, *cpuVal);
  gpuSrc->rowMax(*gpuIds, *gpuVal);

630
  TensorCheckEqual(*cpuVal, *gpuVal);
Z
zhangjinchao01 已提交
631 632 633
}

TEST(Matrix, topK) {
Y
Yi Wang 已提交
634 635
  for (auto samples : {1, 17, 131}) {  // prime numbers close to 1, 16, 127
    for (auto dim : {1, 3, 997}) {     // prime numbers close to 1, 4, 1024
Z
zhangjinchao01 已提交
636 637
      for (auto beamSize : {1, 5, 10, 20, 40, (int)rand() % dim + 1}) {
        if (beamSize > dim) continue;
638
        VLOG(3) << " samples=" << samples << " beamSize=" << beamSize
Z
zhangjinchao01 已提交
639 640 641 642 643 644 645 646 647
                << " dim=" << dim;
        testMatrixTopK(samples, dim, beamSize);
      }
    }
  }
}

void testSMatrixTopK(int samples, int dim, int beamSize, real ratio) {
  int nnz = samples * dim * ratio;
Y
Yi Wang 已提交
648
  if (nnz < 1) nnz = 1;  // Because sparseRand in MathUtil.cpp requires this.
Z
zhangjinchao01 已提交
649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665
  MatrixPtr cpuSrc = std::make_shared<CpuSparseMatrix>(samples, dim, nnz);
  MatrixPtr gpuSrc = std::make_shared<GpuSparseMatrix>(samples, dim, nnz);
  MatrixPtr cpuVal = std::make_shared<CpuMatrix>(samples, beamSize);
  MatrixPtr gpuVal = std::make_shared<GpuMatrix>(samples, beamSize);
  IVectorPtr cpuIds = std::make_shared<CpuIVector>(samples * beamSize);
  IVectorPtr gpuIds = std::make_shared<GpuIVector>(samples * beamSize);

  cpuSrc->randomizeUniform();
  gpuSrc->copyFrom(*cpuSrc);
  cpuVal->zero();
  cpuIds->zero();
  gpuVal->zero();
  gpuIds->zero();

  cpuSrc->rowMax(*cpuIds, *cpuVal);
  gpuSrc->rowMax(*gpuIds, *gpuVal);

666
  TensorCheckEqual(*cpuVal, *gpuVal);
Z
zhangjinchao01 已提交
667 668 669 670 671 672 673 674 675 676 677 678 679 680 681

  IVectorPtr outCheckIds = std::make_shared<CpuIVector>(samples * beamSize);
  outCheckIds->copyFrom(*gpuIds);

  const int* data1 = cpuIds->getData();
  const int* data2 = outCheckIds->getData();
  size_t size = cpuIds->getSize();
  for (size_t i = 0; i < size; i++) {
    if (data1[i] == -1 && data1[i] != data2[i]) {
      EXPECT_EQ(data1[i], data2[i]);
    }
  }
}

TEST(SMatrix, topK) {
Y
Yi Wang 已提交
682 683 684
  for (auto samples : {1, 3, 61}) {
    for (auto dim : {1, 3, 61}) {
      for (auto beamSize : {1, 3, 61}) {
Z
zhangjinchao01 已提交
685 686
        for (auto ratio : {0.01, 0.001}) {
          if (beamSize > dim) continue;
687 688
          VLOG(3) << " samples=" << samples << " beamSize=" << beamSize
                  << " dim=" << dim << " ratio=" << ratio;
Z
zhangjinchao01 已提交
689 690 691 692 693 694 695
          testSMatrixTopK(samples, dim, beamSize, ratio);
        }
      }
    }
  }
}

L
Luo Tao 已提交
696
void testMatrixSequenceAvg(int batchSize, int inputDim, int mode) {
Z
zhangjinchao01 已提交
697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715
  MatrixPtr cpuInput = std::make_shared<CpuMatrix>(batchSize, inputDim);
  MatrixPtr gpuInput = std::make_shared<GpuMatrix>(batchSize, inputDim);
  cpuInput->randomizeUniform();
  gpuInput->copyFrom(*cpuInput);

  IVectorPtr cpuSequence;
  generateSequenceStartPositions(batchSize, cpuSequence);
  IVectorPtr gpuSequence = IVector::create(cpuSequence->getSize(), true);
  gpuSequence->copyFrom(*cpuSequence);

  int newBatchSize = cpuSequence->getSize() - 1;
  MatrixPtr cpuOutput = std::make_shared<CpuMatrix>(newBatchSize, inputDim);
  MatrixPtr gpuOutput = std::make_shared<GpuMatrix>(newBatchSize, inputDim);
  cpuOutput->zero();
  gpuOutput->zero();

  cpuOutput->sequenceAvgForward(*cpuInput, *cpuSequence, mode);
  gpuOutput->sequenceAvgForward(*gpuInput, *gpuSequence, mode);

716
  TensorCheckErr(*cpuOutput, *gpuOutput);
L
Luo Tao 已提交
717 718 719 720 721 722 723 724 725 726

  MatrixPtr cpuInGrad = std::make_shared<CpuMatrix>(batchSize, inputDim);
  MatrixPtr gpuInGrad = std::make_shared<GpuMatrix>(batchSize, inputDim);
  cpuInGrad->randomizeUniform();
  gpuInGrad->copyFrom(*cpuInGrad);

  cpuInGrad->sequenceAvgBackward(*cpuOutput, *cpuSequence, mode);
  gpuInGrad->sequenceAvgBackward(*gpuOutput, *gpuSequence, mode);

  TensorCheckErr(*cpuInGrad, *gpuInGrad);
Z
zhangjinchao01 已提交
727 728
}

L
Luo Tao 已提交
729
TEST(Matrix, sequenceAvg) {
Z
zhangjinchao01 已提交
730 731 732 733 734
  for (auto batchSize : {10, 128, 6000}) {
    for (auto inputDim : {32, 100, 512}) {
      for (auto mode : {0, 1, 2}) {
        VLOG(3) << " batchSize=" << batchSize << " inputDim=" << inputDim
                << " mode=" << mode;
L
Luo Tao 已提交
735
        testMatrixSequenceAvg(batchSize, inputDim, mode);
Z
zhangjinchao01 已提交
736 737 738 739 740
      }
    }
  }
}

741 742 743 744
void testParamReluBackwardDiff(int height,
                               int width,
                               int w_height,
                               int w_width) {
Z
zhangjinchao01 已提交
745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768
  MatrixPtr oGrad = CpuMatrix::create(height, width, false, false);
  MatrixPtr input = CpuMatrix::create(height, width, false, false);
  MatrixPtr diff = CpuMatrix::create(height, width, false, false);
  MatrixPtr w = CpuMatrix::create(w_height, w_width, false, false);

  oGrad->randomizeUniform();
  input->randomizeUniform();
  w->randomizeUniform();
  diff->randomizeUniform();
  input->add(-0.5);

  MatrixPtr oGradGpu = GpuMatrix::create(height, width, false, true);
  MatrixPtr inputGpu = GpuMatrix::create(height, width, false, true);
  MatrixPtr diffGpu = CpuMatrix::create(height, width, false, true);
  MatrixPtr wGpu = GpuMatrix::create(w_height, w_width, false, true);

  oGradGpu->copyFrom(*oGrad);
  inputGpu->copyFrom(*input);
  wGpu->copyFrom(*w);
  diffGpu->copyFrom(*diff);

  diff->paramReluBackwardDiff(*oGrad, *input, *w);
  diffGpu->paramReluBackwardDiff(*oGradGpu, *inputGpu, *wGpu);

769
  TensorCheckErr(*diff, *diffGpu);
Z
zhangjinchao01 已提交
770 771 772
}

TEST(Matrix, paramReluBackwardDiff) {
H
hedaoyuan 已提交
773 774
  for (auto height : {10, 40, 100}) {
    for (auto width : {10, 40, 100}) {
Z
zhangjinchao01 已提交
775 776
      for (auto w_height : {1, 2}) {
        for (auto w_width : {1, 2}) {
H
hedaoyuan 已提交
777
          if (width % (w_height * w_width)) continue;
Z
zhangjinchao01 已提交
778 779 780 781 782 783 784
          testParamReluBackwardDiff(height, width, w_height, w_width);
        }
      }
    }
  }
}

785
void testClassificationError(int numSamples, int dim, int topkSize) {
H
He 已提交
786 787 788 789 790 791 792 793 794 795 796 797
  MatrixPtr cpuError = std::make_shared<CpuMatrix>(numSamples, 1);
  MatrixPtr gpuError = std::make_shared<GpuMatrix>(numSamples, 1);
  MatrixPtr cpuOutput = std::make_shared<CpuMatrix>(numSamples, dim);
  MatrixPtr gpuOutput = std::make_shared<GpuMatrix>(numSamples, dim);
  IVectorPtr cpuLabel = std::make_shared<CpuIVector>(numSamples);
  IVectorPtr gpuLabel = std::make_shared<GpuIVector>(numSamples);

  cpuOutput->randomizeUniform();
  cpuLabel->rand(dim);
  gpuOutput->copyFrom(*cpuOutput);
  gpuLabel->copyFrom(*cpuLabel);

798 799
  cpuError->classificationError(*cpuOutput, *cpuLabel, topkSize);
  gpuError->classificationError(*gpuOutput, *gpuLabel, topkSize);
H
He 已提交
800

801
  TensorCheckEqual(*cpuError, *gpuError);
H
He 已提交
802 803 804
}

TEST(Matrix, classificationError) {
Y
Yi Wang 已提交
805 806 807
  for (auto numSamples : {1, 3, 31}) {
    for (auto dim : {1, 3, 31}) {
      for (auto topkSize : {1, 3, (int)rand() % dim + 1}) {
808 809 810 811 812
        if (topkSize > dim) continue;
        VLOG(3) << " sample= " << numSamples << " topkSize= " << topkSize
                << " dim= " << dim;
        testClassificationError(numSamples, dim, topkSize);
      }
H
He 已提交
813 814 815 816
    }
  }
}

817 818 819 820 821 822 823 824 825 826
void testMaxPoolFwdBwd(int numSamples,
                       int channels,
                       int imgSizeH,
                       int imgSizeW,
                       int ksizeH,
                       int ksizeW,
                       int strideH,
                       int strideW,
                       int padH,
                       int padW) {
827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843
  int outH = 0, outW = 0;
  outH = (imgSizeH - ksizeH + 2 * padH + strideH - 1) / strideH + 1;
  outW = (imgSizeW - ksizeW + 2 * padW + strideW - 1) / strideW + 1;

  int inWidth = imgSizeH * imgSizeW * channels;
  MatrixPtr input = CpuMatrix::create(numSamples, inWidth, false, false);
  MatrixPtr inputGpu = GpuMatrix::create(numSamples, inWidth, false, true);

  int outWidth = channels * outH * outW;
  MatrixPtr target = CpuMatrix::create(numSamples, outWidth, false, false);
  MatrixPtr targetGpu = GpuMatrix::create(numSamples, outWidth, false, true);

  input->randomizeUniform();
  target->randomizeUniform();
  inputGpu->copyFrom(*input);
  targetGpu->copyFrom(*target);

844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867
  target->maxPoolForward(*input,
                         imgSizeH,
                         imgSizeW,
                         channels,
                         ksizeW,
                         ksizeH,
                         strideH,
                         strideW,
                         outH,
                         outW,
                         padH,
                         padW);
  targetGpu->maxPoolForward(*inputGpu,
                            imgSizeH,
                            imgSizeW,
                            channels,
                            ksizeW,
                            ksizeH,
                            strideH,
                            strideW,
                            outH,
                            outW,
                            padH,
                            padW);
868 869 870 871 872 873 874
  MatrixPtr targetCheck = CpuMatrix::create(numSamples, outWidth, false, false);
  targetCheck->copyFrom(*targetGpu);
  checkMatrixEqual(target, targetCheck);

  MatrixPtr inputGrad = CpuMatrix::create(numSamples, inWidth, false, false);
  MatrixPtr inputGpuGrad = GpuMatrix::create(numSamples, inWidth, false, true);
  MatrixPtr targetGrad = CpuMatrix::create(numSamples, outWidth, false, false);
875 876
  MatrixPtr targetGpuGrad =
      GpuMatrix::create(numSamples, outWidth, false, true);
877 878 879 880 881 882

  inputGrad->randomizeUniform();
  targetGrad->randomizeUniform();
  inputGpuGrad->copyFrom(*inputGrad);
  targetGpuGrad->copyFrom(*targetGrad);

883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914
  inputGrad->maxPoolBackward(*input,
                             imgSizeH,
                             imgSizeW,
                             *targetGrad,
                             *target,
                             ksizeW,
                             ksizeH,
                             strideH,
                             strideW,
                             outH,
                             outW,
                             1.0,
                             1.0,
                             padH,
                             padW);
  inputGpuGrad->maxPoolBackward(*inputGpu,
                                imgSizeH,
                                imgSizeW,
                                *targetGpuGrad,
                                *targetGpu,
                                ksizeW,
                                ksizeH,
                                strideH,
                                strideW,
                                outH,
                                outW,
                                1.0,
                                1.0,
                                padH,
                                padW);
  MatrixPtr targetBwdCheck =
      CpuMatrix::create(numSamples, inWidth, false, false);
915 916 917 918
  targetBwdCheck->copyFrom(*inputGpuGrad);
  checkMatrixEqual(inputGrad, targetBwdCheck);
}

919 920 921 922 923 924 925 926 927 928
void testAvgPoolFwdBwd(int numSamples,
                       int channels,
                       int imgSizeH,
                       int imgSizeW,
                       int ksizeH,
                       int ksizeW,
                       int strideH,
                       int strideW,
                       int padH,
                       int padW) {
929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945
  int outH = 0, outW = 0;
  outH = (imgSizeH - ksizeH + 2 * padH + strideH - 1) / strideH + 1;
  outW = (imgSizeW - ksizeW + 2 * padW + strideW - 1) / strideW + 1;

  int inWidth = imgSizeH * imgSizeW * channels;
  MatrixPtr input = CpuMatrix::create(numSamples, inWidth, false, false);
  MatrixPtr inputGpu = GpuMatrix::create(numSamples, inWidth, false, true);

  int outWidth = channels * outH * outW;
  MatrixPtr target = CpuMatrix::create(numSamples, outWidth, false, false);
  MatrixPtr targetGpu = GpuMatrix::create(numSamples, outWidth, false, true);

  input->randomizeUniform();
  target->randomizeUniform();
  inputGpu->copyFrom(*input);
  targetGpu->copyFrom(*target);

946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969
  target->avgPoolForward(*input,
                         imgSizeH,
                         imgSizeW,
                         channels,
                         ksizeW,
                         ksizeH,
                         strideH,
                         strideW,
                         outH,
                         outW,
                         padH,
                         padW);
  targetGpu->avgPoolForward(*inputGpu,
                            imgSizeH,
                            imgSizeW,
                            channels,
                            ksizeW,
                            ksizeH,
                            strideH,
                            strideW,
                            outH,
                            outW,
                            padH,
                            padW);
970 971

  TensorCheckErr(*target, *targetGpu);
972 973 974 975

  MatrixPtr inputGrad = CpuMatrix::create(numSamples, inWidth, false, false);
  MatrixPtr inputGpuGrad = GpuMatrix::create(numSamples, inWidth, false, true);
  MatrixPtr targetGrad = CpuMatrix::create(numSamples, outWidth, false, false);
976 977
  MatrixPtr targetGpuGrad =
      GpuMatrix::create(numSamples, outWidth, false, true);
978 979 980 981 982 983

  inputGrad->randomizeUniform();
  targetGrad->randomizeUniform();
  inputGpuGrad->copyFrom(*inputGrad);
  targetGpuGrad->copyFrom(*targetGrad);

984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009
  inputGrad->avgPoolBackward(*targetGrad,
                             imgSizeH,
                             imgSizeW,
                             ksizeW,
                             ksizeH,
                             strideH,
                             strideW,
                             outH,
                             outW,
                             1.0,
                             1.0,
                             padH,
                             padW);
  inputGpuGrad->avgPoolBackward(*targetGpuGrad,
                                imgSizeH,
                                imgSizeW,
                                ksizeW,
                                ksizeH,
                                strideH,
                                strideW,
                                outH,
                                outW,
                                1.0,
                                1.0,
                                padH,
                                padW);
1010 1011

  TensorCheckErr(*inputGrad, *inputGpuGrad);
1012 1013
}

Y
Yi Wang 已提交
1014 1015
// TODO(yi): I noticed many such blindly combinatorial tests in this
// file.  They are no help to locate defects at all.
1016
TEST(Matrix, PoolFwdBwd) {
Y
Yi Wang 已提交
1017 1018 1019 1020 1021 1022
  for (auto numSamples : {1, 3}) {
    for (auto channels : {1, 3}) {
      for (auto imgSizeH : {13, 17}) {
        for (auto imgSizeW : {17, 19}) {
          for (auto sizeX : {2, 3}) {
            for (auto sizeY : {2, 3}) {
1023 1024
              for (auto sH : {1, 2}) {
                for (auto sW : {1, 2}) {
1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055
                  for (auto pH : {0, (sizeY - 1) / 2}) {
                    for (auto pW : {0, (sizeX - 1) / 2}) {
                      VLOG(3) << " numSamples=" << numSamples
                              << " channels=" << channels
                              << " imgSizeH=" << imgSizeH
                              << " imgSizeW=" << imgSizeW << " sizeX=" << sizeX
                              << " sizeY=" << sizeY << " strideH=" << sH
                              << " strideW=" << sW << " padingH=" << pH
                              << " padingW=" << pW;
                      testMaxPoolFwdBwd(numSamples,
                                        channels,
                                        imgSizeH,
                                        imgSizeW,
                                        sizeX,
                                        sizeY,
                                        sH,
                                        sW,
                                        pH,
                                        pW);
                      testAvgPoolFwdBwd(numSamples,
                                        channels,
                                        imgSizeH,
                                        imgSizeW,
                                        sizeX,
                                        sizeY,
                                        sH,
                                        sW,
                                        pH,
                                        pW);
                    }
                  }
1056 1057 1058 1059 1060 1061 1062 1063 1064 1065
                }
              }
            }
          }
        }
      }
    }
  }
}

1066 1067
void testMaxOutFwdBwd(
    int numSamples, int imgSizeH, int imgSizeW, int channels, int groups) {
1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087
  int inWidth = imgSizeH * imgSizeW * channels;
  int outChannels = channels / groups;
  int outWidth = imgSizeH * imgSizeW * outChannels;

  // forward
  MatrixPtr input = CpuMatrix::create(numSamples, inWidth, false, false);
  MatrixPtr inputGpu = GpuMatrix::create(numSamples, inWidth, false, true);

  MatrixPtr target = CpuMatrix::create(numSamples, outWidth, false, false);
  MatrixPtr targetGpu = GpuMatrix::create(numSamples, outWidth, false, true);

  IVectorPtr id = CpuIVector::create(numSamples * outWidth, false);
  IVectorPtr idGpu = GpuIVector::create(numSamples * outWidth, true);

  input->randomizeUniform();
  inputGpu->copyFrom(*input);

  target->maxoutForward(*input, *id, outChannels, groups);
  targetGpu->maxoutForward(*inputGpu, *idGpu, outChannels, groups);

1088 1089
  TensorCheckErr(*target, *targetGpu);
  TensorCheckEqual(*id, *idGpu);
1090 1091 1092 1093 1094 1095

  // backward
  MatrixPtr inputGrad = CpuMatrix::create(numSamples, inWidth, false, false);
  MatrixPtr inputGpuGrad = GpuMatrix::create(numSamples, inWidth, false, true);

  MatrixPtr targetGrad = CpuMatrix::create(numSamples, outWidth, false, false);
1096 1097
  MatrixPtr targetGpuGrad =
      GpuMatrix::create(numSamples, outWidth, false, true);
1098 1099 1100 1101 1102 1103 1104 1105 1106

  inputGrad->randomizeUniform();
  targetGrad->randomizeUniform();
  inputGpuGrad->copyFrom(*inputGrad);
  targetGpuGrad->copyFrom(*targetGrad);

  inputGrad->maxoutBackward(*targetGrad, *id, outChannels, groups);
  inputGpuGrad->maxoutBackward(*targetGpuGrad, *idGpu, outChannels, groups);

1107
  TensorCheckErr(*inputGrad, *inputGpuGrad);
1108 1109 1110 1111 1112 1113 1114 1115
}

TEST(Matrix, MaxOutFwdBwd) {
  for (auto numSamples : {5, 10}) {
    for (auto channels : {8, 16}) {
      for (auto imgSizeH : {14, 28}) {
        for (auto imgSizeW : {16, 30}) {
          for (auto groups : {2, 4}) {
1116 1117
            VLOG(3) << " numSamples=" << numSamples << " channels=" << channels
                    << " imgSizeH=" << imgSizeH << " imgSizeW=" << imgSizeW
1118 1119 1120 1121 1122 1123 1124 1125 1126
                    << " groups=" << groups;
            testMaxOutFwdBwd(numSamples, imgSizeH, imgSizeW, channels, groups);
          }
        }
      }
    }
  }
}

1127
TEST(CpuMatrix, copyFrom) {
Y
Yi Wang 已提交
1128 1129
  const size_t height = 31;
  const size_t width = 53;
1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140
  CpuMatrix cpu(height, width);
  GpuMatrix gpu(height, width);
  CpuMatrix copy(height, width);

  cpu.randomizeUniform();
  gpu.copyFrom(cpu);
  copy.copyFrom(gpu, HPPL_STREAM_DEFAULT);

  TensorCheckEqual(cpu, copy);
}

D
dangqingqing 已提交
1141 1142 1143 1144 1145 1146 1147 1148
void testBatch2seqPadding(int batchSize, int inputDim) {
  MatrixPtr cpuInput = std::make_shared<CpuMatrix>(batchSize, inputDim);
  MatrixPtr gpuInput = std::make_shared<GpuMatrix>(batchSize, inputDim);
  cpuInput->randomizeUniform();
  gpuInput->copyFrom(*cpuInput);

  IVectorPtr cpuSequence;
  generateSequenceStartPositions(batchSize, cpuSequence);
1149
  for (int i = 0; i < int(cpuSequence->getSize()); ++i) {
Y
Yi Wang 已提交
1150 1151 1152
    (cpuSequence->getData())[i] += 1;  // so no way that maxSeqLen is 0;
  }

D
dangqingqing 已提交
1153 1154 1155 1156
  IVectorPtr gpuSequence = IVector::create(cpuSequence->getSize(), true);
  gpuSequence->copyFrom(*cpuSequence);

  size_t numSeq = cpuSequence->getSize() - 1;
D
dangqingqing 已提交
1157 1158
  size_t maxSeqLen = *std::max_element(cpuSequence->getData(),
                                       cpuSequence->getData() + numSeq);
D
dangqingqing 已提交
1159

Y
Yi Wang 已提交
1160
  printf("numSeq = %ld, maxSeqLen = %ld\n", numSeq, maxSeqLen);
D
dangqingqing 已提交
1161 1162 1163 1164
  MatrixPtr cBatch = std::make_shared<CpuMatrix>(numSeq * maxSeqLen, inputDim);
  MatrixPtr gBatch = std::make_shared<GpuMatrix>(numSeq * maxSeqLen, inputDim);
  MatrixPtr cCheck = std::make_shared<CpuMatrix>(numSeq * maxSeqLen, inputDim);

Y
Yi Wang 已提交
1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194
  // hl_sequence2batch_copy_padding(gBatch->getData(),
  //                                gpuInput->getData(),
  //                                cpuSequence->getData(),
  //                                inputDim,
  //                                maxSeqLen,
  //                                numSeq,
  //                                false,
  //                                true);
  // cCheck->copyFrom(*gBatch);

  // int* seqStart = cpuSequence->getData();
  // float* batchData = cBatch->getData();
  // float* seqData = cpuInput->getData();
  // for (size_t i = 0; i < maxSeqLen; i++) {
  //   for (size_t j = 0; j < numSeq; j++) {
  //     size_t sequenceStart = seqStart[j];
  //     size_t sequenceLength = seqStart[j + 1] - seqStart[j];
  //     if (i < sequenceLength) {
  //       memcpy(batchData + (i * numSeq + j) * inputDim,
  //              seqData + (sequenceStart + i) * inputDim,
  //              inputDim * sizeof(real));
  //     } else {
  //       memset(batchData + (i * numSeq + j) * inputDim,
  //              0,
  //              inputDim * sizeof(real));
  //     }
  //   }
  // }

  // TensorCheckErr(*cBatch, *cCheck);
D
dangqingqing 已提交
1195 1196 1197
}

TEST(Matrix, warpCTC) {
Y
Yi Wang 已提交
1198 1199
  for (auto batchSize : {1, 3, 17}) {
    for (auto inputDim : {1, 3, 31}) {
D
dangqingqing 已提交
1200 1201
      VLOG(3) << " batchSize=" << batchSize << " inputDim=" << inputDim;
      testBatch2seqPadding(batchSize, inputDim);
D
dangqingqing 已提交
1202 1203 1204 1205
    }
  }
}

1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321
int outputSizeCol2Vol(
    int imageSize, int filterSize, int padding, int stride, bool caffeMode) {
  int outputSize;
  if (!caffeMode) {
    outputSize =
        (imageSize - filterSize + 2 * padding + stride - 1) / stride + 1;
  } else {
    outputSize = (imageSize - filterSize + 2 * padding) / stride + 1;
  }
  CHECK_GE(outputSize, 1);
  return outputSize;
}

void testMatrixCol2Vol(int depth, int height, int width) {
  int channel = 3;
  int filterX = 3, filterY = 4, filterZ = 5;
  int strideX = 2, strideY = 2, strideZ = 2;
  int padX = 1, padY = 1, padZ = 1;

  MatrixPtr cpuImage =
      std::make_shared<CpuMatrix>(channel, depth * height * width);
  MatrixPtr gpuImage =
      std::make_shared<GpuMatrix>(channel, depth * height * width);
  cpuImage->randomizeUniform();
  gpuImage->copyFrom(*cpuImage);

  int outD = outputSizeCol2Vol(depth, filterZ, padZ, strideZ, true);
  int outH = outputSizeCol2Vol(height, filterY, padZ, strideY, true);
  int outW = outputSizeCol2Vol(width, filterX, padZ, strideX, true);

  int colBufHeight = channel * filterZ * filterY * filterX;
  int colBufWidth = outD * outH * outW;
  MatrixPtr cpuColBuf = std::make_shared<CpuMatrix>(colBufHeight, colBufWidth);
  MatrixPtr gpuColBuf = std::make_shared<GpuMatrix>(colBufHeight, colBufWidth);
  cpuColBuf->vol2Col(cpuImage->getData(),
                     channel,
                     depth,
                     height,
                     width,
                     filterZ,
                     filterY,
                     filterX,
                     strideZ,
                     strideY,
                     strideX,
                     padZ,
                     padY,
                     padX);
  gpuColBuf->vol2Col(gpuImage->getData(),
                     channel,
                     depth,
                     height,
                     width,
                     filterZ,
                     filterY,
                     filterX,
                     strideZ,
                     strideY,
                     strideX,
                     padZ,
                     padY,
                     padX);
  TensorCheckEqual(*cpuColBuf, *gpuColBuf);

  cpuColBuf->randomizeUniform();
  gpuColBuf->copyFrom(*cpuColBuf);
  cpuColBuf->col2Vol(cpuImage->getData(),
                     channel,
                     depth,
                     height,
                     width,
                     filterZ,
                     filterY,
                     filterX,
                     strideZ,
                     strideY,
                     strideX,
                     padZ,
                     padY,
                     padX,
                     1.0,
                     1.0);
  gpuColBuf->col2Vol(gpuImage->getData(),
                     channel,
                     depth,
                     height,
                     width,
                     filterZ,
                     filterY,
                     filterX,
                     strideZ,
                     strideY,
                     strideX,
                     padZ,
                     padY,
                     padX,
                     1.0,
                     1.0);
  TensorCheckErr(*cpuImage, *gpuImage);
}

TEST(Matrix, col2Vol) {
  for (auto depth : {9, 16, 64, 128}) {
    for (auto height : {9, 11, 73, 128, 256}) {
      for (auto width : {
               9, 32, 100, 512,
           }) {
        VLOG(3) << "depth=" << depth << " height=" << height
                << " width=" << width;
        testMatrixCol2Vol(depth, height, width);
      }
    }
  }
}
///////

Z
zhangjinchao01 已提交
1322
#endif