xref: /aosp_15_r20/external/XNNPACK/test/raddextexp-microkernel-tester.h (revision 4bdc94577ba0e567308109d787f7fec7b531ce36)
1 // 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>
19 #include <xnnpack/microfnptr.h>
20 
21 
22 class RAddExtExpMicrokernelTester {
23  public:
elements(size_t elements)24   inline RAddExtExpMicrokernelTester& elements(size_t elements) {
25     assert(elements != 0);
26     this->elements_ = elements;
27     return *this;
28   }
29 
elements()30   inline size_t elements() const {
31     return this->elements_;
32   }
33 
iterations(size_t iterations)34   inline RAddExtExpMicrokernelTester& iterations(size_t iterations) {
35     this->iterations_ = iterations;
36     return *this;
37   }
38 
iterations()39   inline size_t iterations() const {
40     return this->iterations_;
41   }
42 
Test(xnn_f32_raddextexp_ukernel_function raddextexp)43   void Test(xnn_f32_raddextexp_ukernel_function raddextexp) const {
44     std::random_device random_device;
45     auto rng = std::mt19937(random_device());
46     // Choose such range that expf(x[i]) overflows, but double-precision exp doesn't overflow.
47     auto f32rng = std::bind(std::uniform_real_distribution<float>(90.0f, 100.0f), rng);
48 
49     std::vector<float> x(elements() + XNN_EXTRA_BYTES / sizeof(float));
50     for (size_t iteration = 0; iteration < iterations(); iteration++) {
51       std::generate(x.begin(), x.end(), std::ref(f32rng));
52 
53       // Compute reference results.
54       double sum_ref = 0.0f;
55       for (size_t i = 0; i < elements(); i++) {
56         sum_ref += exp(double(x[i]));
57       }
58 
59       // Call optimized micro-kernel.
60       float sum[2] = { nanf(""), nanf("") };
61       raddextexp(elements() * sizeof(float), x.data(), sum);
62 
63       // Verify results.
64       ASSERT_NEAR(sum_ref, exp2(double(sum[1])) * double(sum[0]), std::abs(sum_ref) * 1.0e-6)
65         << "elements = " << elements() << ", y:value = " << sum[0] << ", y:exponent = " << sum[1];
66     }
67   }
68 
69  private:
70   size_t elements_{1};
71   size_t iterations_{15};
72 };
73