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
#include "paddle/gserver/layers/SelectiveFullyConnectedLayer.h"
#include "paddle/math/CpuSparseMatrix.h"

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

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

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) {
54
    this_int = std::rand() % int_max;  // NOLINT
Z
zhangjinchao01 已提交
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
    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;
}

72 73 74 75
void calcOutput(ComData& comData,
                const string configFile,
                const string configArgs,
                bool useGpu) {
Z
zhangjinchao01 已提交
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
  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);
98 99
  trainer.getGradientMachine()->forwardBackward(
      inArgs, &comData.outArgs, PASS_TRAIN);
Z
zhangjinchao01 已提交
100 101 102 103 104 105 106 107 108 109 110
  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) {
111 112
    if (std::isinf(A[i]) || std::isnan(A[i]) || std::isinf(B[i]) ||
        std::isnan(B[i])) {
Z
zhangjinchao01 已提交
113 114 115 116 117 118 119
    } else if (fabs(A[i] - B[i]) > err) {
      diffNum++;
    }
  }
  EXPECT_EQ(0, diffNum);
}

120 121 122 123
void checkTranspose(real* matrix,
                    real* transpose,
                    size_t width,
                    size_t matSize) {
Z
zhangjinchao01 已提交
124 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
#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(),
154
                   outArgsFc[0].value->getWidth());
Z
zhangjinchao01 已提交
155
  CpuMatrix selfcCost(outArgsSelfc[0].value->getHeight(),
156
                      outArgsSelfc[0].value->getWidth());
Z
zhangjinchao01 已提交
157 158 159 160 161
  fcCost.copyFrom(*outArgsFc[0].value);
  selfcCost.copyFrom(*outArgsSelfc[0].value);
  checkMatrix(fcCost.getData(), selfcCost.getData(), fcCost.getElementCnt());

  // check selective fc output and fc output
162 163
  LOG(INFO) << "Compare output of SelectiveFullyConectedLayer "
            << "with FullyConectedLayer";
Z
zhangjinchao01 已提交
164
  CpuMatrix fcOut(outArgsFc[1].value->getHeight(),
165
                  outArgsFc[1].value->getWidth());
Z
zhangjinchao01 已提交
166
  CpuMatrix selfcOut(outArgsSelfc[1].value->getHeight(),
167
                     outArgsSelfc[1].value->getWidth());
Z
zhangjinchao01 已提交
168 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

  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") {
194 195 196 197
      checkMatrix(
          paraValue1.getData(), paraValue2.getData(), paraValue1.getSize());
      checkMatrix(
          paraGrad1.getData(), paraGrad2.getData(), paraGrad1.getSize());
Z
zhangjinchao01 已提交
198
    } else {
199 200 201 202 203 204 205 206
      checkTranspose(paraValue1.getData(),
                     paraValue2.getData(),
                     fcLayerWidth,
                     paraValue1.getSize());
      checkTranspose(paraGrad1.getData(),
                     paraGrad2.getData(),
                     fcLayerWidth,
                     paraGrad1.getSize());
Z
zhangjinchao01 已提交
207 208 209 210
    }
  }
}

211 212 213 214 215
void compareSparseMulOutput(
    real* fcOutput,
    real* selOutput,
    size_t nnz,
    const std::shared_ptr<std::vector<std::pair<int*, size_t>>>& selCols) {
Z
zhangjinchao01 已提交
216 217 218 219 220
#ifndef PADDLE_TYPE_DOUBLE
  real err = 1e-3;
#else
  real err = 1e-10;
#endif
221 222 223 224 225 226 227
  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 已提交
228 229 230 231 232 233 234 235 236 237
  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++;
238 239 240
        LOG(INFO) << count << " diff : " << fcOutput[i * fcLayerWidth + selIdx]
                  << "\t" << selOutput[count];
      }
Z
zhangjinchao01 已提交
241 242 243 244 245 246
      count++;
    }
  }
  EXPECT_EQ(0, diffNum);
}

