"docs/source/reference/experiment_config.rst" did not exist on "5d0251fc499be130cafc777dd28ee17556b53b43"
hip.cpp 8.69 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2015-2022 Advanced Micro Devices, Inc. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
Paul's avatar
Paul committed
24

Paul's avatar
Paul committed
25
26
#include <migraphx/gpu/hip.hpp>
#include <migraphx/manage_ptr.hpp>
27
#include <migraphx/register_op.hpp>
28
#include <migraphx/gpu/context.hpp>
29
#include <migraphx/gpu/device/contiguous.hpp>
Paul's avatar
Paul committed
30
#include <miopen/miopen.h>
31
32
#include <memory>
#include <mutex>
Paul's avatar
Paul committed
33
34
#include <vector>

Paul's avatar
Paul committed
35
namespace migraphx {
Paul's avatar
Paul committed
36
inline namespace MIGRAPHX_INLINE_NS {
Paul's avatar
Paul committed
37
namespace gpu {
Paul's avatar
Paul committed
38

39
MIGRAPHX_REGISTER_OP(hip_allocate)
40
MIGRAPHX_REGISTER_OP(hip_sync_stream)
41
42
43
44
45
46
MIGRAPHX_REGISTER_OP(hip_copy_to_gpu)
MIGRAPHX_REGISTER_OP(hip_copy_from_gpu)
MIGRAPHX_REGISTER_OP(hip_copy)
MIGRAPHX_REGISTER_OP(hip_allocate_memory)
MIGRAPHX_REGISTER_OP(hip_copy_literal)

47
48
using hip_ptr      = MIGRAPHX_MANAGE_PTR(void, hipFree);
using hip_host_ptr = MIGRAPHX_MANAGE_PTR(void, hipHostUnregister);
Paul's avatar
Paul committed
49

Paul's avatar
Paul committed
50
std::string hip_error(int error) { return hipGetErrorString(static_cast<hipError_t>(error)); }
Paul's avatar
Paul committed
51

52
53
54
55
56
57
58
59
60
bool is_device_ptr(const void* ptr)
{
    hipPointerAttribute_t attr;
    auto status = hipPointerGetAttributes(&attr, ptr);
    if(status != hipSuccess)
        return false;
    return attr.memoryType == hipMemoryTypeDevice;
}

Paul's avatar
Paul committed
61
std::size_t get_available_gpu_memory()
Paul's avatar
Paul committed
62
{
Paul's avatar
Paul committed
63
64
    size_t free;
    size_t total;
Paul's avatar
Paul committed
65
    auto status = hipMemGetInfo(&free, &total);
Paul's avatar
Paul committed
66
    if(status != hipSuccess)
Paul's avatar
Paul committed
67
        MIGRAPHX_THROW("Failed getting available memory: " + hip_error(status));
Paul's avatar
Paul committed
68
69
70
    return free;
}

71
72
73
74
75
76
77
78
79
void* get_device_ptr(void* hptr)
{
    void* result = nullptr;
    auto status  = hipHostGetDevicePointer(&result, hptr, 0);
    if(status != hipSuccess)
        MIGRAPHX_THROW("Failed getting device pointer: " + hip_error(status));
    return result;
}

80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
struct host_ptr_cache
{
    std::unordered_map<void*, std::weak_ptr<void>> cache;
    std::mutex m;
    std::shared_ptr<void> get(void* ptr)
    {
        std::lock_guard<std::mutex> lock(m);
        auto it = cache.find(ptr);
        if(it != cache.end())
            return it->second.lock();
        return nullptr;
    }

    void put(const std::shared_ptr<void>& p)
    {
        std::lock_guard<std::mutex> lock(m);
        cache[p.get()] = p;
    }
};

static host_ptr_cache& get_host_ptr_cache()
{
    static host_ptr_cache cache;
    return cache;
}

std::shared_ptr<void> allocate_gpu(std::size_t sz, bool host = false)
Paul's avatar
Paul committed
107
108
{
    if(sz > get_available_gpu_memory())
Paul's avatar
Paul committed
109
        MIGRAPHX_THROW("Memory not available to allocate buffer: " + std::to_string(sz));
110
111
    void* alloc_ptr = nullptr;
    auto status     = host ? hipHostMalloc(&alloc_ptr, sz) : hipMalloc(&alloc_ptr, sz);
Paul's avatar
Paul committed
112
113
114
    if(status != hipSuccess)
    {
        if(host)
Paul's avatar
Paul committed
115
            MIGRAPHX_THROW("Gpu allocation failed: " + hip_error(status));
Paul's avatar
Paul committed
116
        else
117
            return allocate_gpu(sz, true);
Paul's avatar
Paul committed
118
    }
119
120
121
122
123
124
125
    assert(alloc_ptr != nullptr);
    std::shared_ptr<void> result = share(hip_ptr{alloc_ptr});
    if(host)
    {
        get_host_ptr_cache().put(result);
    }
    return result;
Paul's avatar
Paul committed
126
127
}

128
std::shared_ptr<void> register_on_gpu(void* ptr, std::size_t sz)
129
{
130
131
132
133
134
    std::shared_ptr<void> result = get_host_ptr_cache().get(ptr);
    if(result)
    {
        return result;
    }
135
136
137
    auto status = hipHostRegister(ptr, sz, hipHostRegisterMapped);
    if(status != hipSuccess)
        MIGRAPHX_THROW("Gpu register failed: " + hip_error(status));
138
139
140
    result = share(hip_host_ptr{ptr});
    get_host_ptr_cache().put(result);
    return result;
141
142
}

Paul's avatar
Paul committed
143
144
145
template <class T>
std::vector<T> read_from_gpu(const void* x, std::size_t sz)
{
146
    gpu_sync();
Paul's avatar
Paul committed
147
    std::vector<T> result(sz);
148
149
    assert(not is_device_ptr(result.data()));
    assert(is_device_ptr(x));
Paul's avatar
Paul committed
150
151
    auto status = hipMemcpy(result.data(), x, sz * sizeof(T), hipMemcpyDeviceToHost);
    if(status != hipSuccess)
Paul's avatar
Paul committed
152
        MIGRAPHX_THROW("Copy from gpu failed: " + hip_error(status)); // NOLINT
Paul's avatar
Paul committed
153
154
155
    return result;
}

156
std::shared_ptr<void> write_to_gpu(const void* x, std::size_t sz, bool host = false)
Paul's avatar
Paul committed
157
{
158
    gpu_sync();
Paul's avatar
Paul committed
159
    auto result = allocate_gpu(sz, host);
160
161
    assert(is_device_ptr(result.get()));
    assert(not is_device_ptr(x));
Paul's avatar
Paul committed
162
163
    auto status = hipMemcpy(result.get(), x, sz, hipMemcpyHostToDevice);
    if(status != hipSuccess)
Paul's avatar
Paul committed
164
        MIGRAPHX_THROW("Copy to gpu failed: " + hip_error(status));
Paul's avatar
Paul committed
165
166
167
    return result;
}

Paul's avatar
Paul committed
168
169
170
171
172
173
174
175
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);
}

Paul's avatar
Paul committed
176
argument allocate_gpu(const shape& s, bool host)
Paul's avatar
Paul committed
177
{
178
    auto p = allocate_gpu(s.bytes() + 1, host);
Paul's avatar
Paul committed
179
180
181
    return {s, [p]() mutable { return reinterpret_cast<char*>(p.get()); }};
}

182
183
184
argument register_on_gpu(const argument& arg)
{
    auto arg_shared = arg.share();
185
    auto p          = register_on_gpu(arg_shared.data(), arg_shared.get_shape().bytes());
186
187
    auto s          = arg_shared.get_shape();
    return {s, [p, a = std::move(arg_shared)]() mutable { return get_device_ptr(p.get()); }};
188
}
189

Paul's avatar
Paul committed
190
argument to_gpu(const argument& arg, bool host)
Paul's avatar
Paul committed
191
{
192
    auto p = write_to_gpu(arg.data(), arg.get_shape().bytes(), host);
193
    return {arg.get_shape(), p};
Paul's avatar
Paul committed
194
195
}

Paul's avatar
Paul committed
196
argument from_gpu(const argument& arg)
Paul's avatar
Paul committed
197
{
Paul's avatar
Paul committed
198
    argument result;
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
    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));
            // cppcheck-suppress returnDanglingLifetime
            result = {x.get_shape(), [v]() mutable { return v.data(); }};
        },
        [&](const auto& xs) {
            std::vector<argument> args;
            std::transform(xs.begin(), xs.end(), std::back_inserter(args), [&](auto x) {
                return from_gpu(x);
            });
            result = argument{args};
        });

