test_SelectiveFCLayer.cpp 14.8 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

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

Y
Yu Yang 已提交
15 16
#include <gtest/gtest.h>
#include <math.h>
Z
zhangjinchao01 已提交
17
#include <paddle/utils/PythonUtil.h>
Y
Yu Yang 已提交
18
#include <algorithm>
Z
zhangjinchao01 已提交
19 20
#include <cstdlib>
#include <ctime>
Y
Yu Yang 已提交
21
#include "ModelConfig.pb.h"
Z
zhangjinchao01 已提交
22 23
#include "paddle/gserver/layers/DataLayer.h"
#include "paddle/gserver/layers/FullyConnectedLayer.h"
Y
Yu Yang 已提交
24
#include "paddle/gserver/layers/Layer.h"
Z
zhangjinchao01 已提交
25 26 27 28 29 30 31
#include "paddle/gserver/layers/SelectiveFullyConnectedLayer.h"
#include "paddle/math/CpuSparseMatrix.h"
#include "paddle/trainer/Trainer.h"

using namespace paddle;  // NOLINT
using namespace std;     // NOLINT

32 33 34 35 36
DECLARE_bool(use_gpu);
DECLARE_int32(num_passes);
DECLARE_string(config);
DECLARE_string(init_model_path);
DECLARE_string(config_args);
Z
zhangjinchao01 已提交
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54

size_t fcLayerWidth = 1024;

struct ComData {
  vector<Argument> outArgs;
  vector<ParameterPtr> parameters;
};

int randint(int* data, size_t int_max, size_t size) {
  srand((size_t)(time(NULL)));
  if (int_max < size) {
    return -1;
  }
  size_t count = 0;
  std::map<int, int> tmp;
  int this_int = 0;

  while (count < size) {
55
    this_int = std::rand() % int_max;  // NOLINT
Z
zhangjinchao01 已提交
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
    if (tmp.find(this_int) == tmp.end()) {
      tmp[this_int] = 0;
      count += 1;
    }
  }

  if (tmp.size() != size) {
    return -1;
  }
  count = 0;
  for (auto itr = tmp.begin(); itr != tmp.end(); ++itr) {
    data[count] = itr->first;
    count += 1;
  }
  return 0;
}

73 74 75 76
void calcOutput(ComData& comData,
                const string configFile,
                const string configArgs,
                bool useGpu) {
Z
zhangjinchao01 已提交
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
  FLAGS_config = configFile;
  FLAGS_config_args = configArgs;
  FLAGS_use_gpu = useGpu;
  FLAGS_init_model_path = "gserver/tests/SelectiveFcTest/model";
  *ThreadLocalRand::getSeed() = 0;
  srand(0);

  Trainer trainer;
  trainer.init(TrainerConfigHelper::createFromFlags(), false);

  comData.parameters = trainer.getGradientMachine()->getParameters();

  auto dataProvider = trainer.getDataProvider();
  int32_t batchSize = trainer.getConfig().opt_config().batch_size();
  DataBatch dataBatch;
  dataProvider->setSkipShuffle();
  dataProvider->reset();
  dataProvider->getNextBatch(batchSize, &dataBatch);
  CHECK(dataBatch.getSize()) << "No data from data provider";

  vector<Argument>& inArgs = dataBatch.getStreams();
  trainer.getGradientMachine()->start(trainer.getConfig(), nullptr);
99 100
  trainer.getGradientMachine()->forwardBackward(
      inArgs, &comData.outArgs, PASS_TRAIN);
Z
zhangjinchao01 已提交
101 102 103 104 105 106 107 108 109 110 111
  trainer.getGradientMachine()->finish();
}

void checkMatrix(real* A, real* B, size_t matSize) {
#ifndef PADDLE_TYPE_DOUBLE
  real err = 1e-3;
#else
  real err = 1e-10;
#endif
  int diffNum = 0;
  for (size_t i = 0; i < matSize; ++i) {
112 113
    if (std::isinf(A[i]) || std::isnan(A[i]) || std::isinf(B[i]) ||
        std::isnan(B[i])) {
Z
zhangjinchao01 已提交
114 115 116 117 118 119 120
    } else if (fabs(A[i] - B[i]) > err) {
      diffNum++;
    }
  }
  EXPECT_EQ(0, diffNum);
}

