benchmark.cc 15.2 KB
Newer Older
T
tensor-tang 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License. */

#include <iostream>
T
tensor-tang 已提交
16
#include <random>
T
tensor-tang 已提交
17 18 19 20
#include <string>
#include <vector>
#include "gflags/gflags.h"
#include "glog/logging.h"
T
tensor-tang 已提交
21
#include "paddle/fluid/framework/tensor.h"
T
tensor-tang 已提交
22
#include "paddle/fluid/operators/jit/kernels.h"
23
#include "paddle/fluid/platform/device_tracer.h"
T
tensor-tang 已提交
24 25
#include "paddle/fluid/platform/place.h"
#include "paddle/fluid/platform/port.h"
T
tensor-tang 已提交
26
#include "paddle/fluid/platform/variant.h"  // for UNUSED
T
tensor-tang 已提交
27 28 29 30

DEFINE_int32(burning, 10, "Burning times.");
DEFINE_int32(repeat, 3000, "Repeat times.");
DEFINE_int32(max_size, 1000, "The Max size would be tested.");
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
DEFINE_string(filter, "", "The Benchmark name would be run.");

class BenchJITKernel {
 public:
  BenchJITKernel() = default;
  virtual ~BenchJITKernel() = default;
  virtual void Run() = 0;
  virtual const char* Name() = 0;
  virtual const char* Dtype() = 0;
  virtual const char* Place() = 0;
};

static std::vector<BenchJITKernel*> g_all_benchmarks;

BenchJITKernel* InsertBenchmark(BenchJITKernel* b) {
  g_all_benchmarks.push_back(b);
  return b;
}