Paul's avatar
Paul committed
214
215
216
    return result;
}

Paul's avatar
Paul committed
217
218
219
220
void set_device(std::size_t id)
{
    auto status = hipSetDevice(id);
    if(status != hipSuccess)
Paul's avatar
Paul committed
221
        MIGRAPHX_THROW("Error setting device");
Paul's avatar
Paul committed
222
223
}

224
225
226
227
228
229
void gpu_sync()
{
    auto status = hipDeviceSynchronize();
    if(status != hipSuccess)
        MIGRAPHX_THROW("hip device synchronization failed: " + hip_error(status));
}
Paul's avatar
Paul committed
230

231
232
void gpu_sync(const context& ctx) { ctx.finish(); }

233
void hip_async_copy(context& ctx, const argument& src, const argument& dst, hipMemcpyKind kind)
mei-ye's avatar
mei-ye committed
234
{
235
236
237
    std::size_t src_size = src.get_shape().bytes();
    std::size_t dst_size = dst.get_shape().bytes();
    if(src_size > dst_size)
Paul's avatar
Paul committed
238
        MIGRAPHX_THROW("Not enough memory available in destination to do copy");
239
    auto status = hipMemcpyAsync(dst.data(), src.data(), src_size, kind, ctx.get_stream().get());
240
    if(status != hipSuccess)
241
        MIGRAPHX_THROW("Gpu copy failed: " + hip_error(status));
mei-ye's avatar
mei-ye committed
242
}
243