121 122 123 124
void checkTranspose(real* matrix,
                    real* transpose,
                    size_t width,
                    size_t matSize) {
Z
zhangjinchao01 已提交
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154
#ifndef PADDLE_TYPE_DOUBLE
  real err = 1e-3;
#else
  real err = 1e-10;
#endif
  size_t height = matSize / width;
  int diffNum = 0;
  size_t rowId = 0;
  size_t colId = 0;
  for (size_t i = 0; i < matSize; ++i) {
    if (i % width == 0 && i) {
      rowId++;
    }
    colId = i % width;
    if (fabs(matrix[i] - transpose[colId * height + rowId]) > err) {
      diffNum++;
      LOG(INFO) << i << " diff : " << matrix[i] << "\t"
                << transpose[colId * height + rowId];
    }
  }
  EXPECT_EQ(0, diffNum);
}

void compareOutput(ComData& fcData, ComData& selFcData) {
  vector<Argument> outArgsFc = fcData.outArgs;
  vector<Argument> outArgsSelfc = selFcData.outArgs;

  // check cost
  LOG(INFO) << "Check cost";
  CpuMatrix fcCost(outArgsFc[0].value->getHeight(),
155
                   outArgsFc[0].value->getWidth());
Z
zhangjinchao01 已提交
156
  CpuMatrix selfcCost(outArgsSelfc[0].value->getHeight(),
157
                      outArgsSelfc[0].value->getWidth());
Z
zhangjinchao01 已提交
158 159 160 161 162
  fcCost.copyFrom(*outArgsFc[0].value);
  selfcCost.copyFrom(*outArgsSelfc[0].value);
  checkMatrix(fcCost.getData(), selfcCost.getData(), fcCost.getElementCnt());

  // check selective fc output and fc output
163 164
  LOG(INFO) << "Compare output of SelectiveFullyConectedLayer "
            << "with FullyConectedLayer";
Z
zhangjinchao01 已提交
165
  CpuMatrix fcOut(outArgsFc[1].value->getHeight(),
166
                  outArgsFc[1].value->getWidth());
Z
zhangjinchao01 已提交
167
  CpuMatrix selfcOut(outArgsSelfc[1].value->getHeight(),
168
                     outArgsSelfc[1].value->getWidth());
Z
zhangjinchao01 已提交
169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194

  fcOut.copyFrom(*outArgsFc[1].value);
  selfcOut.copyFrom(*outArgsSelfc[1].value);
  checkMatrix(fcOut.getData(), selfcOut.getData(), fcOut.getElementCnt());

  // check gradient math
  vector<ParameterPtr>& fcParam = fcData.parameters;
  vector<ParameterPtr>& selfcParam = selFcData.parameters;
  for (size_t i = 0; i < fcParam.size(); ++i) {
    ParameterPtr p1, p2;
    p1 = fcParam[i];
    p2 = selfcParam[i];

    string paramName = p1->getName();
    LOG(INFO) << "check parameter : " << paramName;

    // check parameter value
    CpuVector paraValue1(p1->getSize());
    CpuVector paraValue2(p2->getSize());
    paraValue1.copyFrom(*p1->getBuf(PARAMETER_VALUE));
    paraValue2.copyFrom(*p2->getBuf(PARAMETER_VALUE));

    // check gradient
    CpuVector paraGrad1(*p1->getBuf(PARAMETER_GRADIENT));
    CpuVector paraGrad2(*p2->getBuf(PARAMETER_GRADIENT));
    if (paramName == "rand_fc_param.bias") {
195 196 197 198
      checkMatrix(
          paraValue1.getData(), paraValue2.getData(), paraValue1.getSize());
      checkMatrix(
          paraGrad1.getData(), paraGrad2.getData(), paraGrad1.getSize());
Z
zhangjinchao01 已提交
199
    } else {
200 201 202 203 204 205 206 207
      checkTranspose(paraValue1.getData(),
                     paraValue2.getData(),
                     fcLayerWidth,
                     paraValue1.getSize());
      checkTranspose(paraGrad1.getData(),
                     paraGrad2.getData(),
                     fcLayerWidth,
                     paraGrad1.getSize());
Z
zhangjinchao01 已提交
208 209 210 211
    }
  }
}

