flush_cache.hpp 12.8 KB
Newer Older
ltqin's avatar
ltqin committed
1
2
3
4
5
6
// SPDX-License-Identifier: MIT
// Copyright (c) 2018-2024, Advanced Micro Devices, Inc. All rights reserved.

#pragma once

#include <hip/hip_runtime.h>
7
#include <hip/hip_ext.h>
ltqin's avatar
ltqin committed
8
#include <set>
9
#include <vector>
ltqin's avatar
ltqin committed
10
11
12
13
14
15
16
17

#include "ck/ck.hpp"
#include "ck/stream_config.hpp"
#include "ck/host_utility/hip_check_error.hpp"
#include "ck/utility/flush_icache.hpp"
namespace ck {
namespace utility {

18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
template <typename Argument, typename DsDataType>
struct RotatingMemWrapperMultiD
{
    static constexpr index_t NumDs = DsDataType::Size();

    using ADataType     = decltype(Argument::p_a_grid);
    using BDataType     = decltype(Argument::p_b_grid);
    using DsGridPointer = decltype(Argument::p_ds_grid);

    RotatingMemWrapperMultiD() = delete;
    RotatingMemWrapperMultiD(Argument& arg_,
                             std::size_t rotating_count_,
                             std::size_t size_a_,
                             std::size_t size_b_,
                             std::array<std::size_t, NumDs> size_ds_)
        : arg(arg_),
          rotating_count(rotating_count_),
          size_a(size_a_),
          size_b(size_b_),
          size_ds(size_ds_)
    {
        p_a_grids.push_back(arg.p_a_grid);
        p_b_grids.push_back(arg.p_b_grid);
        p_ds_grids.push_back(arg.p_ds_grid);
        for(size_t i = 1; i < rotating_count; i++)
        {
            {
                void* pADeviceBuf;
46
47
                HIP_CHECK_ERROR(hipMalloc(static_cast<void**>(&pADeviceBuf), size_a_));
                HIP_CHECK_ERROR(hipMemcpy(static_cast<void*>(pADeviceBuf),
48
49
50
51
52
53
54
55
                                          const_cast<void*>(p_a_grids[0]),
                                          size_a_,
                                          hipMemcpyDeviceToDevice));
                p_a_grids.push_back(pADeviceBuf);
            }

            {
                void* pBDeviceBuf;
56
57
                HIP_CHECK_ERROR(hipMalloc(static_cast<void**>(&pBDeviceBuf), size_b_));
                HIP_CHECK_ERROR(hipMemcpy(static_cast<void*>(pBDeviceBuf),
58
59
60
61
62
63
64
65
66
67
68
                                          const_cast<void*>(p_b_grids[0]),
                                          size_b_,
                                          hipMemcpyDeviceToDevice));
                p_b_grids.push_back(pBDeviceBuf);
            }

            {

                DsGridPointer ds_buffer;
                static_for<0, NumDs, 1>{}([&](auto j) {
                    void* pDDeviceBuf;
69
70
                    HIP_CHECK_ERROR(hipMalloc(static_cast<void**>(&pDDeviceBuf), size_ds_[j]));
                    HIP_CHECK_ERROR(hipMemcpy(static_cast<void*>(pDDeviceBuf),
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
                                              static_cast<const void*>(p_ds_grids[0][j]),
                                              size_ds_[j],
                                              hipMemcpyDeviceToDevice));

                    using DDataType = remove_cvref_t<tuple_element_t<j.value, DsDataType>>;

                    ds_buffer(j) = static_cast<const DDataType*>(pDDeviceBuf);
                });

                p_ds_grids.push_back(ds_buffer);
            }
        }
    }

