test.cc 50.2 KB
Newer Older
T
tensor-tang 已提交
1
/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
2 3 4 5 6 7 8 9 10 11 12 13

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. */
T
tensor-tang 已提交
14

15
#include <iostream>
T
tensor-tang 已提交
16
#include <random>
17

T
tensor-tang 已提交
18 19 20
#include "gflags/gflags.h"
#include "glog/logging.h"
#include "gtest/gtest.h"
T
tensor-tang 已提交
21
#include "paddle/fluid/operators/jit/kernels.h"
T
tensor-tang 已提交
22
#include "paddle/fluid/platform/cpu_info.h"
T
tensor-tang 已提交
23
#include "paddle/fluid/platform/place.h"
T
tensor-tang 已提交
24

25
DEFINE_double(acc, 1e-5, "Test accuracy threshold.");
26

T
tensor-tang 已提交
27
template <typename T>
28 29
void RandomVec(const int n, T* a, const T lower = static_cast<T>(-2.f),
               const T upper = static_cast<T>(2.f)) {
T
tensor-tang 已提交
30 31 32 33 34 35 36 37 38
  static unsigned int seed = 100;
  std::mt19937 rng(seed++);
  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);
  }
}

template <typename T>
39
void ExpectEQ(const T* target, const T* refer, size_t n) {
T
tensor-tang 已提交
40
  if (std::is_floating_point<T>::value) {
41
    for (size_t i = 0; i < n; ++i) {
T
tensor-tang 已提交
42
      EXPECT_NEAR(target[i], refer[i], FLAGS_acc) << " at index : " << i;
T
tensor-tang 已提交
43 44
    }
  } else {
45
    for (size_t i = 0; i < n; ++i) {
T
tensor-tang 已提交
46
      EXPECT_EQ(target[i], refer[i]) << " at index : " << i;
T
tensor-tang 已提交
47 48 49 50
    }
  }
}

T
tensor-tang 已提交
51 52
std::vector<int> TestSizes() {
  std::vector<int> s;
T
tensor-tang 已提交
53
  for (int i = 1; i < 32; ++i) {
T
tensor-tang 已提交
54 55
    s.push_back(i);
  }
T
tensor-tang 已提交
56 57 58 59
  // test some large size
  s.push_back(100);
  s.push_back(1000);
  s.push_back(2000);
T
tensor-tang 已提交
60 61 62
  return s;
}

T
tensor-tang 已提交
63
namespace jit = paddle::operators::jit;
64
using CPUPlace = paddle::platform::CPUPlace;
T
tensor-tang 已提交
65

66
template <typename KernelTuple, typename PlaceType, typename Tester,
67
          typename... Args>
68 69
void TestAllImpls(const typename KernelTuple::attr_type& attr,
                  const Tester& verifier, const Args&... args) {
70 71 72 73
  auto funcs = jit::GetAllCandidateFuncsWithTypes<KernelTuple, PlaceType>(attr);
  for (auto f : funcs) {
    VLOG(10) << "Test Kernel " << f.first;
    verifier(f.second, args...);
T
tensor-tang 已提交
74
  }
T
tensor-tang 已提交
75 76
}

77 78 79 80
template <typename KernelTuple, typename PlaceType>
void TestKernelXYZN() {
  using T = typename KernelTuple::data_type;
  VLOG(10) << "Test JITKernel: " << jit::to_string(KernelTuple::kernel_type);
T
tensor-tang 已提交
81
  for (int d : TestSizes()) {
82
    auto ref = jit::GetReferFunc<KernelTuple>();
T
tensor-tang 已提交
83 84
    EXPECT_TRUE(ref != nullptr);

T
tensor-tang 已提交
85
    std::vector<T> x(d), y(d), zref(d);
T
tensor-tang 已提交
86 87 88
    RandomVec<T>(d, x.data());
    RandomVec<T>(d, y.data());

T
tensor-tang 已提交
89 90 91 92 93 94 95 96 97 98 99
    std::vector<T> xinp(d), yinp(d);  // inplace test
    std::copy(x.begin(), x.end(), xinp.begin());
    std::copy(y.begin(), y.end(), yinp.begin());

    const T* x_data = x.data();
    const T* y_data = y.data();
    T* zref_data = zref.data();
    T* xinp_data = xinp.data();
    T* yinp_data = yinp.data();

    // test refer code inplace
T
tensor-tang 已提交
100
    ref(x_data, y_data, zref_data, d);
T
tensor-tang 已提交
101 102 103 104 105
    ref(x_data, yinp_data, yinp_data, d);
    ref(xinp_data, y_data, xinp_data, d);
    ExpectEQ<T>(xinp_data, zref_data, d);
    ExpectEQ<T>(yinp_data, zref_data, d);

106 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
    auto verifier = [](const typename KernelTuple::func_type tgt,
                       const std::vector<T>& x, const std::vector<T>& y,
                       const std::vector<T>& zref) {
      EXPECT_TRUE(tgt != nullptr);
      EXPECT_EQ(zref.size(), x.size());
      EXPECT_EQ(zref.size(), y.size());
      const T* x_data = x.data();
      const T* y_data = y.data();
      const T* zref_data = zref.data();
      const int d = zref.size();

      std::vector<T> ztgt(d);
      T* ztgt_data = ztgt.data();
      // test normal
      tgt(x_data, y_data, ztgt_data, d);
      ExpectEQ<T>(ztgt_data, zref_data, d);
      // test inplace x
      std::copy(x.begin(), x.end(), ztgt.begin());
      tgt(ztgt_data, y_data, ztgt_data, d);
      ExpectEQ<T>(ztgt_data, zref_data, d);
      // test inplace y
      std::copy(y.begin(), y.end(), ztgt.begin());
      tgt(x_data, ztgt_data, ztgt_data, d);
      ExpectEQ<T>(ztgt_data, zref_data, d);
    };

    TestAllImpls<KernelTuple, PlaceType>(d, verifier, x, y, zref);
T
tensor-tang 已提交
133 134
  }
}
T
tensor-tang 已提交
135

136 137 138 139
template <typename KernelTuple, typename PlaceType>
void TestKernelAXYN() {
  using T = typename KernelTuple::data_type;
  VLOG(10) << "Test JITKernel: " << jit::to_string(KernelTuple::kernel_type);
140
  for (int d : TestSizes()) {
141
    auto ref = jit::GetReferFunc<KernelTuple>();
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
    EXPECT_TRUE(ref != nullptr);

    const T a = static_cast<T>(3);
    std::vector<T> x(d), yref(d);
    std::vector<T> xinp(d);  // inplace test
    RandomVec<T>(d, x.data());
    std::copy(x.begin(), x.end(), xinp.begin());

    const T* x_data = x.data();
    T* yref_data = yref.data();
    T* xinp_data = xinp.data();
    // test refer code inplace
    ref(&a, x_data, yref_data, d);
    ref(&a, xinp_data, xinp_data, d);
    ExpectEQ<T>(xinp_data, yref_data, d);

158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
    auto verifier = [](const typename KernelTuple::func_type tgt, const T a,
                       const std::vector<T>& x, const std::vector<T>& yref) {
      EXPECT_TRUE(tgt != nullptr);
      EXPECT_EQ(yref.size(), x.size());
      const T* x_data = x.data();
      const T* yref_data = yref.data();
      const int d = yref.size();
      std::vector<T> ytgt(d);
      T* ytgt_data = ytgt.data();
      // test normal
      tgt(&a, x_data, ytgt_data, d);
      ExpectEQ<T>(ytgt_data, yref_data, d);
      // test inplace x
      std::copy(x.begin(), x.end(), ytgt.begin());
      tgt(&a, ytgt_data, ytgt_data, d);
      ExpectEQ<T>(ytgt_data, yref_data, d);
    };
    TestAllImpls<KernelTuple, PlaceType>(d, verifier, a, x, yref);
176 177 178
  }
}