212 213 214 215 216
void compareSparseMulOutput(
    real* fcOutput,
    real* selOutput,
    size_t nnz,
    const std::shared_ptr<std::vector<std::pair<int*, size_t>>>& selCols) {
Z
zhangjinchao01 已提交
217 218 219 220 221
#ifndef PADDLE_TYPE_DOUBLE
  real err = 1e-3;
#else
  real err = 1e-10;
#endif
222 223 224 225 226 227 228
  size_t nnzCount =
      std::accumulate(selCols->begin(),
                      selCols->end(),
                      0UL,
                      [](size_t a, const std::pair<int*, size_t>& arr) {
                        return a + arr.second;
                      });
Z
zhangjinchao01 已提交
229 230 231 232 233 234 235 236 237 238
  EXPECT_EQ(nnz, nnzCount);

  size_t sampleNum = selCols->size();
  int diffNum = 0;
  size_t count = 0;
  for (size_t i = 0; i < sampleNum; ++i) {
    for (size_t j = 0; j < (*selCols)[i].second; ++j) {
      size_t selIdx = (*selCols)[i].first[j];
      if (fabs(fcOutput[i * fcLayerWidth + selIdx] - selOutput[count]) > err) {
        diffNum++;
239 240 241
        LOG(INFO) << count << " diff : " << fcOutput[i * fcLayerWidth + selIdx]
                  << "\t" << selOutput[count];
      }
Z
zhangjinchao01 已提交
242 243 244 245 246 247
      count++;
    }
  }
  EXPECT_EQ(0, diffNum);
}

248 249 250 251 252
LayerPtr creatDataLayer(string name,
                        size_t batchSize,
                        size_t layerSize,
                        std::vector<real>& values,
                        bool useGpu) {
Z
zhangjinchao01 已提交
253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268
  LayerConfig dataConfig;
  dataConfig.set_name(name);
  dataConfig.set_type("data");
  dataConfig.set_size(layerSize);
  LayerPtr layer = LayerPtr(new DataLayer(dataConfig));

  Argument data;
  data.value = Matrix::create(batchSize, layerSize, false, useGpu);
  data.value->copyFrom(values.data(), batchSize * layerSize);

  DataLayerPtr dataLayer = std::dynamic_pointer_cast<DataLayer>(layer);
  dataLayer->setData(data);
  dataLayer->forward(PASS_TEST);
  return layer;
}

269 270
ParameterPtr creatParameter(
    string name, int pid, size_t paraSize, string paramFile, bool useGpu) {
Z
zhangjinchao01 已提交
271 272 273 274 275 276 277 278 279 280 281 282 283
  ParameterConfig paraConfig;
  paraConfig.set_name(name);
  paraConfig.set_size(paraSize);

  ParameterPtr parameter =
      std::make_shared<Parameter>(paraConfig, useGpu, /*initialize */ false);
  parameter->enableType(PARAMETER_VALUE);
  parameter->randomize();
  parameter->setID(pid);
  parameter->load(paramFile);
  return parameter;
}

284 285 286 287 288 289 290
LayerPtr initFcLayer(LayerPtr dataLayer,
                     LayerConfig layerConfig,
                     int dataLayerSize,
                     int fcLayerSize,
                     string paraName,
                     string paraFile,
                     bool useGpu) {
Z
zhangjinchao01 已提交
291 292 293 294
  LayerMap layerMap;
  ParameterMap parameterMap;

  layerMap[dataLayer->getName()] = dataLayer;
295 296
  ParameterPtr para = creatParameter(
      paraName, 0, dataLayerSize * fcLayerSize, paraFile, useGpu);
Z
zhangjinchao01 已提交
297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314
  parameterMap[para->getName()] = para;

  layerConfig.add_inputs();
  LayerInputConfig& input = *(layerConfig.mutable_inputs(0));
  input.set_input_layer_name(dataLayer->getName());
  input.set_input_parameter_name(paraName);

  LayerPtr testLayer = Layer::create(layerConfig);
  layerMap[testLayer->getName()] = testLayer;

  testLayer->setNeedGradient(false);
  testLayer->init(layerMap, parameterMap);
  return testLayer;
}