    void Next()
    {
        if(rotating_count > 1)
        {
            std::size_t idx = iter++ % rotating_count;
            arg.p_a_grid    = reinterpret_cast<ADataType>(p_a_grids[idx]);
            arg.p_b_grid    = reinterpret_cast<BDataType>(p_b_grids[idx]);
            arg.p_ds_grid   = p_ds_grids[idx];
        }
    }
    void Print()
    {
aska-0096's avatar
aska-0096 committed
97
        std::cout << "RotatingMemWrapperMultiD: { size_a: " << size_a << ", size_b: " << size_b;
98
99
        static_for<0, NumDs, 1>{}(
            [&](auto j) { std::cout << ", size_d" << j.value << ": " << size_ds[j]; });
aska-0096's avatar
aska-0096 committed
100
        std::cout << ", rotating_count: " << rotating_count << "}" << std::endl;
101
102
103
104
105
106
107
108
109
110
111
112
113
    }
    ~RotatingMemWrapperMultiD()
    {
        if(rotating_count > 1)
        {
            // restore ptr
            arg.p_a_grid  = reinterpret_cast<ADataType>(p_a_grids[0]);
            arg.p_b_grid  = reinterpret_cast<BDataType>(p_b_grids[0]);
            arg.p_ds_grid = p_ds_grids[0];

            // free device mem
            for(size_t i = 1; i < rotating_count; i++)
            {
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
                try
                {
                    HIP_CHECK_ERROR(hipFree(const_cast<void*>(p_a_grids[i])));
                }
                catch(std::runtime_error& re)
                {
                    std::cerr << re.what() << std::endl;
                }

                try
                {
                    HIP_CHECK_ERROR(hipFree(const_cast<void*>(p_b_grids[i])));
                }
                catch(std::runtime_error& re)
                {
                    std::cerr << re.what() << std::endl;
                }
131
132
133

                static_for<0, NumDs, 1>{}([&](auto j) {
                    using DDataType = remove_cvref_t<tuple_element_t<j.value, DsDataType>>;
134
135
136
137
138
139
140
141
142
                    try
                    {
                        HIP_CHECK_ERROR(
                            hipFree(static_cast<void*>(const_cast<DDataType*>(p_ds_grids[i][j]))));
                    }
                    catch(std::runtime_error& re)
                    {
                        std::cerr << re.what() << std::endl;
                    }
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
                });
            }
        }
    }

    private:
    Argument& arg;
    std::size_t iter                       = 0;
    std::size_t rotating_count             = 1;
    std::size_t size_a                     = 0;
    std::size_t size_b                     = 0;
    std::array<std::size_t, NumDs> size_ds = {0};
    std::vector<const void*> p_a_grids;
    std::vector<const void*> p_b_grids;
    std::vector<DsGridPointer> p_ds_grids;
};

ltqin's avatar
ltqin committed
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
template <typename Argument>
struct RotatingMemWrapper
{
    using ADataType = decltype(Argument::p_a_grid);
    using BDataType = decltype(Argument::p_b_grid);

    RotatingMemWrapper() = delete;
    RotatingMemWrapper(Argument& arg_,
                       std::size_t rotating_count_,
                       std::size_t size_a_,
                       std::size_t size_b_)
        : arg(arg_), rotating_count(rotating_count_), size_a(size_a_), size_b(size_b_)
    {
        p_a_grids.push_back(arg.p_a_grid);
        p_b_grids.push_back(arg.p_b_grid);
        for(size_t i = 1; i < rotating_count; i++)
        {
            {
                void* pADeviceBuf;
179
180
                HIP_CHECK_ERROR(hipMalloc(static_cast<void**>(&pADeviceBuf), size_a_));
                HIP_CHECK_ERROR(hipMemcpy(static_cast<void*>(pADeviceBuf),
ltqin's avatar
ltqin committed
181
182
183
184
185
186
187
188
                                          const_cast<void*>(p_a_grids[0]),
                                          size_a_,
                                          hipMemcpyDeviceToDevice));
                p_a_grids.push_back(pADeviceBuf);
            }

            {
                void* pBDeviceBuf;
189
190
                HIP_CHECK_ERROR(hipMalloc(static_cast<void**>(&pBDeviceBuf), size_b_));
                HIP_CHECK_ERROR(hipMemcpy(static_cast<void*>(pBDeviceBuf),
ltqin's avatar
ltqin committed
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
                                          const_cast<void*>(p_b_grids[0]),
                                          size_b_,
                                          hipMemcpyDeviceToDevice));
                p_b_grids.push_back(pBDeviceBuf);
            }
        }
    }