179 180 181 182
template <typename KernelTuple, typename PlaceType>
void TestKernelXYN() {
  using T = typename KernelTuple::data_type;
  VLOG(10) << "Test JITKernel: " << jit::to_string(KernelTuple::kernel_type);
183
  for (int d : TestSizes()) {
184
    auto ref = jit::GetReferFunc<KernelTuple>();
185 186 187 188
    EXPECT_TRUE(ref != nullptr);

    std::vector<T> x(d), yref(d);
    std::vector<T> xinp(d);  // inplace test
189
    RandomVec<T>(d, x.data());
190 191 192 193 194 195 196 197 198
    std::copy(x.begin(), x.end(), xinp.begin());

    const T* x_data = x.data();
    T* yref_data = yref.data();
    T* xinp_data = xinp.data();
    // test refer code inplace
    ref(x_data, yref_data, d);
    ref(xinp_data, xinp_data, d);
    ExpectEQ<T>(xinp_data, yref_data, d);
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
    auto verifier = [](const typename KernelTuple::func_type tgt,
                       const std::vector<T>& x, const std::vector<T>& yref) {
      EXPECT_TRUE(tgt != nullptr);
      EXPECT_EQ(yref.size(), x.size());
      const T* x_data = x.data();
      const T* yref_data = yref.data();
      const int d = yref.size();
      std::vector<T> ytgt(d);
      T* ytgt_data = ytgt.data();
      // test normal
      tgt(x_data, ytgt_data, d);
      ExpectEQ<T>(ytgt_data, yref_data, d);
      // test inplace x
      std::copy(x.begin(), x.end(), ytgt.begin());
      tgt(ytgt_data, ytgt_data, d);
      ExpectEQ<T>(ytgt_data, yref_data, d);
    };
    TestAllImpls<KernelTuple, PlaceType>(d, verifier, x, yref);
  }
}

template <typename KernelTuple, typename PlaceType>
void TestKernelXRN() {
  using T = typename KernelTuple::data_type;
  VLOG(10) << "Test JITKernel: " << jit::to_string(KernelTuple::kernel_type);
  auto last_acc = FLAGS_acc;
  FLAGS_acc = 1e-4;
  for (int d : TestSizes()) {
227
    auto ref = jit::GetReferFunc<KernelTuple>();
228 229 230 231 232
    EXPECT_TRUE(ref != nullptr);
    std::vector<T> x(d);
    RandomVec<T>(d, x.data());
    T ref_res;
    ref(x.data(), &ref_res, d);
233

234 235 236 237 238 239 240 241
    auto verifier = [](const typename KernelTuple::func_type tgt,
                       const std::vector<T>& x, const T ref_res) {
      EXPECT_TRUE(tgt != nullptr);
      T tgt_res;
      tgt(x.data(), &tgt_res, x.size());
      ExpectEQ<T>(&tgt_res, &ref_res, 1);
    };
    TestAllImpls<KernelTuple, PlaceType>(d, verifier, x, ref_res);
242
  }
243
  FLAGS_acc = last_acc;
244 245
}

246 247 248 249
template <typename KernelTuple, typename PlaceType>
void TestKernelLSTM() {
  using T = typename KernelTuple::data_type;
  VLOG(10) << "Test JITKernel: " << jit::to_string(KernelTuple::kernel_type);
T
tensor-tang 已提交
250
  std::vector<std::string> all_acts = {"sigmoid", "tanh", "relu", "identity"};
T
tensor-tang 已提交
251 252 253
  auto test_sizes = TestSizes();
  test_sizes.erase(std::remove(test_sizes.begin(), test_sizes.end(), 1000));
  for (int d : test_sizes) {
T
tensor-tang 已提交
254 255 256 257 258 259 260
    for (bool use_peephole : {true, false}) {
      for (auto& act_gate : all_acts) {
        for (auto& act_cand : all_acts) {
          for (auto& act_cell : all_acts) {
            const jit::lstm_attr_t attr(
                d, jit::to_kerneltype(act_gate), jit::to_kerneltype(act_cand),
                jit::to_kerneltype(act_cell), use_peephole);
261
            auto ref = jit::GetReferFunc<KernelTuple>();
T
tensor-tang 已提交
262 263 264
            EXPECT_TRUE(ref != nullptr);
            std::vector<T> xsrc(4 * d), wp(3 * d), ct_1(d);
            std::vector<T> ct_ref(d), ht_ref(d), checked(2 * d);
265
            RandomVec<T>(4 * d, xsrc.data());
266 267
            RandomVec<T>(3 * d, wp.data(), -1.f, 1.f);
            RandomVec<T>(d, ct_1.data(), -1.f, 1.f);
T
tensor-tang 已提交
268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286
            // x could be changed after compute, so copy to save src
            std::vector<T> x(xsrc.size());
            std::copy(xsrc.begin(), xsrc.end(), x.begin());
            const T* ct_1_data = ct_1.data();
            const T* wp_data = wp.data();
            T* x_data = x.data();
            T* checked_data = checked.data();
            T* ct_ref_data = ct_ref.data();
            T* ht_ref_data = ht_ref.data();
            jit::lstm_t step;
            step.gates = x_data;
            step.ct_1 = ct_1_data;
            step.ct = ct_ref_data;
            step.ht = ht_ref_data;
            if (use_peephole) {
              step.wp = wp_data;
              step.checked = checked_data;
            }
            ref(&step, &attr);
T
tensor-tang 已提交
287
            VLOG(10) << attr;
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

            auto verifier = [](
                const typename KernelTuple::func_type tgt,
                const std::vector<T>& xsrc, const std::vector<T>& wp,
                const std::vector<T>& ct_1, const std::vector<T>& ct_ref,
                const std::vector<T>& ht_ref,
                const typename KernelTuple::attr_type& attr) {
              EXPECT_TRUE(tgt != nullptr);
              EXPECT_EQ(ct_ref.size(), ht_ref.size());
              EXPECT_EQ(ct_1.size(), ht_ref.size());
              EXPECT_EQ(xsrc.size(), 4 * ht_ref.size());
              EXPECT_EQ(wp.size(), 3 * ht_ref.size());

              // x could be changed after compute, so copy to save src
              int d = ht_ref.size();
              std::vector<T> x(xsrc.size()), ct(ct_ref.size()),
                  ht(ht_ref.size());
              std::vector<T> checked(2 * d);
              std::copy(xsrc.begin(), xsrc.end(), x.begin());

              const T* ct_1_data = ct_1.data();
              const T* wp_data = wp.data();
              const T* ct_ref_data = ct_ref.data();
              const T* ht_ref_data = ht_ref.data();
              T* x_data = x.data();
              T* ct_data = ct.data();
              T* ht_data = ht.data();
              T* checked_data = checked.data();

              jit::lstm_t step;
              step.gates = x_data;
              step.ct_1 = ct_1_data;
              step.ct = ct_data;
              step.ht = ht_data;
              if (attr.use_peephole) {
                step.wp = wp_data;
                step.checked = checked_data;
              }

              tgt(&step, &attr);
              ExpectEQ<T>(ct_data, ct_ref_data, d);
              ExpectEQ<T>(ht_data, ht_ref_data, d);
            };
            TestAllImpls<KernelTuple, PlaceType>(attr, verifier, xsrc, wp, ct_1,
                                                 ct_ref, ht_ref, attr);
T
tensor-tang 已提交
333 334 335 336 337 338 339
          }
        }
      }
    }
  }
}

340 341 342 343
template <typename KernelTuple, typename PlaceType>
void TestKernelGRU() {
  using T = typename KernelTuple::data_type;
  VLOG(10) << "Test JITKernel: " << jit::to_string(KernelTuple::kernel_type);
344
  std::vector<std::string> all_acts = {"sigmoid", "tanh", "relu", "identity"};
T
tensor-tang 已提交
345 346 347
  auto test_sizes = TestSizes();
  test_sizes.erase(std::remove(test_sizes.begin(), test_sizes.end(), 1000));
  for (int d : test_sizes) {
348 349 350 351
    for (auto& act_gate : all_acts) {
      for (auto& act_cand : all_acts) {
        const jit::gru_attr_t attr(d, jit::to_kerneltype(act_gate),
                                   jit::to_kerneltype(act_cand));
352
        auto ref = jit::GetReferFunc<KernelTuple>();
353 354
        EXPECT_TRUE(ref != nullptr);
        std::vector<T> xsrc(3 * d), ht_1(d), ht_ref(d);
355 356
        RandomVec<T>(3 * d, xsrc.data());
        RandomVec<T>(d, ht_1.data());
357 358 359 360 361 362 363 364 365 366 367
        // x could be changed after compute, so copy to save src
        std::vector<T> x(xsrc.size());
        std::copy(xsrc.begin(), xsrc.end(), x.begin());
        const T* ht_1_data = ht_1.data();
        T* x_data = x.data();
        T* ht_ref_data = ht_ref.data();
        jit::gru_t step;
        step.gates = x_data;
        step.ht_1 = ht_1_data;
        step.ht = ht_ref_data;
        ref(&step, &attr);
T
tensor-tang 已提交
368
        VLOG(10) << attr;
369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394
        auto verifier = [](const typename KernelTuple::func_type tgt,
                           const std::vector<T>& xsrc,
                           const std::vector<T>& ht_1,
                           const std::vector<T>& ht_ref,
                           const typename KernelTuple::attr_type& attr) {
          EXPECT_TRUE(tgt != nullptr);
          EXPECT_EQ(ht_1.size(), ht_ref.size());
          EXPECT_EQ(xsrc.size(), 3 * ht_ref.size());

          // x could be changed after compute, so copy to save src
          int d = ht_ref.size();
          std::vector<T> x(xsrc.size()), ht(ht_ref.size());
          std::copy(xsrc.begin(), xsrc.end(), x.begin());
          const T* ht_1_data = ht_1.data();
          const T* ht_ref_data = ht_ref.data();
          T* x_data = x.data();
          T* ht_data = ht.data();
          jit::gru_t step;
          step.gates = x_data;
          step.ht_1 = ht_1_data;
          step.ht = ht_data;
          tgt(&step, &attr);
          ExpectEQ<T>(ht_data, ht_ref_data, d);
        };
        TestAllImpls<KernelTuple, PlaceType>(attr, verifier, xsrc, ht_1, ht_ref,
                                             attr);
395 396 397 398 399
      }
    }
  }
}

