MKLDNNTester.cpp 11.1 KB
Newer Older
T
tensor-tang 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/* Copyright (c) 2017 PaddlePaddle Authors. All Rights Reserve.

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

15 16 17
#include "MKLDNNTester.h"
#include "paddle/gserver/layers/MKLDNNBase.h"
#include "paddle/gserver/layers/MKLDNNLayer.h"
T
tensor-tang 已提交
18 19 20 21

namespace paddle {

// init data layer and test layer of both dnn and reference
22
void MKLDNNTester::reset(const TestConfig& dnn,
T
tensor-tang 已提交
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
                         const TestConfig& ref,
                         size_t batchSize) {
  const bool trans = false;
  const bool useGpu = false;

  // clear
  configs_.clear();
  layerNames_.clear();
  dataLayers_.clear();
  datas_.clear();
  layerMaps_.clear();
  parameters_.clear();
  testLayers_.clear();

  // resize
  configs_.resize(NUM);
  layerNames_.resize(NUM);
  dataLayers_.resize(NUM);
  datas_.resize(NUM);
  layerMaps_.resize(NUM);
  parameters_.resize(NUM);
  testLayers_.resize(NUM);

  // reset configs and layer names
  configs_[DNN] = dnn;
  configs_[REF] = ref;
  layerNames_[DNN] = "mkldnn";     // the first is mkldnn layer
  layerNames_[REF] = "reference";  // second is reference layer

  // reset others
  for (size_t i = 0; i < NUM; ++i) {
    configs_[i].layerConfig.set_name(layerNames_[i]);
    initDataLayer(configs_[i],
                  &(dataLayers_[i]),
                  &(datas_[i]),
                  &(layerMaps_[i]),
                  layerNames_[i],
                  batchSize,
                  trans,
                  useGpu);
    initTestLayer(
        configs_[i], &(layerMaps_[i]), &(parameters_[i]), &(testLayers_[i]));
  }
  dnnLayer_ = testLayers_[DNN];
  refLayer_ = testLayers_[REF];
  EXPECT_EQ(dataLayers_[DNN].size(), dataLayers_[REF].size());
  EXPECT_EQ(parameters_[DNN].size(), parameters_[REF].size());

  setInputImgSize();
}

74
void MKLDNNTester::setInputImgSize() {
T
tensor-tang 已提交
75 76 77 78 79 80 81 82 83 84
  for (size_t n = 0; n < dataLayers_.size(); ++n) {
    for (size_t i = 0; i < dataLayers_[n].size(); ++i) {
      // TODO(TJ): fix me when concat and elewise ready
      dataLayers_[n][i]->getOutput().setFrameHeight(ih_);
      dataLayers_[n][i]->getOutput().setFrameWidth(iw_);
    }
  }
}

// init randome parameters of ref, and copy to mkldnn
85
void MKLDNNTester::randomWgtDatas() {
T
tensor-tang 已提交
86 87 88 89 90 91 92 93 94 95 96 97 98
  EXPECT_EQ(parameters_[DNN].size(), parameters_[REF].size());
  for (size_t i = 0; i < parameters_[REF].size(); ++i) {
    const VectorPtr& dnnValue = parameters_[DNN][i]->getBuf(PARAMETER_VALUE);
    const VectorPtr& refValue = parameters_[REF][i]->getBuf(PARAMETER_VALUE);
    parameters_[REF][i]->randomize();
    dnnValue->copyFrom(*refValue);

    VLOG(lvl_) << "Random weight data " << parameters_[DNN][i]->getName();
    printVector(dnnValue);
  }
}

// random botdata of ref layer and copy same to mkldnn
99
void MKLDNNTester::randomBotDatas() {
T
tensor-tang 已提交
100 101 102 103 104 105 106 107 108 109
  CHECK_EQ(dataLayers_.size(), NUM);
  for (size_t i = 0; i < dataLayers_[DNN].size(); ++i) {
    dataLayers_[REF][i]->getOutputValue()->randomizeUniform();
    dataLayers_[DNN][i]->getOutputValue()->copyFrom(
        *(dataLayers_[REF][i]->getOutputValue()));
    VLOG(lvl_) << "Input " << i << " data:";
    printMatrix(dataLayers_[REF][i]->getOutputValue());
  }
}

110
void MKLDNNTester::randomTopDiffs() {
T
tensor-tang 已提交
111 112 113 114 115 116
  refLayer_->getOutputGrad()->randomizeUniform();
  dnnLayer_->getOutputGrad()->copyFrom(*(refLayer_->getOutputGrad()));
  VLOG(lvl_) << "Random dom Backward Input, TopDiff: ";
  printMatrix(refLayer_->getOutputGrad());
}

117
void MKLDNNTester::checkForward() {
T
tensor-tang 已提交
118 119 120
  printTopDatas();
  double delta = compareMatrix(testLayers_[DNN]->getOutputValue(),
                               testLayers_[REF]->getOutputValue());
T
tensor-tang 已提交
121
  VLOG(MKLDNN_ALL) << "Check Forward";
T
tensor-tang 已提交
122 123 124
  EXPECT_LE(fabs(delta), eps_);
}

125
void MKLDNNTester::checkBackwardData() {
T
tensor-tang 已提交
126 127
  // TODO(TJ): uncomment me when batch norm ready
  // const bool isBN = dnnLayer_->getType() == "mkldnn_batch_norm";
T
tensor-tang 已提交
128 129 130 131 132 133 134 135 136 137
  for (size_t i = 0; i < dataLayers_[DNN].size(); ++i) {
    const MatrixPtr& dnnDiff = dataLayers_[DNN][i]->getOutputGrad();
    const MatrixPtr& refDiff = dataLayers_[REF][i]->getOutputGrad();
    VLOG(lvl_) << "Mkldnn Backward Output BotDiff " << i;
    printMatrix(dnnDiff);
    VLOG(lvl_) << "Reference Backward Output BotDiff " << i;
    printMatrix(refDiff);

    double delta = compareMatrix(dnnDiff, refDiff);
    EXPECT_LE(fabs(delta), eps_);
T
tensor-tang 已提交
138 139 140 141 142
    // TODO(TJ): uncomment me when batch norm ready
    // if (isBN) {
    //  // the other two inputs in batch norm are for moving mean and var
    //  break;
    // }
T
tensor-tang 已提交
143 144 145
  }
}

146
void MKLDNNTester::checkBackwardWgts() {
T
tensor-tang 已提交
147 148 149 150
  CHECK_EQ(parameters_[DNN].size(), parameters_[REF].size());
  vector<VectorPtr> dnnWgts;  // used to temply save mkldnn weights
  saveWgt(parameters_[DNN], dnnWgts);

151 152
  const MKLDNNLayerPtr dnnlayer =
      std::dynamic_pointer_cast<MKLDNNLayer>(dnnLayer_);
T
tensor-tang 已提交
153
  CHECK(dnnlayer);
154
  dnnlayer->convertWeightsToPaddle();
T
tensor-tang 已提交
155 156 157 158 159 160 161 162 163 164 165 166
  for (size_t i = 0; i < parameters_[DNN].size(); ++i) {
    const VectorPtr& dnn = parameters_[DNN][i]->getBuf(PARAMETER_VALUE);
    const VectorPtr& ref = parameters_[REF][i]->getBuf(PARAMETER_VALUE);
    VLOG(lvl_) << "Mkldnn Output weight " << parameters_[DNN][i]->getName();
    printVector(dnn);
    VLOG(lvl_) << "Reference Output weight " << parameters_[REF][i]->getName();
    printVector(ref);

    double delta = compareVector(dnn, ref);
    EXPECT_LE(fabs(delta), eps_);
  }

T
tensor-tang 已提交
167
  VLOG(MKLDNN_ALL) << "Restore dnn weights before comapre";
T
tensor-tang 已提交
168 169 170
  restoreWgt(dnnWgts, parameters_[DNN]);
}

171
void MKLDNNTester::saveWgt(const vector<ParameterPtr>& from,
T
tensor-tang 已提交
172 173 174 175 176 177 178 179 180 181
                           vector<VectorPtr>& to) {
  const bool useGpu = false;
  to.resize(from.size());
  for (size_t i = 0; i < to.size(); ++i) {
    const VectorPtr& wgt = from[i]->getBuf(PARAMETER_VALUE);
    to[i] = Vector::create(wgt->getSize(), useGpu);
    to[i]->copyFrom(*wgt);
  }
}

182
void MKLDNNTester::restoreWgt(const vector<VectorPtr>& from,
T
tensor-tang 已提交
183 184 185 186 187 188 189 190 191
                              vector<ParameterPtr>& to) {
  CHECK_EQ(from.size(), to.size());
  for (size_t i = 0; i < from.size(); ++i) {
    const VectorPtr& wgt = to[i]->getBuf(PARAMETER_VALUE);
    wgt->copyFrom(*from[i]);
  }
}

// clear parameters grad
192
void MKLDNNTester::clearWgtDiffs() {
T
tensor-tang 已提交
193 194 195 196 197 198 199 200 201 202
  for (size_t n = 0; n < parameters_.size(); ++n) {
    for (size_t i = 0; i < parameters_[n].size(); ++i) {
      const VectorPtr& grad = parameters_[n][i]->getBuf(PARAMETER_GRADIENT);
      if (grad) {
        grad->zeroMem();
      }
    }
  }
}

203
void MKLDNNTester::clearBotDiffs() {
T
tensor-tang 已提交
204 205 206 207 208 209 210 211 212
  // dnn and ref
  for (size_t n = 0; n < dataLayers_.size(); ++n) {
    // all inputs layers
    for (size_t i = 0; i < dataLayers_[n].size(); ++i) {
      dataLayers_[n][i]->getOutputGrad()->zeroMem();
    }
  }
}

213
void MKLDNNTester::clearBotDiffs(int n) {
T
tensor-tang 已提交
214 215 216 217 218 219 220
  CHECK_LT(n, NUM);
  // all inputs layers
  for (size_t i = 0; i < dataLayers_[n].size(); ++i) {
    dataLayers_[n][i]->getOutputGrad()->zeroMem();
  }
}

221
void MKLDNNTester::clearTopDatas() {
T
tensor-tang 已提交
222 223 224 225 226
  for (size_t i = 0; i < testLayers_.size(); ++i) {
    testLayers_[i]->getOutputValue()->zeroMem();
  }
}

227
void MKLDNNTester::printTopDatas() {
T
tensor-tang 已提交
228 229 230 231 232 233 234 235 236 237
  if (!log_) {
    return;
  }

  for (int n = 0; n < NUM; ++n) {
    VLOG(lvl_) << testLayers_[n]->getType() << " forward output TopData: ";
    printMatrix(testLayers_[n]->getOutputValue());
  }
}

238
void MKLDNNTester::printMatrix(const MatrixPtr& m) {
T
tensor-tang 已提交
239 240 241
  if (!log_) {
    return;
  }
T
tensor-tang 已提交
242 243 244 245

  std::ostringstream ostr;
  m->print(ostr);
  VLOG(lvl_) << std::endl << ostr.str();
T
tensor-tang 已提交
246 247
}

248
void MKLDNNTester::printVector(const VectorPtr& v) {
T
tensor-tang 已提交
249 250 251 252
  if (!log_) {
    return;
  }

T
tensor-tang 已提交
253 254 255
  std::ostringstream ostr;
  v->print(ostr, v->getSize());
  VLOG(lvl_) << std::endl << ostr.str();
T
tensor-tang 已提交
256 257
}

258
double MKLDNNTester::getDelta(const real* d1,
T
tensor-tang 已提交
259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279
                              const real* d2,
                              size_t len,
                              const float failRate,
                              const float thres) {
  double delta = 0, sum = 0;
  int failCnt = 0;
  const double eps = 1e-5;
  double maxOut = 0;
  for (size_t i = 0; i < len; ++i) {
    double ref = fabs(d2[i]);
    double diff = fabs(d1[i] - d2[i]);
    delta += diff;
    sum += ref;
    if (ref > eps && fabs(d1[i]) > eps && diff / ref > thres) {
      maxOut = std::max(maxOut, diff / ref);
      failCnt++;
    }
  }
  EXPECT_TRUE(std::isnormal(sum));
  EXPECT_FALSE(std::isinf(sum));
  EXPECT_FALSE(std::isnan(delta));
T
tensor-tang 已提交
280 281
  VLOG(MKLDNN_ALL) << "reference avg data: " << sum / len
                   << ", delta: " << delta / sum << ", failCnt:" << failCnt;
T
tensor-tang 已提交
282 283 284
  return (failCnt / (float)len) > failRate ? maxOut : delta / sum;
}

285
double MKLDNNTester::compareMatrix(const MatrixPtr& m1, const MatrixPtr& m2) {
T
tensor-tang 已提交
286 287 288 289
  CHECK_EQ(m1->getElementCnt(), m2->getElementCnt());
  return getDelta(m1->getData(), m2->getData(), m1->getElementCnt());
}

290
double MKLDNNTester::compareVector(const VectorPtr& v1, const VectorPtr& v2) {
T
tensor-tang 已提交
291 292 293 294
  CHECK_EQ(v1->getSize(), v2->getSize());
  return getDelta(v1->getData(), v2->getData(), v1->getSize());
}

295
void MKLDNNTester::runOnce() {
T
tensor-tang 已提交
296 297 298 299 300 301 302 303 304 305 306 307 308 309 310
  // test forward
  randomBotDatas();
  dnnLayer_->forward(PASS_TRAIN);
  refLayer_->forward(PASS_TRAIN);
  checkForward();

  // test backward
  randomTopDiffs();
  dnnLayer_->backward(nullptr);
  refLayer_->backward(nullptr);
  checkBackwardData();
  checkBackwardWgts();

  // clear buffers
  // ref code will addto the diff, dnn code will writeto it
T
tensor-tang 已提交
311
  // and clearTopDatas() and clearWgtDiffs() should be coverd by test layers
T
tensor-tang 已提交
312 313 314
  clearBotDiffs(REF);
}

315
void MKLDNNTester::run(const TestConfig& dnn,
T
tensor-tang 已提交
316 317 318 319 320 321 322 323
                       const TestConfig& ref,
                       size_t batchSize,
                       size_t inputImgH,
                       size_t inputImgW,
                       size_t iter,
                       float epsilon,
                       bool log,
                       int level) {
T
tensor-tang 已提交
324 325
  VLOG(MKLDNN_TESTS) << "Test MKLDNN functionality: " << dnn.layerConfig.type()
                     << " vs " << ref.layerConfig.type();
T
tensor-tang 已提交
326 327 328 329 330 331 332
  ih_ = inputImgH;
  iw_ = inputImgW;
  iter_ = iter;
  eps_ = epsilon;
  log_ = log;
  lvl_ = level;

T
tensor-tang 已提交
333 334
  // Firstly test FLAGS_use_mkldnn_wgt = false
  FLAGS_use_mkldnn_wgt = false;
T
tensor-tang 已提交
335
  // reset and run once
T
tensor-tang 已提交
336
  reset(dnn, ref, batchSize);
T
tensor-tang 已提交
337 338 339
  randomWgtDatas();
  clearWgtDiffs();
  clearBotDiffs();
T
tensor-tang 已提交
340
  for (size_t i = 0; i < iter_; ++i) {
T
tensor-tang 已提交
341
    VLOG(MKLDNN_TESTS) << "Check Iteration " << i;
T
tensor-tang 已提交
342 343
    runOnce();
  }
T
tensor-tang 已提交
344

T
tensor-tang 已提交
345 346 347
  // Then test FLAGS_use_mkldnn_wgt = true
  FLAGS_use_mkldnn_wgt = true;
  // after run once the mkldnn weight has been stored in dnnlayer
T
tensor-tang 已提交
348
  // then save the weights and restart again
T
tensor-tang 已提交
349 350 351 352
  vector<VectorPtr> dnnWgts, refWgts;
  CHECK_EQ(parameters_[DNN].size(), parameters_[REF].size());
  saveWgt(parameters_[DNN], dnnWgts);
  saveWgt(parameters_[REF], refWgts);
T
tensor-tang 已提交
353

T
tensor-tang 已提交
354 355
  // restart again with flag true
  reset(dnn, ref, batchSize);
T
tensor-tang 已提交
356

T
tensor-tang 已提交
357 358 359 360 361
  // restore wgt
  restoreWgt(dnnWgts, parameters_[DNN]);
  restoreWgt(refWgts, parameters_[REF]);
  clearWgtDiffs();
  clearBotDiffs();
T
tensor-tang 已提交
362

T
tensor-tang 已提交
363
  for (size_t i = 0; i < iter_; ++i) {
T
tensor-tang 已提交
364
    VLOG(MKLDNN_TESTS) << "Check Iteration " << i;
T
tensor-tang 已提交
365 366 367 368 369
    runOnce();
  }
}

}  //  namespace paddle