    void Next()
    {
        if(rotating_count > 1)
        {
            std::size_t idx = iter++ % rotating_count;
            arg.p_a_grid    = reinterpret_cast<ADataType>(p_a_grids[idx]);
            arg.p_b_grid    = reinterpret_cast<BDataType>(p_b_grids[idx]);
        }
    }
    void Print()
    {
        std::cout << "RotatingMemWrapper: { size_a: " << size_a << ", size_b: " << size_b
                  << ", rotating_count: " << rotating_count << "}" << std::endl;
    }
    ~RotatingMemWrapper()
    {
        if(rotating_count > 1)
        {
            // restore ptr
            arg.p_a_grid = reinterpret_cast<ADataType>(p_a_grids[0]);
            arg.p_b_grid = reinterpret_cast<BDataType>(p_b_grids[0]);

            // free device mem
            for(size_t i = 1; i < rotating_count; i++)
            {
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
                try
                {
                    HIP_CHECK_ERROR(hipFree(const_cast<void*>(p_a_grids[i])));
                }
                catch(std::runtime_error& re)
                {
                    std::cerr << re.what() << std::endl;
                }

                try
                {
                    HIP_CHECK_ERROR(hipFree(const_cast<void*>(p_b_grids[i])));
                }
                catch(std::runtime_error& re)
                {
                    std::cerr << re.what() << std::endl;
                }
ltqin's avatar
ltqin committed
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
            }
        }
    }