400 401 402 403 404
template <typename KernelTuple, typename PlaceType>
void TestKernelNCHW16CMulNC() {
  using T = typename KernelTuple::data_type;
  VLOG(10) << "Test JITKernel: " << jit::to_string(KernelTuple::kernel_type);
  const int n = 3, c = 16 * 4, h = 10, w = 10;
405
  auto ref = jit::GetReferFunc<KernelTuple>();
406 407 408 409 410 411 412 413 414 415 416 417 418 419 420
  EXPECT_TRUE(ref != nullptr);
  int sz = n * c * h * w;
  std::vector<T> x(sz), y(n * c), zref(sz);
  std::vector<T> ztgt(sz), zjit(sz);
  RandomVec<T>(sz, x.data());
  RandomVec<T>(n * c, y.data());

  const T* x_data = x.data();
  const T* y_data = y.data();
  T* zref_data = zref.data();
  T* ztgt_data = ztgt.data();
  T* zjit_data = zjit.data();
  constexpr int simd_width = ZMM_FLOAT_BLOCK;
  int C = c / simd_width;
  auto tgt = jit::KernelFuncs<KernelTuple, PlaceType>::Cache().At(0);
421 422 423
  auto funcs = jit::GetAllCandidateFuncs<KernelTuple, PlaceType>(0);
  EXPECT_GT(funcs.size(), 0UL);
  auto jitcode = funcs[0];
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 453 454 455 456 457 458 459 460 461 462 463 464 465
  EXPECT_TRUE(tgt != nullptr);

  if (std::is_same<T, float>::value &&
      paddle::platform::MayIUse(paddle::platform::avx512f)) {
    EXPECT_TRUE(jitcode != nullptr);
  }
  for (int ni = 0; ni < n; ni++) {
    for (int ci = 0; ci < C; ci++) {
      auto ptr_x =
          x_data + ni * C * h * w * simd_width + ci * h * w * simd_width;
      auto ptr_y = y_data + ni * C * simd_width + ci * simd_width;
      auto ptr_zref =
          zref_data + ni * C * h * w * simd_width + ci * h * w * simd_width;
      auto ptr_ztgt =
          ztgt_data + ni * C * h * w * simd_width + ci * h * w * simd_width;

      ref(ptr_x, ptr_y, ptr_zref, h, w);
      tgt(ptr_x, ptr_y, ptr_ztgt, h, w);

      if (jitcode) {
        auto ptr_zjit =
            zjit_data + ni * C * h * w * simd_width + ci * h * w * simd_width;
        jitcode(ptr_x, ptr_y, ptr_zjit, h, w);
      }
    }
  }
  ExpectEQ<T>(ztgt_data, zref_data, sz);
  if (jitcode) {
    ExpectEQ<T>(zjit_data, zref_data, sz);
  }
}

template <typename KernelTuple, typename PlaceType>
void TestKernelLayerNorm() {
  using T = typename KernelTuple::data_type;
  VLOG(10) << "Test JITKernel: " << jit::to_string(KernelTuple::kernel_type);
  const T epsilon = 9.99999975e-06;
  for (int n : {1, 2, 10}) {
    for (int x_dim_0 : {1, 9, 17, 50}) {
      int left = n * x_dim_0;
      for (int x_dim_1 : TestSizes()) {
        int right = x_dim_1;
466
        auto ref = jit::GetReferFunc<KernelTuple>();
467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538
        EXPECT_TRUE(ref != nullptr);
        int sz = left * right;
        std::vector<T> x(sz), mean(left), var(left), scale(right), bias(right),
            outref(sz);
        RandomVec<T>(sz, x.data());
        RandomVec<T>(left, mean.data());
        RandomVec<T>(left, var.data());
        RandomVec<T>(right, scale.data());
        RandomVec<T>(right, bias.data());

        const T* scale_data = scale.data();
        const T* bias_data = bias.data();
        T* x_data = x.data();
        T* mean_data = mean.data();
        T* var_data = var.data();
        T* outref_data = outref.data();

        ref(x_data, outref_data, mean_data, var_data, scale_data, bias_data,
            left, epsilon, right);

        auto verifier = [](
            const typename KernelTuple::func_type tgt, const std::vector<T>& x_,
            const std::vector<T>& outref_, const std::vector<T>& mean_,
            const std::vector<T>& var_, const std::vector<T>& scale,
            const std::vector<T>& bias, const int& left, const float& epsilon,
            const typename KernelTuple::attr_type& right) {
          EXPECT_TRUE(tgt != nullptr);
          std::vector<T> outtgt(outref_.size());
          std::vector<T> x(x_.size());
          std::vector<T> mean(mean_.size());
          std::vector<T> var(var_.size());
          std::vector<T> outref(outref_.size());
          std::copy(x_.begin(), x_.end(), x.begin());
          std::copy(mean_.begin(), mean_.end(), mean.begin());
          std::copy(var_.begin(), var_.end(), var.begin());
          std::copy(outref_.begin(), outref_.end(), outref.begin());

          EXPECT_EQ(x.size(), static_cast<size_t>(left * right));
          EXPECT_EQ(outref.size(), static_cast<size_t>(left * right));
          EXPECT_EQ(mean.size(), static_cast<size_t>(left));
          EXPECT_EQ(var.size(), static_cast<size_t>(left));
          EXPECT_EQ(scale.size(), static_cast<size_t>(right));
          EXPECT_EQ(bias.size(), static_cast<size_t>(right));

          const T* scale_data = scale.data();
          const T* bias_data = bias.data();
          T* x_data = x.data();
          T* mean_data = mean.data();
          T* var_data = var.data();
          T* outref_data = outref.data();
          T* outtgt_data = outtgt.data();
          tgt(x_data, outtgt_data, mean_data, var_data, scale_data, bias_data,
              left, epsilon, right);
          ExpectEQ<T>(outtgt_data, outref_data, left * right);
        };
        TestAllImpls<KernelTuple, PlaceType>(right, verifier, x, outref, mean,
                                             var, scale, bias, left, epsilon,
                                             right);
      }
    }
  }
}

template <typename KernelTuple, typename PlaceType>
void TestKernelCRFDecoding() {
  using T = typename KernelTuple::data_type;
  VLOG(10) << "Test JITKernel: " << jit::to_string(KernelTuple::kernel_type);
  constexpr int state_trans_base_idx = 2;
  auto test_sizes = TestSizes();
  test_sizes.erase(std::remove(test_sizes.begin(), test_sizes.end(), 2000));
  for (int seq_len : {1, 11, 17, 50}) {
    for (int tag_num : test_sizes) {
539
      auto ref = jit::GetReferFunc<KernelTuple>();
540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580
      EXPECT_TRUE(ref != nullptr);
      int x_sz = seq_len * tag_num;
      int w_sz = (tag_num + state_trans_base_idx) * tag_num;
      std::vector<T> x(x_sz), w(w_sz), alpharef(x_sz);
      std::vector<int> trackref(x_sz);
      RandomVec<T>(x_sz, x.data());
      RandomVec<T>(w_sz, w.data());

      ref(seq_len, (const T*)x.data(), (const T*)w.data(), alpharef.data(),
          trackref.data(), tag_num);

      auto verifier = [](
          const typename KernelTuple::func_type tgt, const int& seq_len,
          const std::vector<T>& x, const std::vector<T>& w,
          const std::vector<T>& alpharef, const std::vector<int>& trackref,
          const typename KernelTuple::attr_type& tag_num) {
        constexpr int state_trans_base_idx = 2;
        EXPECT_TRUE(tgt != nullptr);
        EXPECT_EQ(x.size(), static_cast<size_t>(seq_len * tag_num));
        EXPECT_EQ(w.size(), static_cast<size_t>(
                                (tag_num + state_trans_base_idx) * tag_num));
        EXPECT_EQ(alpharef.size(), static_cast<size_t>(seq_len * tag_num));
        EXPECT_EQ(trackref.size(), static_cast<size_t>(seq_len * tag_num));
        std::vector<T> alphatgt(alpharef.size());
        std::vector<int> tracktgt(trackref.size());
        memcpy(tracktgt.data(), trackref.data(), tag_num * sizeof(int));
        tgt(seq_len, (const T*)x.data(), (const T*)w.data(), alphatgt.data(),
            tracktgt.data(), tag_num);
        ExpectEQ<T>(alpharef.data(), alphatgt.data(), seq_len * tag_num);
        ExpectEQ<int>(trackref.data(), tracktgt.data(), seq_len * tag_num);
      };
      TestAllImpls<KernelTuple, PlaceType>(tag_num, verifier, seq_len, x, w,
                                           alpharef, trackref, tag_num);
    }
  }
}

