generate.hpp 1.69 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
    unsigned long seed = 0;
Paul's avatar
Paul committed
37
38
    unsigned long x    = 123456789;
    unsigned long y    = 362436069;
Paul's avatar
Paul committed
39
    unsigned long z    = 521288629ULL ^ seed;
40

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

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

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

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

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

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

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

} // namespace migraph

#endif