gemv_int8_compute_test.cc 13.7 KB
Newer Older
X
Xiaoyang LI 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
// Copyright (c) 2019 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 <gflags/gflags.h>
#include <gtest/gtest.h>
#include "lite/tests/utils/fill_data.h"
#include "lite/tests/utils/naive_math_impl.h"
#ifdef LITE_WITH_ARM
#include "lite/backends/arm/math/funcs.h"
#endif  // LITE_WITH_ARM
#include "lite/core/context.h"
23
#include "lite/core/profile/timer.h"
X
Xiaoyang LI 已提交
24 25
#include "lite/core/tensor.h"
#include "lite/tests/utils/tensor_utils.h"
C
chenjiaoAngel 已提交
26
#include "lite/backends/arm/math/saturate.h"
X
Xiaoyang LI 已提交
27 28

typedef paddle::lite::Tensor Tensor;
29
using paddle::lite::profile::Timer;
X
Xiaoyang LI 已提交
30 31 32 33 34 35 36 37 38 39 40

DEFINE_int32(power_mode,
             3,
             "power mode: "
             "0 for POWER_HIGH;"
             "1 for POWER_LOW;"
             "2 for POWER_FULL;"
             "3 for NO_BIND");
DEFINE_int32(threads, 1, "threads num");
DEFINE_int32(warmup, 0, "warmup times");
DEFINE_int32(repeats, 1, "repeats times");
41
DEFINE_bool(basic_test, true, "do all tests");
X
Xiaoyang LI 已提交
42 43 44 45 46 47 48
DEFINE_bool(check_result, true, "check the result");

DEFINE_int32(M, 512, "gemv: M");
DEFINE_int32(N, 512, "gemv: N");

DEFINE_bool(traA, false, "gemv: A transpose");

C
chenjiaoAngel 已提交
49
DEFINE_int32(flag_act, 0, "do act");
X
Xiaoyang LI 已提交
50
DEFINE_bool(flag_bias, false, "with bias");
C
chenjiaoAngel 已提交
51 52
DEFINE_double(leakey_relu_alpha, 1.0, "leakey relu alpha");
DEFINE_double(clipped_coef, 6.0, "clipped relu coef");
X
Xiaoyang LI 已提交
53