template <typename KernelTuple, typename PlaceType>
void TestKernelSeqPool() {
  using T = typename KernelTuple::data_type;
  VLOG(10) << "Test JITKernel: " << jit::to_string(KernelTuple::kernel_type);
581 582
  std::vector<jit::SeqPoolType> pool_types = {
      jit::SeqPoolType::kSum, jit::SeqPoolType::kAvg, jit::SeqPoolType::kSqrt};
T
tensor-tang 已提交
583 584
  auto test_sizes = TestSizes();
  test_sizes.erase(std::remove(test_sizes.begin(), test_sizes.end(), 1000));
585
  for (auto type : pool_types) {
T
tensor-tang 已提交
586
    for (int w : test_sizes) {
T
tensor-tang 已提交
587
      jit::seq_pool_attr_t attr(w, type);
T
tensor-tang 已提交
588
      for (int h : test_sizes) {
T
tensor-tang 已提交
589
        attr.h = h;
590
        auto ref = jit::GetReferFunc<KernelTuple>();
591 592
        EXPECT_TRUE(ref != nullptr);
        std::vector<T> x(h * w), yref(w);
593
        RandomVec<T>(h * w, x.data());
594 595 596 597
        const T* x_data = x.data();
        T* yref_data = yref.data();
        ref(x_data, yref_data, &attr);
        VLOG(10) << attr;
598 599 600 601 602 603 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 630 631 632
        auto verifier = [](const typename KernelTuple::func_type tgt,
                           const std::vector<T>& x, const std::vector<T>& yref,
                           const typename KernelTuple::attr_type& attr) {
          EXPECT_TRUE(tgt != nullptr);
          EXPECT_EQ(x.size() % yref.size(), static_cast<size_t>(0));
          int w = yref.size();
          std::vector<T> y(w);
          const T* x_data = x.data();
          const T* yref_data = yref.data();
          T* y_data = y.data();
          tgt(x_data, y_data, &attr);
          ExpectEQ<T>(y_data, yref_data, w);
        };
        TestAllImpls<KernelTuple, PlaceType>(attr, verifier, x, yref, attr);
      }
    }
  }
}

template <typename KernelTuple, typename PlaceType>
void TestKernelEmbSeqPool() {
  using T = typename KernelTuple::data_type;
  VLOG(10) << "Test JITKernel: " << jit::to_string(KernelTuple::kernel_type);
  int64_t tbl_h = 1e4;
  std::vector<jit::SeqPoolType> pool_types = {
      jit::SeqPoolType::kSum};  // only support sum yet
  auto test_sizes = TestSizes();
  test_sizes.erase(std::remove(test_sizes.begin(), test_sizes.end(), 1000));
  for (int tbl_w : test_sizes) {
    std::vector<T> table(tbl_h * tbl_w);
    RandomVec<T>(tbl_h * tbl_w, table.data());
    const T* table_data = table.data();
    for (auto type : pool_types) {
      for (int idx_w : {1, 2, 10, 16}) {
        for (int idx_h : {1, 2, 9, 13, 16}) {
633
          auto ref = jit::GetReferFunc<KernelTuple>();
634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668
          EXPECT_TRUE(ref != nullptr);
          std::vector<int64_t> idx(idx_h * idx_w);
          RandomVec<int64_t>(idx_h * idx_w, idx.data(), 0, tbl_h - 1);
          int64_t out_w = tbl_w * idx_w;
          std::vector<T> oref(out_w);
          const int64_t* idx_data = idx.data();
          T* o_data = oref.data();
          jit::emb_seq_pool_attr_t attr(tbl_h, tbl_w, idx_h, idx_w, out_w,
                                        type);
          ref(table_data, idx_data, o_data, &attr);

          auto verifier = [](const typename KernelTuple::func_type tgt,
                             const std::vector<T>& table,
                             const std::vector<int64_t>& idx,
                             const std::vector<T>& oref,
                             const typename KernelTuple::attr_type& attr) {
            EXPECT_TRUE(tgt != nullptr);
            EXPECT_EQ(table.size(), static_cast<size_t>(attr.table_height *
                                                        attr.table_width));
            EXPECT_EQ(idx.size(), static_cast<size_t>(attr.index_height *
                                                      attr.index_width));
            EXPECT_EQ(oref.size(),
                      static_cast<size_t>(attr.table_width * attr.index_width));
            const T* table_data = table.data();
            const int64_t* idx_data = idx.data();
            const T* oref_data = oref.data();
            int o_w = oref.size();
            std::vector<T> out(o_w);
            T* o_data = out.data();
            tgt(table_data, idx_data, o_data, &attr);
            ExpectEQ<T>(o_data, oref_data, o_w);
          };
          TestAllImpls<KernelTuple, PlaceType>(attr, verifier, table, idx, oref,
                                               attr);
        }
669 670 671 672 673
      }
    }
  }
}

674 675 676 677
template <typename KernelTuple, typename PlaceType>
void TestKernelMatMul() {
  using T = typename KernelTuple::data_type;
  VLOG(10) << "Test JITKernel: " << jit::to_string(KernelTuple::kernel_type);
678
  auto last_acc = FLAGS_acc;
T
tensor-tang 已提交
679 680
  // export MKL_CBWR=AVX would make MKL force to use AVX
  // export KMP_DETERMINISTIC_REDUCTION=yes would make the result deterministic
681
  FLAGS_acc = 1e-3;
T
tensor-tang 已提交
682 683 684
  for (int m : {1, 2, 3, 4}) {
    for (int n : {1, 2, 3, 4}) {
      for (int k : TestSizes()) {
685
        auto ref = jit::GetReferFunc<KernelTuple>();
T
tensor-tang 已提交
686 687
        EXPECT_TRUE(ref != nullptr);
        std::vector<T> a(m * k), b(k * n), c(m * n);
688 689
        RandomVec<T>(m * k, a.data());
        RandomVec<T>(k * n, b.data());
T
tensor-tang 已提交
690 691 692
        const T* a_data = a.data();
        const T* b_data = b.data();
        T* c_data = c.data();
693 694
        const jit::matmul_attr_t attr{m, n, k};
        ref(a_data, b_data, c_data, &attr);
695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711
        auto verifier = [](const typename KernelTuple::func_type tgt,
                           const std::vector<T>& a, const std::vector<T>& b,
                           const std::vector<T>& cref,
                           const typename KernelTuple::attr_type& attr) {
          EXPECT_TRUE(tgt != nullptr);
          EXPECT_EQ(a.size(), static_cast<size_t>(attr.m * attr.k));
          EXPECT_EQ(b.size(), static_cast<size_t>(attr.k * attr.n));
          EXPECT_EQ(cref.size(), static_cast<size_t>(attr.m * attr.n));
          std::vector<T> c(cref.size());
          const T* a_data = a.data();
          const T* b_data = b.data();
          const T* cref_data = cref.data();
          T* c_data = c.data();
          tgt(a_data, b_data, c_data, &attr);
          ExpectEQ<T>(c_data, cref_data, attr.m * attr.n);
        };
        TestAllImpls<KernelTuple, PlaceType>(attr, verifier, a, b, c, attr);
T
tensor-tang 已提交
712 713 714
      }
    }
  }
715
  FLAGS_acc = last_acc;
T
tensor-tang 已提交
716 717
}