244
245
void gpu_copy(context& ctx, const argument& src, const argument& dst)
{
246
247
248
249
250
251
252
    // Workaround: Use contiguous as hip's memcpy is broken
    device::contiguous(ctx.get_stream().get(), dst, src);
    // hip_async_copy(ctx, src, dst, hipMemcpyDeviceToDevice);
}

void copy_to_gpu(context& ctx, const argument& src, const argument& dst)
{
Shucai Xiao's avatar
Shucai Xiao committed
253
254
255
256
257
258
259
260
    if(src.get_shape() == dst.get_shape() and dst.get_shape().packed())
    {
        hip_async_copy(ctx, src, dst, hipMemcpyHostToDevice);
    }
    else
    {
        gpu_copy(ctx, register_on_gpu(src), dst);
    }
261
262
263
264
}

void copy_from_gpu(context& ctx, const argument& src, const argument& dst)
{
Shucai Xiao's avatar
Shucai Xiao committed
265
266
267
268
269
270
271
272
    if(src.get_shape() == dst.get_shape() and dst.get_shape().packed())
    {
        hip_async_copy(ctx, src, dst, hipMemcpyDeviceToHost);
    }
    else
    {
        gpu_copy(ctx, src, register_on_gpu(dst));
    }
273
274
275
276
277
}

argument get_preallocation(context& ctx, const std::string& id)
{
    return ctx.get_current_device().preallocations.at(id);
278
279
}

280
281
282
283
284
void store_preallocated_param(context& ctx, const std::string& id, const argument& a)
{
    ctx.get_current_device().preallocations[id] = a;
}

285
// clang-format off
Paul's avatar
Paul committed
286
} // namespace gpu
Paul's avatar
Paul committed
287
} // namespace MIGRAPHX_INLINE_NS
Paul's avatar
Paul committed
288
} // namespace migraphx