C
chenjiaoAngel 已提交
54 55 56 57 58 59 60 61 62
bool test_gemv_int8(bool tra,
                    int m,
                    int n,
                    bool has_bias,
                    int flag_act,
                    int cls,
                    int ths,
                    float six = 6.f,
                    float alpha = 1.f) {
X
Xiaoyang LI 已提交
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
  Tensor ta;
  Tensor tb;
  Tensor tc_int8;
  Tensor tc_fp32;
  Tensor tc_basic_int8;
  Tensor tc_basic_fp32;
  Tensor tbias;

  ta.Resize({m, n});
  tb.Resize({n});
  tc_int8.Resize({m});
  tc_fp32.Resize({m});
  tc_basic_int8.Resize({m});
  tc_basic_fp32.Resize({m});
  tbias.Resize({m});

  ta.set_precision(PRECISION(kInt8));
  tb.set_precision(PRECISION(kInt8));
  tc_int8.set_precision(PRECISION(kInt8));
  tc_fp32.set_precision(PRECISION(kFloat));
  tc_basic_int8.set_precision(PRECISION(kInt8));
  tc_basic_fp32.set_precision(PRECISION(kFloat));
  tbias.set_precision(PRECISION(kFloat));

  fill_tensor_rand(ta, -127, 127);
  fill_tensor_rand(tb, -127, 127);
  fill_tensor_rand(tbias, -1.f, 1.f);

  std::vector<float> scale_a(static_cast<size_t>(m), 1.f / 127);
  std::vector<float> scale_b = {1.f / 127};
  std::vector<float> scale_c = {n / 127.f};
  std::vector<float> scale_merge_fp32(static_cast<size_t>(m));
  std::vector<float> scale_merge_int8(static_cast<size_t>(m));
  for (int j = 0; j < m; ++j) {
    scale_merge_fp32[j] = scale_a[j] * scale_b[0];
    scale_merge_int8[j] = scale_merge_fp32[j] / scale_c[0];
  }

  LOG(INFO) << "gemv_int8 M: " << m << ", N: " << n
            << ", transA: " << (tra ? "true" : "false")
C
chenjiaoAngel 已提交
103
            << ", act: " << flag_act
X
Xiaoyang LI 已提交
104 105 106 107 108 109 110 111 112 113
            << ", bias: " << (has_bias ? "true" : "false");
#ifdef LITE_WITH_ARM
  auto da = ta.mutable_data<int8_t>();
  auto db = tb.mutable_data<int8_t>();
  auto dc_int8 = tc_int8.mutable_data<int8_t>();
  auto dc_fp32 = tc_fp32.mutable_data<float>();
  auto dc_basic_int8 = tc_basic_int8.mutable_data<int8_t>();
  auto dc_basic_fp32 = tc_basic_fp32.mutable_data<float>();
  auto dbias = tbias.mutable_data<float>();

C
chenjiaoAngel 已提交
114 115 116 117 118 119 120 121 122 123
  paddle::lite_api::ActivationType act =
      paddle::lite_api::ActivationType::kIndentity;
  if (flag_act == 1) {
    act = paddle::lite_api::ActivationType::kRelu;
  } else if (flag_act == 2) {
    act = paddle::lite_api::ActivationType::kRelu6;
  } else if (flag_act == 4) {
    act = paddle::lite_api::ActivationType::kLeakyRelu;
  }

X
Xiaoyang LI 已提交
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
  if (FLAGS_check_result) {
    Tensor ta_fp32;
    Tensor tb_fp32;
    ta_fp32.Resize({m, n});
    ta_fp32.set_precision(PRECISION(kFloat));
    tb_fp32.Resize({n});
    tb_fp32.set_precision(PRECISION(kFloat));

    auto da_fp32 = ta_fp32.mutable_data<float>();
    auto db_fp32 = tb_fp32.mutable_data<float>();

    paddle::lite::arm::math::int8_to_fp32(
        da, da_fp32, scale_a.data(), 1, 1, ta.numel());
    paddle::lite::arm::math::int8_to_fp32(
        db, db_fp32, scale_b.data(), 1, 1, tb.numel());
    basic_gemv(m,
               n,
               da_fp32,
               db_fp32,
               dbias,
               dc_basic_fp32,
               1.f,
               0.f,
               false,
               has_bias,
C
chenjiaoAngel 已提交
149 150 151
               flag_act,
               six,
               alpha);
X
Xiaoyang LI 已提交
152 153 154 155 156 157
    paddle::lite::arm::math::fp32_to_int8(dc_basic_fp32,
                                          dc_basic_int8,
                                          scale_c.data(),
                                          1,
                                          1,
                                          tc_basic_fp32.numel());
C
chenjiaoAngel 已提交
158 159 160 161 162
   if (flag_act == 2) { // relu6
      for (int i = 0; i < tc_basic_int8.numel(); i++) {
          dc_basic_int8[i] = dc_basic_int8[i] > six ? six : dc_basic_int8[i];
      }
  }
X
Xiaoyang LI 已提交
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
  }
  Timer t0;
  //! compute
  double ops = 2.0 * m * n;
  std::unique_ptr<paddle::lite::KernelContext> ctx1(
      new paddle::lite::KernelContext);
  auto& ctx = ctx1->As<paddle::lite::ARMContext>();
  ctx.SetRunMode(static_cast<paddle::lite_api::PowerMode>(cls), ths);
  /// warmup
  for (int j = 0; j < FLAGS_warmup; ++j) {
    paddle::lite::arm::math::gemv_int8(da,
                                       db,
                                       dc_fp32,
                                       false,
                                       m,
                                       n,
                                       scale_merge_fp32.data(),
                                       has_bias,
                                       dbias,
C
chenjiaoAngel 已提交
182 183 184 185 186
                                       flag_act > 0,
                                       act,
                                       &ctx,
                                       six,
                                       alpha);
X
Xiaoyang LI 已提交
187 188 189 190 191 192 193 194 195 196 197
  }

  /// int8 output compute
  Tensor tbias_int8;
  tbias_int8.Resize(tbias.dims());
  tbias_int8.set_precision(PRECISION(kFloat));
  auto dbias_int8 = tbias_int8.mutable_data<float>();
  for (int l = 0; l < tbias_int8.numel(); ++l) {
    dbias_int8[l] = dbias[l] / scale_c[0];
  }
  for (int i = 0; i < FLAGS_repeats; ++i) {
198
    t0.Start();
X
Xiaoyang LI 已提交
199 200 201 202 203 204 205 206 207
    paddle::lite::arm::math::gemv_int8(da,
                                       db,
                                       dc_fp32,
                                       false,
                                       m,
                                       n,
                                       scale_merge_fp32.data(),
                                       has_bias,
                                       dbias,
C
chenjiaoAngel 已提交
208 209 210 211 212
                                       flag_act > 0,
                                       act,
                                       &ctx,
                                       six,
                                       alpha);
213
    t0.Stop();
X
Xiaoyang LI 已提交
214 215 216 217
  }
  LOG(INFO) << "gemv_int8_int8 output: M: " << m << ", N: " << n
            << ", power_mode: " << cls << ", threads: " << ths
            << ", GOPS: " << ops * 1e-9f
218 219 220 221
            << " GOPS, avg time: " << t0.LapTimes().Avg()
            << " ms, min time: " << t0.LapTimes().Min()
            << " ms, mean GOPs: " << ops * 1e-6f / t0.LapTimes().Avg()
            << " GOPs, max GOPs: " << ops * 1e-6f / t0.LapTimes().Min()
X
Xiaoyang LI 已提交
222 223 224
            << " GOPs";

  /// fp32 output compute
225
  t0.Reset();
X
Xiaoyang LI 已提交
226
  for (int i = 0; i < FLAGS_repeats; ++i) {
227
    t0.Start();
X
Xiaoyang LI 已提交
228 229 230 231 232 233 234 235 236
    paddle::lite::arm::math::gemv_int8(da,
                                       db,
                                       dc_int8,
                                       false,
                                       m,
                                       n,
                                       scale_merge_int8.data(),
                                       has_bias,
                                       dbias_int8,
C
chenjiaoAngel 已提交
237 238 239 240 241
                                       flag_act > 0,
                                       act,
                                       &ctx,
                                       six,
                                       alpha);
242
    t0.Stop();
X
Xiaoyang LI 已提交
243 244 245 246
  }
  LOG(INFO) << "gemm_int8_fp32 output: M: " << m << ", N: " << n
            << ", power_mode: " << cls << ", threads: " << ths
            << ", GOPS: " << ops * 1e-9f
247 248 249 250
            << " GOPS, avg time: " << t0.LapTimes().Avg()
            << " ms, min time: " << t0.LapTimes().Min()
            << " ms, mean GOPs: " << ops * 1e-6f / t0.LapTimes().Avg()
            << " GOPs, max GOPs: " << ops * 1e-6f / t0.LapTimes().Min()
X
Xiaoyang LI 已提交
251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 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
            << " GOPs";

  if (FLAGS_check_result) {
    double max_ratio = 0;
    double max_diff = 0;
    /// fp32 result
    tensor_cmp_host(tc_basic_fp32, tc_fp32, max_ratio, max_diff);
    LOG(INFO) << "fp32 compare result, max diff: " << max_diff
              << ", max ratio: " << max_ratio;
    if (std::abs(max_ratio) > 1e-4f && std::abs(max_diff) > 5e-5f) {
      Tensor tdiff;
      tdiff.set_precision(PRECISION(kFloat));
      tdiff.Resize(tc_fp32.dims());
      tensor_diff(tc_basic_fp32, tc_fp32, tdiff);
      LOG(INFO) << "basic result: ";
      print_tensor(tc_basic_fp32);
      LOG(INFO) << "lite result: ";
      print_tensor(tc_fp32);
      LOG(INFO) << "diff result: ";
      print_tensor(tdiff);
      return false;
    }
    /// int8 result
    max_ratio = 0;
    max_diff = 0;
    tensor_cmp_host(tc_basic_int8, tc_int8, max_ratio, max_diff);
    LOG(INFO) << "int8 compare result, max diff: " << max_diff
              << ", max ratio: " << max_ratio;
    if (fabs(max_ratio) > 1e-4f) {
      Tensor tdiff;
      tdiff.Resize(tc_int8.dims());
      tdiff.set_precision(PRECISION(kInt8));
      tensor_diff(tc_basic_int8, tc_int8, tdiff);
      auto ptr = tdiff.data<int8_t>();
      auto ptr_basic_fp32 = tc_basic_fp32.data<float>();
      float count = 0;
      bool check = true;
      for (int i = 0; i < tdiff.numel(); ++i) {
        if (abs(ptr[i]) > 1) {
          check = false;
          LOG(ERROR) << "basic float data: " << ptr_basic_fp32[i]
                     << ", after scale: " << ptr_basic_fp32[i] / scale_c[0];
          break;
        }
        if (ptr[i] != 0) {
          LOG(ERROR) << "basic float data: " << ptr_basic_fp32[i]
                     << ", after scale: " << ptr_basic_fp32[i] / scale_c[0];
          count += 1;
        }
      }
      check =
          check && count < std::max(10, static_cast<int>(0.01 * tdiff.numel()));
      if (!check) {
        LOG(WARNING) << "int8 basic result";
        print_tensor(tc_basic_int8);
        LOG(WARNING) << "int8 lite result";
        print_tensor(tc_int8);
        LOG(WARNING) << "int8 diff tensor";
        print_tensor(tdiff);
        return false;
      }
    }
  }
#endif
  return true;
}