718 719 720 721
template <typename KernelTuple, typename PlaceType>
void TestKernelSoftmax() {
  using T = typename KernelTuple::data_type;
  VLOG(10) << "Test JITKernel: " << jit::to_string(KernelTuple::kernel_type);
722 723
  for (int bs : {1, 2, 10}) {
    for (int n : TestSizes()) {
D
dengkaipeng 已提交
724
      for (int m : {1, 2, 3}) {  // remain
725 726 727 728 729 730 731
        if (m > n || n % m != 0) {
          continue;
        }
        auto ref = jit::GetReferFunc<KernelTuple>();
        EXPECT_TRUE(ref != nullptr);
        std::vector<T> x(bs * n), y(bs * n);
        RandomVec<T>(bs * n, x.data());
732
        const T* x_data = x.data();
733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761
        T* y_data = y.data();

        std::vector<T> xinp(x.size());  // inplace test
        std::copy(x.begin(), x.end(), xinp.begin());
        ref(x_data, y_data, n, bs, m);
        T* xinp_data = xinp.data();
        ref(xinp_data, xinp_data, n, bs, m);
        ExpectEQ<T>(xinp_data, y_data, n * bs);

        auto verifier = [](const typename KernelTuple::func_type tgt,
                           const std::vector<T>& x, const std::vector<T>& yref,
                           int n, int bs, int m) {
          EXPECT_TRUE(tgt != nullptr);
          EXPECT_EQ(yref.size(), x.size());
          EXPECT_EQ(x.size(), static_cast<size_t>(n * bs));
          const T* x_data = x.data();
          const T* yref_data = yref.data();
          std::vector<T> ytgt(n * bs);
          T* ytgt_data = ytgt.data();
          // test normal
          tgt(x_data, ytgt_data, n, bs, m);
          ExpectEQ<T>(ytgt_data, yref_data, n * bs);
          // test inplace x
          std::copy(x.begin(), x.end(), ytgt.begin());
          tgt(ytgt_data, ytgt_data, n, bs, m);
          ExpectEQ<T>(ytgt_data, yref_data, n * bs);
        };
        TestAllImpls<KernelTuple, PlaceType>(n, verifier, x, y, n, bs, m);
      }
762 763 764 765
    }
  }
}

D
dengkaipeng 已提交
766 767 768 769 770
template <typename KernelTuple, typename PlaceType>
void TestKernelStrideASum() {
  using T = typename KernelTuple::data_type;
  VLOG(10) << "Test JITKernel: " << jit::to_string(KernelTuple::kernel_type);
  for (int d : TestSizes()) {
D
dengkaipeng 已提交
771
    for (int m : {1, 2, 3}) {  // stride
D
dengkaipeng 已提交
772 773 774 775 776 777 778 779 780 781 782
      if (m > d || d % m != 0) {
        continue;
      }
      auto ref = jit::GetReferFunc<KernelTuple>();
      EXPECT_TRUE(ref != nullptr);
      std::vector<T> x(d);
      RandomVec<T>(d, x.data());
      T ref_res;
      ref(x.data(), &ref_res, d, m);

      auto verifier = [](const typename KernelTuple::func_type tgt,
D
dengkaipeng 已提交
783
                         const std::vector<T>& x, const T ref_res,
D
dengkaipeng 已提交
784 785 786 787 788 789 790 791 792 793 794 795 796 797 798
                         const int m) {
        EXPECT_TRUE(tgt != nullptr);
        T tgt_res;
        tgt(x.data(), &tgt_res, x.size(), m);
        ExpectEQ<T>(&tgt_res, &ref_res, 1);
      };
      TestAllImpls<KernelTuple, PlaceType>(d, verifier, x, ref_res, m);
    }
  }
}

template <typename KernelTuple, typename PlaceType>
void TestKernelStrideScal() {
  using T = typename KernelTuple::data_type;
  VLOG(10) << "Test JITKernel: " << jit::to_string(KernelTuple::kernel_type);
D
dengkaipeng 已提交
799
  for (int d : TestSizes()) {
D
dengkaipeng 已提交
800
    for (int m : {1, 2, 3}) {  // stride
D
dengkaipeng 已提交
801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843
      if (m > d || d % m != 0) {
        continue;
      }
      auto ref = jit::GetReferFunc<KernelTuple>();
      EXPECT_TRUE(ref != nullptr);

      const T a = static_cast<T>(3);
      std::vector<T> x(d), yref(d);
      std::vector<T> xinp(d);  // inplace test
      RandomVec<T>(d, x.data());
      std::copy(x.begin(), x.end(), xinp.begin());

      const T* x_data = x.data();
      T* yref_data = yref.data();
      T* xinp_data = xinp.data();
      // test refer code inplace
      ref(&a, x_data, yref_data, d, m);
      ref(&a, xinp_data, xinp_data, d, m);
      ExpectEQ<T>(xinp_data, yref_data, d);

      auto verifier = [](const typename KernelTuple::func_type tgt, const T a,
                         const std::vector<T>& x, const std::vector<T>& yref,
                         const int m) {
        EXPECT_TRUE(tgt != nullptr);
        EXPECT_EQ(yref.size(), x.size());
        const T* x_data = x.data();
        const T* yref_data = yref.data();
        const int d = yref.size();
        std::vector<T> ytgt(d);
        T* ytgt_data = ytgt.data();
        // test normal
        tgt(&a, x_data, ytgt_data, d, m);
        ExpectEQ<T>(ytgt_data, yref_data, d);
        // test inplace x
        std::copy(x.begin(), x.end(), ytgt.begin());
        tgt(&a, ytgt_data, ytgt_data, d, m);
        ExpectEQ<T>(ytgt_data, yref_data, d);
      };
      TestAllImpls<KernelTuple, PlaceType>(d, verifier, a, x, yref, m);
    }
  }
}

844 845 846 847
template <typename KernelTuple, typename PlaceType>
void TestKernelSgd() {
  using T = typename KernelTuple::data_type;
  VLOG(10) << "Test JITKernel: " << jit::to_string(KernelTuple::kernel_type);
848 849 850
  const T lr = 0.1;
  auto UnDuplicatedRandomVec = [](int n, const int64_t lower,
                                  const int64_t upper) -> std::vector<int64_t> {
G
GaoWei8 已提交
851 852 853 854 855 856 857 858 859
    PADDLE_ENFORCE_LE(static_cast<size_t>(upper - lower), n - 1,
                      paddle::platform::errors::InvalidArgument(
                          "The range of Sgd (upper - lower) should be lower "
                          "than n-1 (Sgd size -1). But the upper - lower is %d "
                          "and n-1 is %d.",
                          static_cast<size_t>(upper - lower), n - 1));
    PADDLE_ENFORCE_GT(
        n, 0, paddle::platform::errors::InvalidArgument(
                  "The Sgd size should be larger than 0. But the n is %d.", n));
860 861 862 863 864 865 866 867 868 869 870 871
    std::vector<int64_t> all, out;
    for (int i = 0; i < n; ++i) {
      all.push_back(i);
    }
    std::random_shuffle(all.begin(), all.end());
    out.insert(out.begin(), all.begin(), all.begin() + n);
    return out;
  };
  for (int param_h : {1, 10}) {
    for (int grad_w : TestSizes()) {
      std::vector<T> param(param_h * grad_w);
      std::vector<T> param_out(param_h * grad_w);
872
      RandomVec<T>(param_h * grad_w, param.data());
873 874 875 876 877 878
      const T* param_data = param.data();
      T* out_data = param_out.data();
      for (int rows_size = 1; rows_size <= param_h; ++rows_size) {
        std::vector<T> grad(rows_size * grad_w);
        std::vector<int64_t> rows =
            UnDuplicatedRandomVec(rows_size, 0, rows_size - 1);
879
        RandomVec<T>(rows_size * grad_w, grad.data());
880 881
        const int64_t* rows_data = rows.data();
        const T* grad_data = grad.data();
882
        auto ref = jit::GetReferFunc<KernelTuple>();
883 884 885 886 887 888 889 890 891 892 893 894 895 896 897
        EXPECT_TRUE(ref != nullptr);
        jit::sgd_attr_t attr(param_h, grad_w, rows_size, grad_w, rows_size);
        ref(&lr, param_data, grad_data, rows_data, out_data, &attr);

        // inplace test
        std::vector<T> inp(param.size());
        std::copy(param.begin(), param.end(), inp.begin());
        T* inp_data = inp.data();
        ref(&lr, inp_data, grad_data, rows_data, inp_data, &attr);
        // only the selected rows should be equal
        for (int i = 0; i < rows_size; ++i) {
          ExpectEQ<T>(inp_data + rows[i] * grad_w, out_data + rows[i] * grad_w,
                      grad_w);
        }

898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922
        auto verifier = [](
            const typename KernelTuple::func_type tgt, const T lr,
            const std::vector<T>& param, const std::vector<T>& grad,
            const std::vector<int64_t>& rows, const std::vector<T>& oref,
            const typename KernelTuple::attr_type& attr) {
          EXPECT_TRUE(tgt != nullptr);
          EXPECT_EQ(param.size(),
                    static_cast<size_t>(attr.param_height * attr.param_width));
          EXPECT_EQ(grad.size(),
                    static_cast<size_t>(attr.grad_height * attr.grad_width));
          EXPECT_EQ(rows.size(), static_cast<size_t>(attr.selected_rows_size));
          EXPECT_EQ(param.size(), oref.size());
          const T* param_data = param.data();
          const T* grad_data = grad.data();
          const int64_t* rows_data = rows.data();
          const T* oref_data = oref.data();

          std::vector<T> out(oref.size());
          T* o_data = out.data();
          tgt(&lr, param_data, grad_data, rows_data, o_data, &attr);
          // only the selected rows should be equal
          for (size_t i = 0; i < rows.size(); ++i) {
            ExpectEQ<T>(o_data + rows[i] * attr.grad_width,
                        oref_data + rows[i] * attr.grad_width, attr.grad_width);
          }
923

924 925 926 927 928 929 930 931 932 933
          // inplace
          std::copy(param.begin(), param.end(), out.begin());
          tgt(&lr, o_data, grad_data, rows_data, o_data, &attr);
          for (size_t i = 0; i < rows.size(); ++i) {
            ExpectEQ<T>(o_data + rows[i] * attr.grad_width,
                        oref_data + rows[i] * attr.grad_width, attr.grad_width);
          }
        };
        TestAllImpls<KernelTuple, PlaceType>(attr, verifier, lr, param, grad,
                                             rows, param_out, attr);
934 935 936 937 938
      }
    }
  }
}