247 248 249 250 251
LayerPtr creatDataLayer(string name,
                        size_t batchSize,
                        size_t layerSize,
                        std::vector<real>& values,
                        bool useGpu) {
Z
zhangjinchao01 已提交
252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267
  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;
}

268 269
ParameterPtr creatParameter(
    string name, int pid, size_t paraSize, string paramFile, bool useGpu) {
Z
zhangjinchao01 已提交
270 271 272 273 274 275 276 277 278 279 280 281 282
  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;
}

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

  layerMap[dataLayer->getName()] = dataLayer;
294 295
  ParameterPtr para = creatParameter(
      paraName, 0, dataLayerSize * fcLayerSize, paraFile, useGpu);
Z
zhangjinchao01 已提交
296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313
  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) {
314
  const string& fcConfig = "gserver/tests/SelectiveFcTest/conf/fc.conf";
Z
zhangjinchao01 已提交
315
  const string& fcConfigArgs =
316
      "filelist=gserver/tests/SelectiveFcTest/dense_mul_list";
Z
zhangjinchao01 已提交
317 318 319
  const string& selFcConfig =
      "gserver/tests/SelectiveFcTest/conf/selective_fc.conf";
  const string& selConfigArgs =
320
      "filelist=gserver/tests/SelectiveFcTest/dense_mul_list";
Z
zhangjinchao01 已提交
321 322

  for (auto useGpu : {false, true}) {
323
#ifndef PADDLE_WITH_CUDA
Z
zhangjinchao01 已提交
324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339
    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

340
void testSelectiveFcLayerTrainSparseMul(const LayerConfig& config,
Z
zhangjinchao01 已提交
341 342 343 344 345 346 347 348
                                        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);
  }
349 350
  LayerPtr dataLayer =
      creatDataLayer("data", batchSize, dataLayerSize, values, useGpu);
Z
zhangjinchao01 已提交
351 352

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

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

  // create selected columns
367 368
  std::shared_ptr<std::vector<std::pair<int*, size_t>>> selCols(
      new std::vector<std::pair<int*, size_t>>(batchSize));
Z
zhangjinchao01 已提交
369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385
  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(
386 387 388
      new CpuSparseMatrix(outMatSelfc->getHeight(),
                          outMatSelfc->getWidth(),
                          outMatSelfc->getElementCnt()));
Z
zhangjinchao01 已提交
389
  cpuOutMatSelfc->copyFrom(*outMatSelfc, HPPL_STREAM_DEFAULT);
390
#ifdef PADDLE_WITH_CUDA
Z
zhangjinchao01 已提交
391 392 393 394 395 396 397 398
  if (useGpu) {
    hl_stream_synchronize(HPPL_STREAM_DEFAULT);
  }
#endif
  real* outValueSelfc = cpuOutMatSelfc->getValue();
  size_t nnz = cpuOutMatSelfc->getElementCnt();

  const string& fcParaFile =
399
      "gserver/tests/SelectiveFcTest/model/rand_fc_param.w";
Z
zhangjinchao01 已提交
400 401 402 403 404 405 406
  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);

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

  MatrixPtr outMatFc = fcLayer->getOutputValue();
  MatrixPtr cpuOutMatFc(
418
      new CpuMatrix(outMatFc->getHeight(), outMatFc->getWidth()));
Z
zhangjinchao01 已提交
419
  cpuOutMatFc->copyFrom(*outMatFc, HPPL_STREAM_DEFAULT);
420
#ifdef PADDLE_WITH_CUDA
Z
zhangjinchao01 已提交
421 422 423 424 425 426 427 428
  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) {
429
    delete[](*selCols)[i].first;
Z
zhangjinchao01 已提交
430 431 432 433 434 435 436 437 438 439 440 441 442 443 444
  }
}

#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);
445
#ifdef PADDLE_WITH_CUDA
Z
zhangjinchao01 已提交
446 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
  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;
}