hip.cpp 1.69 KB
Newer Older
Paul's avatar
Paul committed
1
2
3

#include <rtg/miopen/hip.hpp>

Paul's avatar
Paul committed
4
5
6
7
8
#include <rtg/manage_ptr.hpp>
#include <miopen/miopen.h>

#include <vector>

Paul's avatar
Paul committed
9
10
11
namespace rtg {
namespace miopen {

Paul's avatar
Paul committed
12
13
14
using hip_ptr = RTG_MANAGE_PTR(void, hipFree);

hip_ptr allocate_gpu(std::size_t sz)
Paul's avatar
Paul committed
15
16
17
18
19
20
21
{
    void* result;
    // TODO: Check status
    hipMalloc(&result, sz);
    return hip_ptr{result};
}

Paul's avatar
Paul committed
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
template <class T>
hip_ptr write_to_gpu(const T& x)
{
    using type = typename T::value_type;
    auto size  = x.size() * sizeof(type);
    return write_to_gpu(x.data(), size);
}

template <class T>
std::vector<T> read_from_gpu(const void* x, std::size_t sz)
{
    std::vector<T> result(sz);
    // TODO: Check status
    hipMemcpy(result.data(), x, sz * sizeof(T), hipMemcpyDeviceToHost);
    return result;
}

Paul's avatar
Paul committed
39
40
hip_ptr write_to_gpu(const void* x, std::size_t sz)
{
Paul's avatar
Paul committed
41
    auto result = allocate_gpu(sz);
Paul's avatar
Paul committed
42
43
44
45
46
    // TODO: Check status
    hipMemcpy(result.get(), x, sz, hipMemcpyHostToDevice);
    return result;
}

Paul's avatar
Paul committed
47
48
49
50
51
52
rtg::argument allocate_gpu(rtg::shape s)
{
    auto p = share(allocate_gpu(s.bytes()));
    return {s, [p]() mutable { return reinterpret_cast<char*>(p.get()); }};
}

Paul's avatar
Paul committed
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
rtg::argument to_gpu(rtg::argument arg)
{
    auto p = share(write_to_gpu(arg.data(), arg.get_shape().bytes()));
    return {arg.get_shape(), [p]() mutable { return reinterpret_cast<char*>(p.get()); }};
}

rtg::argument from_gpu(rtg::argument arg)
{
    rtg::argument result;
    arg.visit([&](auto x) {
        using type = typename decltype(x)::value_type;
        auto v     = read_from_gpu<type>(arg.data(), x.get_shape().bytes() / sizeof(type));
        result     = {x.get_shape(), [v]() mutable { return reinterpret_cast<char*>(v.data()); }};
    });
    return result;
}

} // namespace miopen

} // namespace rtg