939 940 941 942
template <typename KernelTuple, typename PlaceType>
void TestKernelVBroadcast() {
  using T = typename KernelTuple::data_type;
  VLOG(10) << "Test JITKernel: " << jit::to_string(KernelTuple::kernel_type);
943 944 945 946 947
  for (int w : TestSizes()) {
    std::vector<T> x(w);
    RandomVec<T>(w, x.data());
    const T* x_data = x.data();
    for (int64_t h : {1, 2, 6}) {
948
      auto ref = jit::GetReferFunc<KernelTuple>();
949 950 951 952 953
      EXPECT_TRUE(ref != nullptr);
      std::vector<T> y(w * h);
      T* y_data = y.data();
      ref(x_data, y_data, h, w);

954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969
      auto verifier = [](const typename KernelTuple::func_type tgt,
                         const std::vector<T>& x, const std::vector<T>& yref,
                         const int64_t& h,
                         const typename KernelTuple::attr_type& attr) {
        EXPECT_TRUE(tgt != nullptr);
        EXPECT_EQ(x.size(), static_cast<size_t>(attr));
        EXPECT_EQ(yref.size(), x.size() * h);
        std::vector<T> y(yref.size());
        const T* x_data = x.data();
        const T* yref_data = yref.data();
        T* y_data = y.data();
        tgt(x_data, y_data, h, attr);
        ExpectEQ<T>(y_data, yref_data, yref.size());
      };
      TestAllImpls<KernelTuple, PlaceType>(static_cast<int64_t>(w), verifier, x,
                                           y, h, static_cast<int64_t>(w));
970 971 972 973
    }
  }
}

974 975 976
// test pool
TEST(JITKernel_pool, jitcreator) {
  const auto& jitcreators = jit::JitCodeCreatorPool::Instance().AllCreators();
977 978 979
#if defined(_WIN32) || defined(__APPLE__) || defined(__OSX__)
  EXPECT_EQ(jitcreators.size(), 0UL);
#else
980
  EXPECT_EQ(jitcreators.size(), 25UL);
981
#endif
982 983 984 985 986 987 988
}

TEST(JITKernel_pool, jitpool) {
  // jitpool is related with attr
  const auto& kers = jit::JitCodePool<jit::kVAdd>().Instance().AllKernels();
  EXPECT_EQ(kers.size(), 0UL);
  jit::GetAllCandidateKernels<jit::VAddTuple<float>, CPUPlace>(3);
989 990 991 992
// after call GetAllCandidateKernels, it will create jitcode Automatically
#if defined(_WIN32) || defined(__APPLE__) || defined(__OSX__)
  EXPECT_EQ(kers.size(), 0UL);
#else
993
  EXPECT_EQ(kers.size(), 1UL);
994
#endif
995 996 997 998
}

TEST(JITKernel_pool, more) {
  const auto& kers = jit::KernelPool::Instance().AllKernels();
T
tensor-tang 已提交
999 1000 1001 1002
  size_t target_num = 8;

#ifdef __AVX__
  target_num += 2;
1003
#endif
T
tensor-tang 已提交
1004 1005 1006

#ifdef PADDLE_WITH_MKLML
  target_num += 12;
1007
#endif
T
tensor-tang 已提交
1008 1009

  EXPECT_EQ(kers.size(), target_num);
1010 1011 1012 1013
}

TEST(JITKernel_pool, refer) {
  const auto& kers = jit::ReferKernelPool::Instance().AllKernels();
D
dengkaipeng 已提交
1014
  EXPECT_EQ(kers.size(), 31UL);
1015 1016 1017 1018 1019 1020 1021 1022 1023
}

// test helper
TEST(JITKernel_helper, GetAllCandidateKernels) {
  auto fp_kers =
      jit::GetAllCandidateKernels<jit::VExpTuple<float>, CPUPlace>(10);
#if defined(_WIN32) || defined(__APPLE__) || defined(__OSX__)
  EXPECT_GE(fp_kers.size(), 1UL);  // refer
#else
1024
#ifdef PADDLE_WITH_MKLML
1025
  EXPECT_GE(fp_kers.size(), 3UL);  // jitcode, mkl, refer
1026 1027 1028
#else
  EXPECT_GE(fp_kers.size(), 2UL);  // jitcode, refer
#endif
1029 1030 1031 1032 1033 1034 1035
#endif

  auto db_kers =
      jit::GetAllCandidateKernels<jit::VExpTuple<double>, CPUPlace>(10);
#if defined(_WIN32) || defined(__APPLE__) || defined(__OSX__)
  EXPECT_GE(db_kers.size(), 1UL);  // refer
#else
1036
#ifdef PADDLE_WITH_MKLML
1037
  EXPECT_GE(db_kers.size(), 2UL);  // mkl, refer
1038 1039 1040
#else
  EXPECT_GE(db_kers.size(), 1UL);  // refer
#endif
1041 1042 1043 1044 1045 1046
#endif
}

TEST(JITKernel_helper, GetAllCandidateFuncsWithTypes) {
  auto fp_kers =
      jit::GetAllCandidateFuncsWithTypes<jit::VExpTuple<float>, CPUPlace>(10);
1047 1048 1049 1050 1051 1052
#if defined(__APPLE__) || defined(__OSX__)
  EXPECT_GE(fp_kers.size(), 1UL);  // refer
#else
#if !defined(PADDLE_WITH_MKLML) || defined(_WIN32)
  EXPECT_GE(fp_kers.size(), 2UL);  // jitcode/mkl, refer
#else
1053
  EXPECT_GE(fp_kers.size(), 3UL);  // jitcode, mkl, refer
1054 1055
#endif
#endif
1056 1057 1058

  auto db_kers =
      jit::GetAllCandidateFuncsWithTypes<jit::VExpTuple<double>, CPUPlace>(10);
1059 1060 1061
#if defined(__APPLE__) || defined(__OSX__) || !defined(PADDLE_WITH_MKLML)
  EXPECT_GE(db_kers.size(), 1UL);  // refer
#else
1062
  EXPECT_GE(db_kers.size(), 2UL);  // mkl, refer
1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077
#endif
}

TEST(JITKernel_helper, KernelFuncs) {
  auto f1 = jit::KernelFuncs<jit::VAddTuple<float>, CPUPlace>::Cache().At(3);
  auto f2 = jit::KernelFuncs<jit::VAddTuple<float>, CPUPlace>::Cache()[3];
  EXPECT_TRUE(f1 != nullptr);
  EXPECT_TRUE(f1 == f2);

  auto f3 = jit::KernelFuncs<jit::VAddTuple<float>, CPUPlace>::Cache()[5];
#if defined(_WIN32) || defined(__APPLE__) || defined(__OSX__)
  EXPECT_TRUE(f2 == f3);
#else
  EXPECT_TRUE(f2 != f3);
#endif
1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095
}