#ifndef PADDLE_TYPE_DOUBLE
// The parameter file used in fc.conf and selective_fc.conf is float
TEST(Layer, SelectiveFcLayer_train_dense_mul) {
315
  const string& fcConfig = "gserver/tests/SelectiveFcTest/conf/fc.conf";
Z
zhangjinchao01 已提交
316
  const string& fcConfigArgs =
317
      "filelist=gserver/tests/SelectiveFcTest/dense_mul_list";
Z
zhangjinchao01 已提交
318 319 320
  const string& selFcConfig =
      "gserver/tests/SelectiveFcTest/conf/selective_fc.conf";
  const string& selConfigArgs =
321
      "filelist=gserver/tests/SelectiveFcTest/dense_mul_list";
Z
zhangjinchao01 已提交
322 323

  for (auto useGpu : {false, true}) {
324
#ifndef PADDLE_WITH_GPU
Z
zhangjinchao01 已提交
325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340
    if (useGpu) {
      break;
    }
#endif
    LOG(INFO) << "FullyConnectedLayer forwardBackward()";
    ComData fcData;
    calcOutput(fcData, fcConfig, fcConfigArgs, useGpu);

    LOG(INFO) << "SelectiveFullyConnectedLayer forwardBackward()";
    ComData selFcData;
    calcOutput(selFcData, selFcConfig, selConfigArgs, useGpu);
    compareOutput(fcData, selFcData);
  }
}
#endif  // PADDLE_TYPE_DOUBLE

341
void testSelectiveFcLayerTrainSparseMul(const LayerConfig& config,
Z
zhangjinchao01 已提交
342 343 344 345 346 347 348 349
                                        bool useGpu) {
  FLAGS_use_gpu = useGpu;
  size_t batchSize = 100;
  size_t dataLayerSize = 512;
  std::vector<real> values(batchSize * dataLayerSize);
  for (size_t j = 0; j < batchSize * dataLayerSize; ++j) {
    values[j] = std::rand() / real(RAND_MAX);
  }
350 351
  LayerPtr dataLayer =
      creatDataLayer("data", batchSize, dataLayerSize, values, useGpu);
Z
zhangjinchao01 已提交
352 353

  const string& selfcParaFile =
354
      "gserver/tests/SelectiveFcTest/model/rand_fc_param.w.transpose";
Z
zhangjinchao01 已提交
355 356 357
  const string& selfcParaName = "rand_fc_param.w.transpose";

  std::shared_ptr<SelectiveFullyConnectedLayer> selfcLayer =
358 359 360 361 362 363 364 365
      std::dynamic_pointer_cast<SelectiveFullyConnectedLayer>(
          initFcLayer(dataLayer,
                      config,
                      dataLayerSize,
                      fcLayerWidth,
                      selfcParaName,
                      selfcParaFile,
                      useGpu));
Z
zhangjinchao01 已提交
366 367

  // create selected columns
368 369
  std::shared_ptr<std::vector<std::pair<int*, size_t>>> selCols(
      new std::vector<std::pair<int*, size_t>>(batchSize));
Z
zhangjinchao01 已提交
370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386
  size_t maxNNZ = 30;
  srand((size_t)(time(NULL)));
  int total = 0;
  while (total == 0) {
    for (size_t i = 0; i < batchSize; ++i) {
      size_t num = std::rand() % maxNNZ;
      int* data = new int[num];
      randint(data, fcLayerWidth, num);
      (*selCols)[i] = std::make_pair(data, num);
      total += num;
    }
  }
  selfcLayer->fillSelectiveData(selCols);
  selfcLayer->forward(PASS_TEST);

  MatrixPtr outMatSelfc = selfcLayer->getOutputValue();
  CpuSparseMatrixPtr cpuOutMatSelfc(
387 388 389
      new CpuSparseMatrix(outMatSelfc->getHeight(),
                          outMatSelfc->getWidth(),
                          outMatSelfc->getElementCnt()));
Z
zhangjinchao01 已提交
390
  cpuOutMatSelfc->copyFrom(*outMatSelfc, HPPL_STREAM_DEFAULT);
391
#ifdef PADDLE_WITH_GPU
Z
zhangjinchao01 已提交
392 393 394 395 396 397 398 399
  if (useGpu) {
    hl_stream_synchronize(HPPL_STREAM_DEFAULT);
  }
#endif
  real* outValueSelfc = cpuOutMatSelfc->getValue();
  size_t nnz = cpuOutMatSelfc->getElementCnt();

  const string& fcParaFile =
400
      "gserver/tests/SelectiveFcTest/model/rand_fc_param.w";
Z
zhangjinchao01 已提交
401 402 403 404 405 406 407
  const string& fcParaName = "rand_fc_param.w";
  LayerConfig fcLayerConfig;
  fcLayerConfig.set_name("fc_layer");
  fcLayerConfig.set_type("fc");
  fcLayerConfig.set_active_type("linear");
  fcLayerConfig.set_size(fcLayerWidth);

408 409 410 411 412 413 414
  LayerPtr fcLayer = initFcLayer(dataLayer,
                                 fcLayerConfig,
                                 dataLayerSize,
                                 fcLayerWidth,
                                 fcParaName,
                                 fcParaFile,
                                 useGpu);
Z
zhangjinchao01 已提交
415 416 417 418
  fcLayer->forward(PASS_TEST);

  MatrixPtr outMatFc = fcLayer->getOutputValue();
  MatrixPtr cpuOutMatFc(
419
      new CpuMatrix(outMatFc->getHeight(), outMatFc->getWidth()));
Z
zhangjinchao01 已提交
420
  cpuOutMatFc->copyFrom(*outMatFc, HPPL_STREAM_DEFAULT);
421
#ifdef PADDLE_WITH_GPU
Z
zhangjinchao01 已提交
422 423 424 425 426 427 428 429
  if (useGpu) {
    hl_stream_synchronize(HPPL_STREAM_DEFAULT);
  }
#endif
  real* outValueFc = cpuOutMatFc->getData();

  compareSparseMulOutput(outValueFc, outValueSelfc, nnz, selCols);
  for (size_t i = 0; i < batchSize; ++i) {
430
    delete[](*selCols)[i].first;
Z
zhangjinchao01 已提交
431 432 433 434 435 436 437 438 439 440 441 442 443 444 445
  }
}