TEST(TestLiteGemvInt8, gemv_prepacked_int8) {
  if (FLAGS_basic_test) {
#ifdef LITE_WITH_ARM
    paddle::lite::DeviceInfo::Init();
#endif
    LOG(INFO) << "run basic sgemm test";
324
    for (auto& m : {1, 3, 8, 32}) {  // ,397
X
Xiaoyang LI 已提交
325 326 327
      for (auto& n : {1, 3, 13, 141, 512, 789}) {
        for (auto& tra : {false}) {
          for (auto& has_bias : {false, true}) {
C
chenjiaoAngel 已提交
328
            for (auto& flag_act : {0, 1, 2, 4}) {
X
Xiaoyang LI 已提交
329
              for (auto& th : {1, 2, 4}) {
C
chenjiaoAngel 已提交
330 331 332 333 334 335 336 337 338 339 340
                float six = 6.f;
                float alpha = 8.88f;
                auto flag = test_gemv_int8(tra,
                                           m,
                                           n,
                                           has_bias,
                                           flag_act,
                                           FLAGS_power_mode,
                                           th,
                                           six,
                                           alpha);
X
Xiaoyang LI 已提交
341 342 343
                if (flag) {
                  LOG(INFO) << "test m = " << m << ", n=" << n
                            << ", bias: " << (has_bias ? "true" : "false")
C
chenjiaoAngel 已提交
344
                            << ", act: " << flag_act
X
Xiaoyang LI 已提交
345 346 347 348 349
                            << ", trans A: " << (tra ? "true" : "false")
                            << " passed\n";
                } else {
                  LOG(FATAL) << "test m = " << m << ", n=" << n
                             << ", bias: " << (has_bias ? "true" : "false")
C
chenjiaoAngel 已提交
350
                             << ", act: " << flag_act
X
Xiaoyang LI 已提交
351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370
                             << ", trans A: " << (tra ? "true" : "false")
                             << " failed\n";
                }
              }
            }
          }
        }
      }
    }
  }
}