TEST(JITKernel_helper, GetAllCandidateFuncs) {
  auto funcs = jit::GetAllCandidateFuncs<jit::VExpTuple<float>, CPUPlace>(10);
  auto kers = jit::GetAllCandidateKernels<jit::VExpTuple<float>, CPUPlace>(10);
  EXPECT_EQ(funcs.size(), kers.size());

  std::vector<float> x(10), tgt(10);
  RandomVec<float>(10, x.data());
  auto best = jit::GetDefaultBestFunc<jit::VExpTuple<float>, CPUPlace>(10);
  best(x.data(), tgt.data(), 10);
  for (auto f : funcs) {
    std::vector<float> y(10);
    f(x.data(), y.data(), 10);
    ExpectEQ<float>(y.data(), tgt.data(), 10);
  }
}

T
tensor-tang 已提交
1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130
TEST(JITKernel_helper, pack_weights) {
  const int N = 8 * 60, K = 2;
  float src[K][N], yref[K][N], y[K * N];
  float* x = &(src[0][0]);
  float* ref = &(yref[0][0]);
  for (int i = 0; i < N * K; ++i) {
    *(x + i) = static_cast<float>(i);
  }
  int block = 0;
  std::vector<int> groups;
  if (paddle::platform::MayIUse(paddle::platform::avx512f)) {
    block = ZMM_FLOAT_BLOCK;
    groups.push_back(30);
  } else {
    block = YMM_FLOAT_BLOCK;
    groups.insert(groups.end(), {14, 14, 14, 14, 4});
  }

  int offset = 0;
  int acc = 0;
  for (int g : groups) {
    g = g * block;
    for (int k = 0; k < K; ++k) {
      for (int i = 0; i < g; ++i) {
        *(ref + offset) = src[k][i + acc];
        offset++;
      }
    }
    acc += g;
  }

  jit::pack_weights<float>(x, y, N, K);
  ExpectEQ<float>(y, ref, N * K);
}

1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148
TEST(JITKernel_helper, attr) {
  std::ostringstream out;
  // KernelTypes
  out << jit::to_string(jit::kNone) << jit::to_string(jit::kCRFDecoding)
      << jit::to_string(jit::kEmbSeqPool) << jit::to_string(jit::kGRUH1)
      << jit::to_string(jit::kGRUHtPart1) << jit::to_string(jit::kGRUHtPart2)
      << jit::to_string(jit::kHSum) << jit::to_string(jit::kHMax)
      << jit::to_string(jit::kLSTMCtHt) << jit::to_string(jit::kLSTMC1H1)
      << jit::to_string(jit::kLayerNorm) << jit::to_string(jit::kMatMul)
      << jit::to_string(jit::kNCHW16CMulNC) << jit::to_string(jit::kSeqPool)
      << jit::to_string(jit::kSoftmax) << jit::to_string(jit::kVAdd)
      << jit::to_string(jit::kVAddBias) << jit::to_string(jit::kVAddRelu)
      << jit::to_string(jit::kVBroadcast) << jit::to_string(jit::kVCopy)
      << jit::to_string(jit::kVExp) << jit::to_string(jit::kVIdentity)
      << jit::to_string(jit::kVMul) << jit::to_string(jit::kVRelu)
      << jit::to_string(jit::kVScal) << jit::to_string(jit::kSgd)
      << jit::to_string(jit::kVSigmoid) << jit::to_string(jit::kVSquare)
      << jit::to_string(jit::kVSub) << jit::to_string(jit::kVTanh);
1149
  EXPECT_EQ(out.str().size(), 234UL);
1150 1151 1152 1153 1154

  // SeqPoolTypes
  out.str("");
  out << jit::to_string(jit::kSum) << jit::to_string(jit::kAvg)
      << jit::to_string(jit::kSqrt);
1155
  EXPECT_EQ(out.str().size(), 13UL);
1156 1157 1158 1159 1160 1161 1162 1163 1164

  EXPECT_EQ(jit::to_kerneltype("relu"), jit::kVRelu);
  EXPECT_EQ(jit::to_kerneltype("Identity"), jit::kVIdentity);
  EXPECT_EQ(jit::to_kerneltype("VEXP"), jit::kVExp);
  EXPECT_EQ(jit::to_kerneltype("SigmoiD"), jit::kVSigmoid);
  EXPECT_EQ(jit::to_kerneltype("VTanh"), jit::kVTanh);

  out.str("");
  out << jit::lstm_attr_t(8, jit::kVIdentity, jit::kVSigmoid, jit::kVTanh);
1165
  EXPECT_EQ(out.str().size(), 89UL);
1166 1167 1168

  out.str("");
  out << jit::gru_attr_t(8, jit::kVIdentity, jit::kVSigmoid);
1169
  EXPECT_EQ(out.str().size(), 52UL);
1170 1171 1172

  out.str("");
  out << jit::seq_pool_attr_t(8, jit::SeqPoolType::kSum);
1173
  EXPECT_EQ(out.str().size(), 44UL);
1174 1175 1176

  out.str("");
  out << jit::emb_seq_pool_attr_t(1, 2, 3, 4, 5, jit::SeqPoolType::kAvg);
1177
  EXPECT_EQ(out.str().size(), 93UL);
1178 1179 1180

  out.str("");
  out << jit::sgd_attr_t(1, 2, 3, 4, 5);
1181
  EXPECT_EQ(out.str().size(), 81UL);
1182 1183 1184

  out.str("");
  out << jit::matmul_attr_t(1, 2, 3);
1185
  EXPECT_EQ(out.str().size(), 14UL);
1186 1187
}

1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 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
// test keys
TEST(JITKernel_key, int) {
  EXPECT_TRUE(jit::JitCodeKey<int>(2) == jit::JitCodeKey<int>(2));
  EXPECT_TRUE(jit::JitCodeKey<int>(2) == jit::JitCodeKey<int64_t>(2));
  EXPECT_TRUE(jit::JitCodeKey<int>(2) != jit::JitCodeKey<int>(3));
}

TEST(JITKernel_key, gru) {
  jit::gru_attr_t attr1(8, jit::kVSigmoid, jit::kVTanh);
  jit::gru_attr_t attr2(8, jit::kVSigmoid, jit::kVTanh);
  jit::gru_attr_t attr3(9, jit::kVSigmoid, jit::kVTanh);
  jit::gru_attr_t attr4(9, jit::kVSigmoid, jit::kVIdentity);
  jit::gru_attr_t attr5(9, jit::kVTanh, jit::kVIdentity);

  auto key1 = jit::JitCodeKey<jit::gru_attr_t>(attr1);
  auto key2 = jit::JitCodeKey<jit::gru_attr_t>(attr2);
  auto key3 = jit::JitCodeKey<jit::gru_attr_t>(attr3);
  auto key4 = jit::JitCodeKey<jit::gru_attr_t>(attr4);
  auto key5 = jit::JitCodeKey<jit::gru_attr_t>(attr5);

  EXPECT_TRUE(key1 == key2);
  EXPECT_TRUE(key2 != key3);
  EXPECT_TRUE(key2 != key4);
  EXPECT_TRUE(key2 != key5);
  EXPECT_TRUE(key3 != key4);
  EXPECT_TRUE(key3 != key5);
  EXPECT_TRUE(key4 != key5);
}

TEST(JITKernel_key, lstm) {
  jit::lstm_attr_t attr1(8, jit::kVIdentity, jit::kVSigmoid, jit::kVTanh);
  jit::lstm_attr_t attr2(8, jit::kVIdentity, jit::kVSigmoid, jit::kVTanh);
  jit::lstm_attr_t attr3(9, jit::kVIdentity, jit::kVSigmoid, jit::kVTanh);
  jit::lstm_attr_t attr4(9, jit::kVRelu, jit::kVSigmoid, jit::kVTanh);
  jit::lstm_attr_t attr5(9, jit::kVRelu, jit::kVSigmoid, jit::kVTanh, true);
  jit::lstm_attr_t attr6(9, jit::kVRelu, jit::kVSigmoid, jit::kVTanh, true);

  auto key1 = jit::JitCodeKey<jit::lstm_attr_t>(attr1);
  auto key2 = jit::JitCodeKey<jit::lstm_attr_t>(attr2);
  auto key3 = jit::JitCodeKey<jit::lstm_attr_t>(attr3);
  auto key4 = jit::JitCodeKey<jit::lstm_attr_t>(attr4);
  auto key5 = jit::JitCodeKey<jit::lstm_attr_t>(attr5);
  auto key6 = jit::JitCodeKey<jit::lstm_attr_t>(attr6);

  EXPECT_TRUE(key1 == key2);
  EXPECT_TRUE(key2 != key3);
  EXPECT_TRUE(key2 != key4);
  EXPECT_TRUE(key2 != key5);
  EXPECT_TRUE(key3 != key4);
  EXPECT_TRUE(key3 != key5);
  EXPECT_TRUE(key4 != key5);
  EXPECT_TRUE(key5 == key6);
}

