blob: 9ac98e8cf377c4a70cdf1897e8f1ca7216b9c3a6 [file] [log] [blame]
Marat Dukhan05ac8e32019-10-21 15:39:33 -07001// Copyright 2019 Google LLC
2//
3// This source code is licensed under the BSD-style license found in the
4// LICENSE file in the root directory of this source tree.
5
6#pragma once
7
8#include <gtest/gtest.h>
9
10#include <algorithm>
11#include <cassert>
12#include <cstddef>
13#include <cstdlib>
14#include <functional>
15#include <random>
16#include <vector>
17
18#include <xnnpack.h>
Marat Dukhaneeaa7bd2019-10-25 17:31:25 -070019#include <xnnpack/params-init.h>
Frank Barcharde0601b52019-10-25 17:43:34 -070020#include <xnnpack/params.h>
Marat Dukhan05ac8e32019-10-21 15:39:33 -070021
22
23class VScaleMicrokernelTester {
24 public:
25 enum class Variant {
26 Native,
27 Scalar,
28 };
29
30 inline VScaleMicrokernelTester& n(size_t n) {
31 assert(n != 0);
32 this->n_ = n;
33 return *this;
34 }
35
36 inline size_t n() const {
37 return this->n_;
38 }
39
40 inline VScaleMicrokernelTester& inplace(bool inplace) {
41 this->inplace_ = inplace;
42 return *this;
43 }
44
45 inline bool inplace() const {
46 return this->inplace_;
47 }
48
49 inline VScaleMicrokernelTester& iterations(size_t iterations) {
50 this->iterations_ = iterations;
51 return *this;
52 }
53
54 inline size_t iterations() const {
55 return this->iterations_;
56 }
57
58 void Test(xnn_f32_vscale_ukernel_function vscale, Variant variant = Variant::Native) const {
59 std::random_device random_device;
60 auto rng = std::mt19937(random_device());
61 auto f32rng = std::bind(std::uniform_real_distribution<float>(-1.0f, 1.0f), rng);
62
63 std::vector<float> x(n() + XNN_EXTRA_BYTES / sizeof(float));
64 std::vector<float> y(n() + (inplace() ? XNN_EXTRA_BYTES / sizeof(float) : 0));
65 std::vector<float> y_ref(n());
66 for (size_t iteration = 0; iteration < iterations(); iteration++) {
67 if (inplace()) {
68 std::generate(y.begin(), y.end(), std::ref(f32rng));
69 } else {
70 std::generate(x.begin(), x.end(), std::ref(f32rng));
71 std::fill(y.begin(), y.end(), nanf(""));
72 }
73 const float c = f32rng();
74 const float* x_data = inplace() ? y.data() : x.data();
75
76 // Compute reference results.
77 for (size_t i = 0; i < n(); i++) {
78 y_ref[i] = x_data[i] * c;
79 }
80
81 // Call optimized micro-kernel.
82 vscale(n() * sizeof(float), x_data, y.data(), c);
83
84 // Verify results.
85 for (size_t i = 0; i < n(); i++) {
86 ASSERT_NEAR(y[i], y_ref[i], std::abs(y_ref[i]) * 1.0e-6f)
87 << "at " << i << ", n = " << n();
88 }
89 }
90 }
91
92 private:
93 size_t n_{1};
94 size_t iterations_{15};
95 bool inplace_{false};
96};