    private:
    Argument& arg;
    std::size_t iter           = 0;
    std::size_t rotating_count = 1;
    std::size_t size_a         = 0;
    std::size_t size_b         = 0;
    std::vector<const void*> p_a_grids;
    std::vector<const void*> p_b_grids;
};

inline void flush_icache()
{
    hipDeviceProp_t deviceProps;
258
    HIP_CHECK_ERROR(hipGetDeviceProperties(&deviceProps, 0));
ltqin's avatar
ltqin committed
259
260
261
    int32_t gpu_block3 = deviceProps.multiProcessorCount * 60;

    ck::flush_icache<<<dim3(gpu_block3), dim3(64), 0, nullptr>>>();
262
    HIP_CHECK_ERROR(hipGetLastError());
ltqin's avatar
ltqin committed
263
264
}
// if TimePrePress == false, return time does not include preprocess's time
aska-0096's avatar
aska-0096 committed
265
template <bool TimePreprocess, typename... Args, typename F, typename PreProcessFunc>
ltqin's avatar
ltqin committed
266
267
268
269
270
271
float launch_and_time_kernel_with_preprocess(const StreamConfig& stream_config,
                                             PreProcessFunc preprocess,
                                             F kernel,
                                             dim3 grid_dim,
                                             dim3 block_dim,
                                             std::size_t lds_byte,
272
                                             Args... args)
ltqin's avatar
ltqin committed
273
274
{
#if CK_TIME_KERNEL
chenjun's avatar
chenjun committed
275
#define MEDIAN 0
ltqin's avatar
ltqin committed
276
277
    if(stream_config.time_kernel_)
    {
278
        if(ck::EnvIsEnabled(CK_ENV(CK_LOGGING)))
279
        {
280
            printf("%s: grid_dim {%u, %u, %u}, block_dim {%u, %u, %u} \n",
281
282
283
284
285
286
287
288
289
290
                   __func__,
                   grid_dim.x,
                   grid_dim.y,
                   grid_dim.z,
                   block_dim.x,
                   block_dim.y,
                   block_dim.z);

            printf("Warm up %d times\n", stream_config.cold_niters_);
        }
ltqin's avatar
ltqin committed
291
292
293
        // warm up
        for(int i = 0; i < stream_config.cold_niters_; ++i)
        {
aska-0096's avatar
aska-0096 committed
294
            kernel<<<grid_dim, block_dim, lds_byte, stream_config.stream_id_>>>(args...);
295
            HIP_CHECK_ERROR(hipGetLastError());
ltqin's avatar
ltqin committed
296
297
298
299
300
301
302
        }

        const int nrepeat = stream_config.nrepeat_;
        if(nrepeat == 0)
        {
            return 0.0;
        }
303
        if(ck::EnvIsEnabled(CK_ENV(CK_LOGGING)))
304
305
306
        {
            printf("Start running %d times...\n", nrepeat);
        }
ltqin's avatar
ltqin committed
307
308
309
310
311
312

#if MEDIAN
        std::set<float> times;
#else
        float total_time = 0;
#endif
chenjun's avatar
chenjun committed
313
314
        hipEvent_t start, stop;

315
316
        HIP_CHECK_ERROR(hipEventCreate(&start));
        HIP_CHECK_ERROR(hipEventCreate(&stop));
chenjun's avatar
chenjun committed
317

ltqin's avatar
ltqin committed
318
319
        for(int i = 0; i < nrepeat; ++i)
        {
320
            preprocess();
ltqin's avatar
ltqin committed
321
322

            // run real kernel
323
324
325
326
327
328
329
330
            hipExtLaunchKernelGGL(kernel,
                                  grid_dim,
                                  block_dim,
                                  lds_byte,
                                  stream_config.stream_id_,
                                  start,
                                  stop,
                                  0,
aska-0096's avatar
aska-0096 committed
331
                                  args...);
332
            HIP_CHECK_ERROR(hipGetLastError());
ltqin's avatar
ltqin committed
333
334
            // end real kernel

335
336
337
338
339
340
341
342
343
344
            HIP_CHECK_ERROR(hipEventRecord(stop, stream_config.stream_id_));
            HIP_CHECK_ERROR(hipEventSynchronize(stop));

            float cur_time = 0;
            HIP_CHECK_ERROR(hipEventElapsedTime(&cur_time, start, stop));
#if MEDIAN
            times.insert(cur_time);
#else
            total_time += cur_time;
#endif
ltqin's avatar
ltqin committed
345
        }
346
347
348
349
350
351
352
353
354
        hip_check_error(hipEventRecord(stop, stream_config.stream_id_));
        hip_check_error(hipEventSynchronize(stop));
        float cur_time = 0;
        hip_check_error(hipEventElapsedTime(&cur_time, start, stop));
#if MEDIAN
        times.insert(cur_time);
#else
        total_time += cur_time;
#endif
ltqin's avatar
ltqin committed
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369

#if MEDIAN
        auto mid = times.begin();
        std::advance(mid, (nrepeat - 1) / 2);
        if(nrepeat % 2 == 1)
        {
            return *mid;
        }
        else
        {
            auto mid_next = mid;
            std::advance(mid_next, 1);
            return (*mid + *mid_next) / 2;
        }
#else
aska-0096's avatar
aska-0096 committed
370
        return total_time / nrepeat;
ltqin's avatar
ltqin committed
371
372
373
374
375
#endif
    }
    else
    {
        preprocess();
aska-0096's avatar
aska-0096 committed
376
        kernel<<<grid_dim, block_dim, lds_byte, stream_config.stream_id_>>>(args...);
377
        HIP_CHECK_ERROR(hipGetLastError());
ltqin's avatar
ltqin committed
378
379
380
381

        return 0;
    }
#else
aska-0096's avatar
aska-0096 committed
382
    kernel<<<grid_dim, block_dim, lds_byte, stream_config.stream_id_>>>(args...);
383
    HIP_CHECK_ERROR(hipGetLastError());
ltqin's avatar
ltqin committed
384
385
386
387
388
389
390

    return 0;
#endif
}

} // namespace utility
} // namespace ck