TEST(JITKernel_key, seq_pool) {
  jit::seq_pool_attr_t attr1(2, jit::SeqPoolType::kSum, 1);
  jit::seq_pool_attr_t attr2(2, jit::SeqPoolType::kSum, 3);
  jit::seq_pool_attr_t attr3(3, jit::SeqPoolType::kSum, 3);
  jit::seq_pool_attr_t attr4(3, jit::SeqPoolType::kAvg, 3);

  auto key1 = jit::JitCodeKey<jit::seq_pool_attr_t>(attr1);
  auto key2 = jit::JitCodeKey<jit::seq_pool_attr_t>(attr2);
  auto key3 = jit::JitCodeKey<jit::seq_pool_attr_t>(attr3);
  auto key4 = jit::JitCodeKey<jit::seq_pool_attr_t>(attr4);

  EXPECT_TRUE(key1 == key2);
  EXPECT_TRUE(key2 != key3);
  EXPECT_TRUE(key2 != key4);
  EXPECT_TRUE(key3 != key4);
}

TEST(JITKernel_key, matmul) {
  jit::matmul_attr_t attr1(1, 2, 3);
  jit::matmul_attr_t attr2(1, 2, 3);
  jit::matmul_attr_t attr3(1, 3, 3);
  jit::matmul_attr_t attr4(2, 3, 4);

  auto key1 = jit::JitCodeKey<jit::matmul_attr_t>(attr1);
  auto key2 = jit::JitCodeKey<jit::matmul_attr_t>(attr2);
  auto key3 = jit::JitCodeKey<jit::matmul_attr_t>(attr3);
  auto key4 = jit::JitCodeKey<jit::matmul_attr_t>(attr4);

  EXPECT_TRUE(key1 == key2);
  EXPECT_TRUE(key2 != key3);
  EXPECT_TRUE(key2 != key4);
  EXPECT_TRUE(key3 != key4);
}

TEST(JITKernel_key, emb_seq_pool) {
  jit::emb_seq_pool_attr_t attr1(1, 2, 3, 4, 5, jit::SeqPoolType::kSum);
  jit::emb_seq_pool_attr_t attr2(1, 2, 3, 4, 5, jit::SeqPoolType::kSum);
  jit::emb_seq_pool_attr_t attr3(10, 2, 9, 8, 7, jit::SeqPoolType::kAvg);
  jit::emb_seq_pool_attr_t attr4(10, 3, 9, 8, 7, jit::SeqPoolType::kSum);
  jit::emb_seq_pool_attr_t attr5(1, 6, 3, 4, 5, jit::SeqPoolType::kSum);

  auto key1 = jit::JitCodeKey<jit::emb_seq_pool_attr_t>(attr1);
  auto key2 = jit::JitCodeKey<jit::emb_seq_pool_attr_t>(attr2);
  auto key3 = jit::JitCodeKey<jit::emb_seq_pool_attr_t>(attr3);
  auto key4 = jit::JitCodeKey<jit::emb_seq_pool_attr_t>(attr4);
  auto key5 = jit::JitCodeKey<jit::emb_seq_pool_attr_t>(attr5);

  EXPECT_TRUE(key1 == key2);
  EXPECT_TRUE(key2 == key3);
  EXPECT_TRUE(key2 != key4);
  EXPECT_TRUE(key2 != key5);
  EXPECT_TRUE(key4 != key5);
}

TEST(JITKernel_key, sgd) {
  jit::sgd_attr_t attr1(1, 2, 3, 4, 5);
  jit::sgd_attr_t attr2(1, 2, 3, 4, 5);
  jit::sgd_attr_t attr3(9, 8, 7, 4, 6);
  jit::sgd_attr_t attr4(1, 2, 3, 6, 5);
  jit::sgd_attr_t attr5(10, 9, 8, 7, 6);

  auto key1 = jit::JitCodeKey<jit::sgd_attr_t>(attr1);
  auto key2 = jit::JitCodeKey<jit::sgd_attr_t>(attr2);
  auto key3 = jit::JitCodeKey<jit::sgd_attr_t>(attr3);
  auto key4 = jit::JitCodeKey<jit::sgd_attr_t>(attr4);
  auto key5 = jit::JitCodeKey<jit::sgd_attr_t>(attr5);

  EXPECT_TRUE(key1 == key2);
  EXPECT_TRUE(key2 == key3);
  EXPECT_TRUE(key3 != key4);
  EXPECT_TRUE(key3 != key5);
  EXPECT_TRUE(key4 != key5);
}

1316
// test kernerls
1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346
#define TestKernelVMul TestKernelXYZN
#define TestKernelVAdd TestKernelXYZN
#define TestKernelVAddRelu TestKernelXYZN
#define TestKernelVSub TestKernelXYZN

#define TestKernelVScal TestKernelAXYN
#define TestKernelVAddBias TestKernelAXYN

#define TestKernelVRelu TestKernelXYN
#define TestKernelVIdentity TestKernelXYN
#define TestKernelVSquare TestKernelXYN
#define TestKernelVExp TestKernelXYN
#define TestKernelVSigmoid TestKernelXYN
#define TestKernelVTanh TestKernelXYN
#define TestKernelVCopy TestKernelXYN

#define TestKernelHMax TestKernelXRN
#define TestKernelHSum TestKernelXRN

#define TestKernelLSTMCtHt TestKernelLSTM
#define TestKernelLSTMC1H1 TestKernelLSTM

#define TestKernelGRUH1 TestKernelGRU
#define TestKernelGRUHtPart1 TestKernelGRU
#define TestKernelGRUHtPart2 TestKernelGRU

#define TEST_CPU_KERNEL(kernel_type)                                      \
  TEST(JITKernel, kernel_type) {                                          \
    TestKernel##kernel_type<jit::kernel_type##Tuple<float>, CPUPlace>();  \
    TestKernel##kernel_type<jit::kernel_type##Tuple<double>, CPUPlace>(); \
T
tensor-tang 已提交
1347
  }
T
tensor-tang 已提交
1348

1349 1350 1351 1352
TEST_CPU_KERNEL(VMul);
TEST_CPU_KERNEL(VAdd);
TEST_CPU_KERNEL(VAddRelu);
TEST_CPU_KERNEL(VSub);
T
tensor-tang 已提交
1353

1354 1355
TEST_CPU_KERNEL(VScal);
TEST_CPU_KERNEL(VAddBias);
T
tensor-tang 已提交
1356

1357 1358 1359 1360 1361 1362 1363
TEST_CPU_KERNEL(VRelu);
TEST_CPU_KERNEL(VIdentity);
TEST_CPU_KERNEL(VSquare);
TEST_CPU_KERNEL(VExp);
TEST_CPU_KERNEL(VSigmoid);
TEST_CPU_KERNEL(VTanh);
TEST_CPU_KERNEL(VCopy);
T
tensor-tang 已提交
1364

1365 1366
TEST_CPU_KERNEL(HMax);
TEST_CPU_KERNEL(HSum);
T
tensor-tang 已提交
1367

1368 1369
TEST_CPU_KERNEL(LSTMCtHt);
TEST_CPU_KERNEL(LSTMC1H1);
T
tensor-tang 已提交
1370

1371 1372 1373
TEST_CPU_KERNEL(GRUH1);
TEST_CPU_KERNEL(GRUHtPart1);
TEST_CPU_KERNEL(GRUHtPart2);
1374

1375 1376 1377
TEST_CPU_KERNEL(NCHW16CMulNC);
TEST_CPU_KERNEL(LayerNorm);
TEST_CPU_KERNEL(CRFDecoding);
1378

1379 1380 1381 1382 1383 1384
TEST_CPU_KERNEL(SeqPool);
TEST_CPU_KERNEL(EmbSeqPool);
TEST_CPU_KERNEL(MatMul);
TEST_CPU_KERNEL(Softmax);
TEST_CPU_KERNEL(Sgd);
TEST_CPU_KERNEL(VBroadcast);
D
dengkaipeng 已提交
1385 1386 1387

TEST_CPU_KERNEL(StrideASum);
TEST_CPU_KERNEL(StrideScal);