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 <chrono> 12 #include <cstddef> 13 #include <cstdlib> 14 #include <functional> 15 #include <random> 16 #include <vector> 17 18 #include <xnnpack.h> 19 #include <xnnpack/params.h> 20 21 22 class VScaleExtExpMicrokernelTester { 23 public: elements(size_t elements)24 inline VScaleExtExpMicrokernelTester& 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 VScaleExtExpMicrokernelTester& 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_vscaleextexp_ukernel_function vscaleextexp)43 void Test(xnn_f32_vscaleextexp_ukernel_function vscaleextexp) 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 std::vector<float> y(elements()); 51 std::vector<double> y_ref(elements()); 52 for (size_t iteration = 0; iteration < iterations(); iteration++) { 53 std::generate(x.begin(), x.end(), std::ref(f32rng)); 54 55 // Compute scale parameters. 56 double sum = 0.0; 57 for (size_t i = 0; i < elements(); i++) { 58 sum += std::exp(double(x[i])); 59 } 60 int sum_exponent; 61 const double sum_mantissa = std::frexp(sum, &sum_exponent); 62 const float scale_mantissa = float(1.0 / sum_mantissa); 63 const float scale_exponent = -float(sum_exponent); 64 65 // Compute reference results. 66 for (size_t i = 0; i < elements(); i++) { 67 y_ref[i] = std::exp(double(x[i])) / sum; 68 } 69 70 // Call optimized micro-kernel. 71 vscaleextexp(elements() * sizeof(float), x.data(), y.data(), scale_mantissa, scale_exponent); 72 73 // Verify results. 74 for (size_t i = 0; i < elements(); i++) { 75 ASSERT_NEAR(y_ref[i], y[i], std::abs(y_ref[i]) * 1.0e-6) 76 << "elements = " << elements() << ", scale:mantissa = " << scale_mantissa << ", scale:exponent = " << scale_exponent; 77 } 78 } 79 } 80 81 private: 82 size_t elements_{1}; 83 size_t iterations_{15}; 84 }; 85