#ifndef PADDLE_TYPE_DOUBLE
// The parameter file used in testSelectiveFcLayerTrainSparseMul is float
TEST(Layer, SelectiveFcLayer_train_sparse_mul) {
  LayerConfig selLayerConfig;
  selLayerConfig.set_name("sel_fc");
  selLayerConfig.set_type("selective_fc");
  selLayerConfig.set_active_type("linear");
  selLayerConfig.set_has_selected_colums(false);
  selLayerConfig.set_selective_fc_pass_generation(true);
  selLayerConfig.set_size(fcLayerWidth);

  testSelectiveFcLayerTrainSparseMul(selLayerConfig, false);
446
#ifdef PADDLE_WITH_GPU
Z
zhangjinchao01 已提交
447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472
  testSelectiveFcLayerTrainSparseMul(selLayerConfig, true);
#endif
}
#endif  // PADDLE_TYPE_DOUBLE

// TODO(dangqingqing) test multi threads after support in matrix
// TEST(Layer, SelectiveFcLayer_train_sparse_mul_parallel) {
//   LayerConfig selLayerConfig;
//   selLayerConfig.set_name("sel_fc");
//   selLayerConfig.set_type("selective_fc");
//   selLayerConfig.set_active_type("linear");
//   selLayerConfig.set_has_selected_colums(false);
//   selLayerConfig.set_selective_fc_pass_generation(true);
//   selLayerConfig.set_selective_fc_parallel_plain_mul_thread_num(10);
//   selLayerConfig.set_selective_fc_full_mul_ratio(1000);
//   selLayerConfig.set_size(fcLayerWidth);
//   SelectiveFcLayer_test(selLayerConfig, false);
// }

int main(int argc, char** argv) {
  paddle::initMain(argc, argv);
  testing::InitGoogleTest(&argc, argv);
  initPython(argc, argv);
  int ret = RUN_ALL_TESTS();
  return ret;
}