TEST(TestGemvInt8Custom, gemv_prepacked_int8_custom) {
#ifdef LITE_WITH_ARM
  paddle::lite::DeviceInfo::Init();
#endif
  auto flag = test_gemv_int8(FLAGS_traA,
                             FLAGS_M,
                             FLAGS_N,
                             FLAGS_flag_bias,
C
chenjiaoAngel 已提交
371
                             FLAGS_flag_act,
X
Xiaoyang LI 已提交
372
                             FLAGS_power_mode,
C
chenjiaoAngel 已提交
373 374 375
                             FLAGS_threads,
                             FLAGS_clipped_coef,
                             FLAGS_leakey_relu_alpha);
X
Xiaoyang LI 已提交
376 377 378
  if (!flag) {
    LOG(FATAL) << "test m = " << FLAGS_M << ", n=" << FLAGS_N
               << ", trans A: " << FLAGS_traA << ", bias: " << FLAGS_flag_bias
C
chenjiaoAngel 已提交
379
               << ", act: " << FLAGS_flag_act << " failed!!";
X
Xiaoyang LI 已提交
380 381 382
  }
  LOG(INFO) << "test m = " << FLAGS_M << ", n=" << FLAGS_N
            << ", trans A: " << FLAGS_traA << ", bias: " << FLAGS_flag_bias
C
chenjiaoAngel 已提交
383
            << ", act: " << FLAGS_flag_act << " passed!!";
X
Xiaoyang LI 已提交
384
}