blob: 610acb55ceb96c86d69b3046cf04112940287994 [file] [log] [blame]
XNNPACK Teamb455b122019-09-27 18:10:33 -07001// Copyright (c) Facebook, Inc. and its affiliates.
2// All rights reserved.
3//
4// Copyright 2019 Google LLC
5//
6// This source code is licensed under the BSD-style license found in the
7// LICENSE file in the root directory of this source tree.
8
9#pragma once
10
11#include <gtest/gtest.h>
12
13#include <algorithm>
14#include <cassert>
15#include <cstddef>
16#include <cstdlib>
17#include <functional>
Marat Dukhan5ce30d92020-04-14 03:31:26 -070018#include <limits>
XNNPACK Teamb455b122019-09-27 18:10:33 -070019#include <random>
20#include <vector>
21
22#include <xnnpack/params.h>
23
24
25class LUTMicrokernelTester {
26 public:
27 inline LUTMicrokernelTester& n(size_t n) {
28 assert(n != 0);
29 this->n_ = n;
30 return *this;
31 }
32
33 inline size_t n() const {
34 return this->n_;
35 }
36
37 inline LUTMicrokernelTester& inplace(bool inplace) {
38 this->inplace_ = inplace;
39 return *this;
40 }
41
42 inline bool inplace() const {
43 return this->inplace_;
44 }
45
46 inline LUTMicrokernelTester& iterations(size_t iterations) {
47 this->iterations_ = iterations;
48 return *this;
49 }
50
51 inline size_t iterations() const {
52 return this->iterations_;
53 }
54
55 void Test(xnn_x8_lut_ukernel_function lut) const {
56 std::random_device random_device;
57 auto rng = std::mt19937(random_device());
Marat Dukhan5ce30d92020-04-14 03:31:26 -070058 auto u8rng = std::bind(std::uniform_int_distribution<uint32_t>(0, std::numeric_limits<uint8_t>::max()), rng);
XNNPACK Teamb455b122019-09-27 18:10:33 -070059
60 std::vector<uint8_t> x(n());
61 std::vector<uint8_t> t(256);
62 std::vector<uint8_t> y(n());
63 std::vector<uint8_t> y_ref(n());
64 for (size_t iteration = 0; iteration < iterations(); iteration++) {
65 std::generate(x.begin(), x.end(), std::ref(u8rng));
66 std::generate(t.begin(), t.end(), std::ref(u8rng));
67 if (inplace()) {
68 std::generate(y.begin(), y.end(), std::ref(u8rng));
69 } else {
70 std::fill(y.begin(), y.end(), 0xA5);
71 }
72 const uint8_t* x_data = inplace() ? y.data() : x.data();
73
74 // Compute reference results.
75 for (size_t i = 0; i < n(); i++) {
76 y_ref[i] = t[x_data[i]];
77 }
78
79 // Call optimized micro-kernel.
80 lut(n(), x_data, t.data(), y.data());
81
82 // Verify results.
83 for (size_t i = 0; i < n(); i++) {
84 ASSERT_EQ(uint32_t(y_ref[i]), uint32_t(y[i]))
85 << "at position " << i << ", n = " << n();
86 }
87 }
88 }
89
90 private:
91 size_t n_{1};
92 bool inplace_{false};
93 size_t iterations_{15};
94};