generate.hpp 1.71 KB
Newer Older
Paul's avatar
Paul committed
1
2
3
4
#ifndef MIGRAPH_GUARD_MIGRAPHLIB_GENERATE_HPP
#define MIGRAPH_GUARD_MIGRAPHLIB_GENERATE_HPP

#include <migraph/argument.hpp>
Paul's avatar
Paul committed
5
#include <migraph/literal.hpp>
Paul's avatar
Paul committed
6
7
8
9
#include <random>

namespace migraph {

Paul's avatar
Paul committed
10
template <class T, MIGRAPH_REQUIRES(std::is_floating_point<T>{})>
Paul's avatar
Paul committed
11
constexpr T normalize(unsigned long z)
12
{
Paul's avatar
Paul committed
13
14
    if(z == 0)
        return 0;
15
16
17
    return (2.0 / z) - 1.0;
}

Paul's avatar
Paul committed
18
template <class T, MIGRAPH_REQUIRES(std::is_signed<T>{} and not std::is_floating_point<T>{})>
Paul's avatar
Paul committed
19
constexpr T normalize(unsigned long z)
20
{
Paul's avatar
Paul committed
21
22
    const auto max      = std::numeric_limits<T>::max();
    const auto half_max = max / 2;
23
24
25
    return half_max - (z % max);
}

Paul's avatar
Paul committed
26
template <class T, MIGRAPH_REQUIRES(not std::is_signed<T>{} and std::is_integral<T>{})>
Paul's avatar
Paul committed
27
constexpr T normalize(unsigned long z)
28
29
30
31
32
{
    const auto max = std::numeric_limits<T>::max();
    return z % max;
}

Paul's avatar
Paul committed
33
template <class T>
34
35
struct xorshf96_generator
{
Paul's avatar
Paul committed
36
37
    unsigned long x = 123456789;
    unsigned long y = 362436069;
Paul's avatar
Paul committed
38
39
    unsigned long z;

Paul's avatar
Paul committed
40
    xorshf96_generator(unsigned long seed = 0) : z(521288629ULL ^ seed) {}
41

42
    constexpr T operator()() noexcept
43
    {
44
45
46
        x ^= x << 16U;
        x ^= x >> 5U;
        x ^= x << 1U;
47

Paul's avatar
Paul committed
48
        unsigned long t = x;
Paul's avatar
Paul committed
49
50
51
        x               = y;
        y               = z;
        z               = t ^ x ^ y;
52

Paul's avatar
Paul committed
53
        return normalize<T>(z);
54
55
56
    }
};

Paul's avatar
Paul committed
57
template <class T>
Paul's avatar
Paul committed
58
std::vector<T> generate_tensor_data(const migraph::shape& s, unsigned long seed = 0)
Paul's avatar
Paul committed
59
60
{
    std::vector<T> result(s.elements());
Paul's avatar
Paul committed
61
    std::generate(result.begin(), result.end(), xorshf96_generator<T>{seed});
Paul's avatar
Paul committed
62
63
64
    return result;
}

Paul's avatar
Paul committed
65
argument generate_argument(shape s, unsigned long seed = 0);
Paul's avatar
Paul committed
66

Paul's avatar
Paul committed
67
68
69
literal generate_literal(shape s, unsigned long seed = 0);

literal abs(literal l);
Paul's avatar
Paul committed
70
71
72
73

} // namespace migraph

#endif