#define BENCH_JITKERNEL(name, dtype, place)                                    \
  class BenchJITKernel_##name##_##dtype##_##place##_ : public BenchJITKernel { \
   public:                                                                     \
    const char* Name() override { return #name; }                              \
    const char* Dtype() override { return #dtype; }                            \
    const char* Place() override { return #place; }                            \
    void Run() override;                                                       \
  };                                                                           \
T
tensor-tang 已提交
58
  static auto inserted_##name##_##dtype##_##place##_ UNUSED =                  \
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
      InsertBenchmark(new BenchJITKernel_##name##_##dtype##_##place##_());     \
  void BenchJITKernel_##name##_##dtype##_##place##_::Run()

#define BENCH_FP32_CPU(name) BENCH_JITKERNEL(name, FP32, CPU)

void RUN_ALL_BENCHMARK() {
  for (auto p : g_all_benchmarks) {
    if (!FLAGS_filter.empty() && FLAGS_filter != p->Name()) {
      continue;
    }
    LOG(INFO) << "Benchmark " << p->Name() << "." << p->Dtype() << "."
              << p->Place();
    p->Run();
  }
}
T
tensor-tang 已提交
74 75 76

template <typename T>
void RandomVec(const int n, T* a, const T lower = static_cast<T>(-20.f),
77 78
               const T upper = static_cast<T>(20.f), unsigned int seed = 100) {
  std::mt19937 rng(seed);
T
tensor-tang 已提交
79 80 81 82 83 84 85 86 87 88 89 90 91 92
  std::uniform_real_distribution<double> uniform_dist(0, 1);
  for (int i = 0; i < n; ++i) {
    a[i] = static_cast<T>(uniform_dist(rng) * (upper - lower) + lower);
  }
}

std::vector<int> TestSizes() {
  std::vector<int> s;
  for (int i = 1; i <= FLAGS_max_size; ++i) {
    s.push_back(i);
  }
  return s;
}

T
tensor-tang 已提交
93 94 95
template <typename KernelTuples, typename... Args>
struct BenchFunc {
  // return this function avg time
T
tensor-tang 已提交
96
  // TODO(TJ): clear cache every time
T
tensor-tang 已提交
97 98 99 100
  double operator()(const typename KernelTuples::func_type tgt, Args... args) {
    for (int i = 0; i < FLAGS_burning; ++i) {
      tgt(args...);
    }
T
tensor-tang 已提交
101
    auto start = paddle::platform::PosixInNsec() * 1e-3;
T
tensor-tang 已提交
102 103 104
    for (int i = 0; i < FLAGS_repeat; ++i) {
      tgt(args...);
    }
T
tensor-tang 已提交
105
    auto end = paddle::platform::PosixInNsec() * 1e-3;
106
    return static_cast<double>(end - start) / FLAGS_repeat;
T
tensor-tang 已提交
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
  }
};

namespace jit = paddle::operators::jit;

template <jit::KernelType KT, typename KernelTuples, typename PlaceType,
          typename... Args>
void BenchAllImpls(const typename KernelTuples::attr_type& attr, Args... args) {
  BenchFunc<KernelTuples, Args...> benchmark;
  std::vector<std::pair<std::string, double>> infos;
  // test refer
  auto refer = jit::GetRefer<KT, KernelTuples>();
  if (!refer) {
    LOG(FATAL) << "Refer can not be empty!";
  }
  infos.push_back(std::make_pair("Refer", benchmark(refer, args...)));

  // test jitcode
  auto jitcode = jit::GetJitCode<KT, KernelTuples, PlaceType>(attr);
  if (jitcode) {
    infos.push_back(std::make_pair("JitCode", benchmark(jitcode, args...)));
  }
  // test all impls in more
  jit::KernelKey kkey(KT, PlaceType());
  auto& pool = jit::KernelPool().Instance().AllKernels();
  auto iter = pool.find(kkey);
  if (iter != pool.end()) {
    auto& impls = iter->second;
    for (auto& impl : impls) {
T
tensor-tang 已提交
136
      auto i = dynamic_cast<const jit::KernelMore<KernelTuples>*>(impl.get());
T
tensor-tang 已提交
137 138
      if (i && i->UseMe(attr)) {
        auto more = i->GetFunc();
T
tensor-tang 已提交
139 140
        infos.push_back(
            std::make_pair(i->ImplType(), benchmark(more, args...)));
T
tensor-tang 已提交
141 142
      }
    }
T
tensor-tang 已提交
143
  }
T
tensor-tang 已提交
144 145 146 147
  // Test result from Get function
  auto tgt = jit::Get<KT, KernelTuples, PlaceType>(attr);
  if (!tgt) {
    LOG(FATAL) << "Target can not be empty!";
T
tensor-tang 已提交
148
  }
T
tensor-tang 已提交
149 150 151 152 153 154 155 156 157
  infos.push_back(std::make_pair("Target", benchmark(tgt, args...)));

  // print
  std::ostringstream loginfos;
  loginfos << "Kernel Type " << jit::to_string(KT) << ": " << attr << ": ";
  for (auto pair : infos) {
    loginfos << pair.first << " takes " << pair.second << " us; ";
  }
  LOG(INFO) << loginfos.str();
T
tensor-tang 已提交
158 159
}

T
tensor-tang 已提交
160 161
using Tensor = paddle::framework::Tensor;

162
template <jit::KernelType KT, typename T, typename PlaceType>
163
void BenchXYZNKernel() {
T
tensor-tang 已提交
164
  for (int d : TestSizes()) {
T
tensor-tang 已提交
165 166 167 168 169 170 171 172 173 174 175
    Tensor x, y, z;
    x.Resize({d});
    y.Resize({d});
    z.Resize({d});
    T* x_data = x.mutable_data<T>(PlaceType());
    T* y_data = y.mutable_data<T>(PlaceType());
    T* z_data = z.mutable_data<T>(PlaceType());
    RandomVec<T>(d, x_data);
    RandomVec<T>(d, y_data);
    BenchAllImpls<KT, jit::XYZNTuples<T>, PlaceType>(d, x.data<T>(),
                                                     y.data<T>(), z_data, d);
T
tensor-tang 已提交
176 177 178
    // test inplace
    BenchAllImpls<KT, jit::XYZNTuples<T>, PlaceType>(d, x.data<T>(), z_data,
                                                     z_data, d);
T
tensor-tang 已提交
179 180
  }
}
181

182
template <jit::KernelType KT, typename T, typename PlaceType>
183 184 185
void BenchAXYNKernel() {
  for (int d : TestSizes()) {
    const T a = static_cast<T>(3);
T
tensor-tang 已提交
186 187 188 189 190 191 192
    Tensor x, y;
    x.Resize({d});
    y.Resize({d});
    T* x_data = x.mutable_data<T>(PlaceType());
    T* y_data = y.mutable_data<T>(PlaceType());
    RandomVec<T>(d, x_data);
    BenchAllImpls<KT, jit::AXYNTuples<T>, PlaceType>(d, &a, x.data<T>(), y_data,
T
tensor-tang 已提交
193
                                                     d);
T
tensor-tang 已提交
194 195 196
    // test inplace
    BenchAllImpls<KT, jit::AXYNTuples<T>, PlaceType>(d, &a, x.data<T>(), x_data,
                                                     d);
197 198 199
  }
}

200 201 202 203 204 205 206 207 208 209 210
template <jit::KernelType KT, typename T, typename PlaceType>
void BenchXRNKernel() {
  for (int d : TestSizes()) {
    Tensor x;
    RandomVec<T>(d, x.mutable_data<T>({d}, PlaceType()));
    T res;
    BenchAllImpls<KT, jit::XRNTuples<T>, PlaceType>(d, x.data<T>(), &res, d);
  }
}

template <jit::KernelType KT, typename T, typename PlaceType>
211 212
void BenchXYNKernel() {
  for (int d : TestSizes()) {
T
tensor-tang 已提交
213 214 215 216 217 218 219
    Tensor x, y;
    x.Resize({d});
    y.Resize({d});
    T* x_data = x.mutable_data<T>(PlaceType());
    T* y_data = y.mutable_data<T>(PlaceType());
    RandomVec<T>(d, x_data);
    BenchAllImpls<KT, jit::XYNTuples<T>, PlaceType>(d, x.data<T>(), y_data, d);
220 221 222
  }
}

223
template <jit::KernelType KT, typename T, typename PlaceType>
T
tensor-tang 已提交
224 225 226
void BenchLSTMKernel() {
  for (bool use_peephole : {true, false}) {
    for (int d : TestSizes()) {
T
tensor-tang 已提交
227
      const jit::lstm_attr_t attr(d, jit::kVSigmoid, jit::kVTanh, jit::kVTanh,
T
tensor-tang 已提交
228
                                  use_peephole);
T
tensor-tang 已提交
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245
      Tensor x, ct_1, ct, ht, wp, checked;
      x.Resize({4 * d});
      ct_1.Resize({d});
      ct.Resize({d});
      ht.Resize({d});
      wp.Resize({3 * d});
      checked.Resize({2 * d});
      auto place = PlaceType();
      RandomVec<T>(x.numel(), x.mutable_data<T>(place), -2.f, 2.f);
      RandomVec<T>(wp.numel(), wp.mutable_data<T>(place), -2.f, 2.f);
      RandomVec<T>(ct_1.numel(), ct_1.mutable_data<T>(place), -2.f, 2.f);
      const T* ct_1_data = ct_1.data<T>();
      const T* wp_data = wp.data<T>();
      T* x_data = x.mutable_data<T>(place);
      T* checked_data = checked.mutable_data<T>(place);
      T* ct_data = ct.mutable_data<T>(place);
      T* ht_data = ht.mutable_data<T>(place);
T
tensor-tang 已提交
246 247 248 249 250 251 252 253 254
      jit::lstm_t step;
      step.gates = x_data;
      step.ct_1 = ct_1_data;
      step.ct = ct_data;
      step.ht = ht_data;
      if (use_peephole) {
        step.wp = wp_data;
        step.checked = checked_data;
      }
T
tensor-tang 已提交
255
      BenchAllImpls<KT, jit::LSTMTuples<T>, PlaceType>(attr, &step, &attr);
T
tensor-tang 已提交
256 257 258 259
    }
  }
}

260
template <jit::KernelType KT, typename T, typename PlaceType>
261 262
void BenchGRUKernel() {
  for (int d : TestSizes()) {
T
tensor-tang 已提交
263
    const jit::gru_attr_t attr(d, jit::kVSigmoid, jit::kVTanh);
T
tensor-tang 已提交
264 265 266 267 268 269 270 271 272 273
    auto place = PlaceType();
    Tensor x, ht_1, ht;
    x.Resize({3 * d});
    ht_1.Resize({d});
    ht.Resize({d});
    RandomVec<T>(3 * d, x.mutable_data<T>(place), -2.f, 2.f);
    RandomVec<T>(d, ht_1.mutable_data<T>(place), -2.f, 2.f);
    const T* ht_1_data = ht_1.data<T>();
    T* x_data = x.mutable_data<T>(place);
    T* ht_data = ht.mutable_data<T>(place);
274 275 276 277
    jit::gru_t step;
    step.gates = x_data;
    step.ht_1 = ht_1_data;
    step.ht = ht_data;
T
tensor-tang 已提交
278
    BenchAllImpls<KT, jit::GRUTuples<T>, PlaceType>(attr, &step, &attr);
279 280 281
  }
}

282
template <jit::KernelType KT, typename T, typename PlaceType>
283
void BenchSeqPoolKernel() {
284 285
  std::vector<jit::SeqPoolType> pool_types = {
      jit::SeqPoolType::kSum, jit::SeqPoolType::kAvg, jit::SeqPoolType::kSqrt};
286
  for (auto type : pool_types) {
T
tensor-tang 已提交
287
    for (int w : TestSizes()) {
T
tensor-tang 已提交
288
      jit::seq_pool_attr_t attr(w, type);
T
tensor-tang 已提交
289
      for (int h : TestSizes()) {
T
tensor-tang 已提交
290
        attr.h = h;
T
tensor-tang 已提交
291 292 293 294 295 296
        Tensor x, y;
        x.Resize({h * w});
        y.Resize({w});
        RandomVec<T>(h * w, x.mutable_data<T>(PlaceType()), -2.f, 2.f);
        const T* x_data = x.data<T>();
        T* y_data = y.mutable_data<T>(PlaceType());
297 298 299 300 301 302 303
        BenchAllImpls<KT, jit::SeqPoolTuples<T>, PlaceType>(attr, x_data,
                                                            y_data, &attr);
      }
    }
  }
}

304 305 306 307 308 309 310 311 312 313 314
template <jit::KernelType KT, typename T, typename PlaceType>
void BenchEmbSeqPoolKernel() {
  std::vector<jit::SeqPoolType> pool_types = {jit::SeqPoolType::kSum};
  int64_t tbl_h = 1e4;
  for (int tbl_w : {10, 16, 256}) {
    Tensor table;
    table.Resize({tbl_h, tbl_w});
    RandomVec<T>(tbl_h * tbl_w, table.mutable_data<T>(PlaceType()), -2.f, 2.f);
    const T* table_data = table.data<T>();
    for (auto type : pool_types) {
      for (int idx_w : {1, 2, 10, 16}) {
315
        for (int idx_h : {1, 2, 9, 13, 16}) {
316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334
          int64_t out_w = tbl_w * idx_w;
          jit::emb_seq_pool_attr_t attr(tbl_h, tbl_w, idx_h, idx_w, out_w,
                                        type);
          Tensor idx, out;
          idx.Resize({idx_h, idx_w});
          out.Resize({out_w});
          RandomVec<int64_t>(idx_h * idx_w,
                             idx.mutable_data<int64_t>(PlaceType()), 0,
                             tbl_h - 1);
          const int64_t* idx_data = idx.data<int64_t>();
          T* o_data = out.mutable_data<T>(PlaceType());
          BenchAllImpls<KT, jit::EmbSeqPoolTuples<T>, PlaceType>(
              attr, table_data, idx_data, o_data, &attr);
        }
      }
    }
  }
}

335
template <jit::KernelType KT, typename T, typename PlaceType>
T
tensor-tang 已提交
336 337
void BenchMatMulKernel() {
  for (int m : {1, 2, 3, 4}) {
338
    for (int n : TestSizes()) {
T
tensor-tang 已提交
339
      for (int k : TestSizes()) {
T
tensor-tang 已提交
340 341 342 343 344 345 346 347 348
        Tensor a, b, c;
        a.Resize({m * k});
        b.Resize({k * n});
        c.Resize({m * n});
        RandomVec<T>(m * k, a.mutable_data<T>(PlaceType()), -2.f, 2.f);
        RandomVec<T>(k * n, b.mutable_data<T>(PlaceType()), -2.f, 2.f);
        const T* a_data = a.data<T>();
        const T* b_data = b.data<T>();
        T* c_data = c.mutable_data<T>(PlaceType());
349 350 351
        const jit::matmul_attr_t attr{m, n, k};
        BenchAllImpls<KT, jit::MatMulTuples<T>, PlaceType>(attr, a_data, b_data,
                                                           c_data, &attr);
T
tensor-tang 已提交
352 353 354 355 356
      }
    }
  }
}

357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372
template <jit::KernelType KT, typename T, typename PlaceType>
void BenchSoftmaxKernel() {
  for (int bs : {1, 2, 10}) {
    for (int n : TestSizes()) {
      Tensor x, y;
      x.Resize({bs, n});
      y.Resize({bs, n});
      RandomVec<T>(bs * n, x.mutable_data<T>(PlaceType()), -2.f, 2.f);
      const T* x_data = x.data<T>();
      T* y_data = y.mutable_data<T>(PlaceType());
      BenchAllImpls<KT, jit::SoftmaxTuples<T>, PlaceType>(n, x_data, y_data, n,
                                                          bs);
    }
  }
}

373
using T = float;
374
using CPUPlace = paddle::platform::CPUPlace;
375 376

// xyzn
377 378 379 380
BENCH_FP32_CPU(kVMul) { BenchXYZNKernel<jit::kVMul, T, CPUPlace>(); }
BENCH_FP32_CPU(kVAdd) { BenchXYZNKernel<jit::kVAdd, T, CPUPlace>(); }
BENCH_FP32_CPU(kVAddRelu) { BenchXYZNKernel<jit::kVAddRelu, T, CPUPlace>(); }
BENCH_FP32_CPU(kVSub) { BenchXYZNKernel<jit::kVSub, T, CPUPlace>(); }
381 382

// axyn
383 384
BENCH_FP32_CPU(kVScal) { BenchAXYNKernel<jit::kVScal, T, CPUPlace>(); }
BENCH_FP32_CPU(kVAddBias) { BenchAXYNKernel<jit::kVAddBias, T, CPUPlace>(); }
385

386 387 388
// xrn
BENCH_FP32_CPU(kHSum) { BenchXRNKernel<jit::kHSum, T, CPUPlace>(); }
BENCH_FP32_CPU(kHMax) { BenchXRNKernel<jit::kHMax, T, CPUPlace>(); }
389 390

// xyn
391 392 393 394 395 396
BENCH_FP32_CPU(kVRelu) { BenchXYNKernel<jit::kVRelu, T, CPUPlace>(); }
BENCH_FP32_CPU(kVIdentity) { BenchXYNKernel<jit::kVIdentity, T, CPUPlace>(); }
BENCH_FP32_CPU(kVSquare) { BenchXYNKernel<jit::kVSquare, T, CPUPlace>(); }
BENCH_FP32_CPU(kVExp) { BenchXYNKernel<jit::kVExp, T, CPUPlace>(); }
BENCH_FP32_CPU(kVSigmoid) { BenchXYNKernel<jit::kVSigmoid, T, CPUPlace>(); }
BENCH_FP32_CPU(kVTanh) { BenchXYNKernel<jit::kVTanh, T, CPUPlace>(); }
397 398

// lstm and peephole
399 400
BENCH_FP32_CPU(kLSTMCtHt) { BenchLSTMKernel<jit::kLSTMCtHt, T, CPUPlace>(); }
BENCH_FP32_CPU(kLSTMC1H1) { BenchLSTMKernel<jit::kLSTMC1H1, T, CPUPlace>(); }
401 402

// gru functions
403 404 405
BENCH_FP32_CPU(kGRUH1) { BenchGRUKernel<jit::kGRUH1, T, CPUPlace>(); }
BENCH_FP32_CPU(kGRUHtPart1) { BenchGRUKernel<jit::kGRUHtPart1, T, CPUPlace>(); }
BENCH_FP32_CPU(kGRUHtPart2) { BenchGRUKernel<jit::kGRUHtPart2, T, CPUPlace>(); }
406 407

// seq pool function
408
BENCH_FP32_CPU(kSeqPool) { BenchSeqPoolKernel<jit::kSeqPool, T, CPUPlace>(); }
409

410 411 412 413 414
// embedding seq pool function
BENCH_FP32_CPU(kEmbSeqPool) {
  BenchEmbSeqPoolKernel<jit::kEmbSeqPool, T, CPUPlace>();
}

415
// matmul
416 417 418 419
BENCH_FP32_CPU(kMatMul) { BenchMatMulKernel<jit::kMatMul, T, CPUPlace>(); }

// softmax
BENCH_FP32_CPU(kSoftmax) { BenchSoftmaxKernel<jit::kSoftmax, T, CPUPlace>(); }
420

421 422 423 424 425 426
// Benchmark all jit kernels including jitcode, mkl and refer.
// To use this tool, run command: ./benchmark [options...]
// Options:
//     --burning: the burning time before count
//     --repeat: the repeat times
//     --max_size: the max size would be tested
427
//     --filter: the bench name would be run
428 429 430 431 432
int main(int argc, char* argv[]) {
  gflags::ParseCommandLineFlags(&argc, &argv, true);
  google::InitGoogleLogging(argv[0]);
  LOG(INFO) << "Burning " << FLAGS_burning << " times, Repeat " << FLAGS_repeat
            << " times.";
T
tensor-tang 已提交
433

434
  RUN_ALL_BENCHMARK();
435
}