gemm_impl.cpp 14.3 KB
Newer Older
1
2
3
/*
 * The MIT License (MIT)
 *
4
 * Copyright (c) 2015-2023 Advanced Micro Devices, Inc. All rights reserved.
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
 *
 * 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.
 */
24
#include <rocblas/rocblas.h>
25
#include <migraphx/gpu/gemm_impl.hpp>
26
#include <migraphx/reduce_dims.hpp>
27
#include <migraphx/permutation.hpp>
Shucai Xiao's avatar
Shucai Xiao committed
28

29
30
31
32
33
34
// #include <migraphx/config.hpp>
// #include <migraphx/gpu/context.hpp>
#include <migraphx/generate.hpp>
#include <migraphx/operation.hpp>
#include <migraphx/time.hpp>

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

39
rocblas_datatype get_type(shape::type_t type)
Shucai Xiao's avatar
Shucai Xiao committed
40
{
41
    switch(type)
42
    {
43
44
45
46
47
48
49
    case shape::double_type: return rocblas_datatype_f64_r;
    case shape::float_type: return rocblas_datatype_f32_r;
    case shape::half_type: return rocblas_datatype_f16_r;
    case shape::int8_type: return rocblas_datatype_i8_r;
    case shape::uint8_type: return rocblas_datatype_u8_r;
    case shape::int32_type: return rocblas_datatype_i32_r;
    case shape::uint32_type: return rocblas_datatype_u32_r;
Paul Fultz II's avatar
Paul Fultz II committed
50
    case shape::tuple_type:
51
    case shape::bool_type:
52
53
54
55
    case shape::uint16_type:
    case shape::int16_type:
    case shape::int64_type:
    case shape::uint64_type: MIGRAPHX_THROW("ROCBLAS_GEMM: data type not supported!");
56
    }
57
58

    MIGRAPHX_THROW("ROCBLAS_GEMM: data type not supported!");
59
60
}

61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
void blas_shape(const shape& s)
{
    if(s.lens().size() < 2)
        return;
    if(std::none_of(s.strides().end() - 2, s.strides().end(), [&](auto i) { return i == 1; }))
        MIGRAPHX_THROW("GPU_GEMM: needs to have one matrix stride as 1");
    if(s.lens().size() < 3)
        return;
    shape batch_shape{s.type(),
                      {s.lens().begin(), s.lens().end() - 2},
                      {s.strides().begin(), s.strides().end() - 2}};
    auto batch_shapes = reduce_dims({batch_shape});
    if(batch_shapes.front().lens().size() != 1)
        MIGRAPHX_THROW("GPU_GEMM: Batch dimension is not collapsible");
}

77
78
79
80
81
82
83
84
85
86
87
88
89
shape transpose_batch(const shape& s, unsigned trans_batch)
{
    if(trans_batch == 0)
        return s;
    if(s.lens().size() < 3)
        return s;
    auto batch = s.lens().size() - 3;
    std::vector<int64_t> perm(s.lens().size());
    std::iota(perm.begin(), perm.end(), 0);
    std::swap(perm[batch], perm[batch + trans_batch]);
    return shape::from_permutation(s.type(), s.lens(), perm);
}

90
91
92
93
94
95
96
97
98
template <class R, class... Ts, class... Us>
R rocblas_invoke(R (*f)(Ts...), Us... xs)
{
    if constexpr(sizeof...(Ts) == sizeof...(Us))
        return f(xs...);
    else
        return f(xs..., nullptr, nullptr);
}

99
100
101
102
103
104
105
106
107
108
109
110
static bool is_transposed(const shape& s)
{
    if(not s.transposed())
        return false;
    return s.strides().back() != 1;
}

static rocblas_int get_batch_stride(const argument& a)
{
    return a.get_shape().strides()[a.get_shape().strides().size() - 3];
}

111

112
template <class T>
Shucai Xiao's avatar
Shucai Xiao committed
113
114
115
116
117
void gemm_impl(context& ctx,
               const shape& output_shape,
               const std::vector<argument>& args,
               T alpha,
               T beta,
118
119
               bool int8_x4_format,
               bool compute_fp32)
Shucai Xiao's avatar
Shucai Xiao committed
120
{
121
    output_shape.visit_type([&](auto as) {   // TODO:  not needed?
122
    (void)as;
Shucai Xiao's avatar
Shucai Xiao committed
123
        auto out_lens   = output_shape.lens();
Shucai Xiao's avatar
Shucai Xiao committed
124
125
        auto num_matrices = std::accumulate(
            out_lens.rbegin() + 2, out_lens.rend(), std::size_t{1}, std::multiplies<std::size_t>());
126
        if(num_matrices == 1 or (num_matrices > 1 and get_batch_stride(args[1]) == 0))
Shucai Xiao's avatar
Shucai Xiao committed
127
        {
128
129
130
131
            // If the batch dimension of B is broadcasted, then we can
            // multiply m by the batch_size and use rocblas_gemm_ex
            // instead of rocblas_gemm_strided_batched_ex.

Shucai Xiao's avatar
Shucai Xiao committed
132
            // the rocblas_gemm API handles inputs and output matrices as
Shucai Xiao's avatar
Shucai Xiao committed
133
134
135
            // column-major format. When doing a C = A * B, we actually do
            // C^T = (B^T) * (A^T). That is the reason we input args[1] as
            // A and args[0] as B in calling the rocblas_gemm.
136
            auto to_invoke = 
137
138
139
140
            create_gemm_args(ctx, ROCBLAS_CALL::ROCBLAS_GEMM_EX, output_shape, args, 
                                              alpha, beta, int8_x4_format, compute_fp32);
            // rocblas_invoke(&rocblas_gemm_ex,
            //                to_invoke);
Shucai Xiao's avatar
Shucai Xiao committed
141
142
143
        }
        else
        {
144
            auto to_invoke = 
145
146
147
148
            create_gemm_args(ctx, ROCBLAS_CALL::ROCBLAS_GEMM_STRIDED_BATCHED_EX, 
                                              output_shape, args, alpha, beta, int8_x4_format, compute_fp32);
            // rocblas_invoke(&rocblas_gemm_strided_batched_ex,
            //               to_invoke);
Shucai Xiao's avatar
Shucai Xiao committed
149
150
        }
    });
151
}
Shucai Xiao's avatar
Shucai Xiao committed
152

153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
std::vector<argument> generate_arguments(const std::vector<shape>& shapes, unsigned long seed = 0)
{
    std::vector<argument> args;
    std::transform(shapes.begin(), shapes.end(), std::back_inserter(args), [&](auto& s) {
        return to_gpu(generate_argument(s, seed++));
    });
    return args;
}

// from perf.cpp
using milliseconds = std::chrono::duration<double, std::milli>;
std::pair<double, double>
time_op(context& ictx, operation op, const std::vector<shape>& inputs, int n)
{

    // TODO: Use std::ref
    migraphx::context ctx = ictx;
    auto& gctx            = any_cast<migraphx::gpu::context>(ctx);
    auto output           = op.compute_shape(inputs);
    // op.finalize(ctx, output, inputs);
    auto args = generate_arguments(inputs);
    auto run  = [&] {
        op.compute(ctx, output, args);
        ctx.finish();
    };
    gctx.enable_perf_measurement();
    run();
    double host_time   = 0.0;
    double device_time = 0.0;
    for(auto i : range(n))
    {
        (void)i;
        host_time += time<milliseconds>(run);
        device_time += gctx.get_elapsed_ms();
    }
    return std::make_pair(host_time / n, device_time / n);
}

191
192
193
194
void gemm(context& ctx,
          const shape& output_shape,
          const std::vector<argument>& args,
          float alpha,
Shucai Xiao's avatar
Shucai Xiao committed
195
          float beta,
196
197
          bool int8_x4_format,
          bool compute_fp32)
198
{
199
    gemm_impl(ctx, output_shape, args, alpha, beta, int8_x4_format, compute_fp32);
200
201
202
203
204
205
}

void gemm(context& ctx,
          const shape& output_shape,
          const std::vector<argument>& args,
          int32_t alpha,
Shucai Xiao's avatar
Shucai Xiao committed
206
          int32_t beta,
207
208
          bool int8_x4_format,
          bool compute_fp32)
209
{
210
    gemm_impl(ctx, output_shape, args, alpha, beta, int8_x4_format, compute_fp32);
Shucai Xiao's avatar
Shucai Xiao committed
211
212
}

213
214
215
216

/**
 * Create a list of the arguments needed for rocBLAS GEMM calls, from
 * a set of MigraphX arguments.
217
 */
218
template <class T>
219
static auto create_gemm_args(context& ctx,
220
221
222
223
224
225
226
                      ROCBLAS_CALL rocblas_call,
                      const shape& output_shape,
                      const std::vector<argument>& inputs,
                      T alpha,
                      T beta,
                      bool int8_x4_format,
                      bool compute_fp32)
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
{
    const bool is_3inputs = (inputs.size() == 4);
    if(not is_3inputs)
    {
        beta = 0;
    }

    bool transa     = is_transposed(inputs[0].get_shape());
    bool transb     = is_transposed(inputs[1].get_shape());
    auto n_dim      = output_shape.lens().size();
    auto dim_1      = n_dim - 1;
    auto dim_0      = n_dim - 2;
    rocblas_int lda = inputs[0].get_shape().strides()[transa ? dim_1 : dim_0];
    rocblas_int ldb = inputs[1].get_shape().strides()[transb ? dim_1 : dim_0];
    rocblas_int ldc = inputs[2].get_shape().strides()[dim_0];
    rocblas_int ldd = is_3inputs ? inputs[3].get_shape().strides()[dim_0] : ldc;

    rocblas_datatype arg_type = get_type(inputs[0].get_shape().type());
    auto output_type          = arg_type;
    if(output_type == rocblas_datatype_i8_r)
    {
        output_type = rocblas_datatype_i32_r;
    }
    auto compute_type = output_type;
    if(compute_fp32)
    {
        if(arg_type == rocblas_datatype_f16_r)
            compute_type = rocblas_datatype_f32_r;
    }

#if ROCBLAS_VERSION_MAJOR >= 2 && ROCBLAS_VERSION_MINOR >= 38
    rocblas_gemm_flags flag =
        int8_x4_format ? rocblas_gemm_flags_pack_int8x4 : rocblas_gemm_flags_none;
#else
    (void)int8_x4_format;
    int flag = 0;
#endif

    auto a_lens = inputs[0].get_shape().lens();
    auto b_lens = inputs[1].get_shape().lens();
267
268
269
    void * alpha_v = nullptr;
    void* beta_v = nullptr;
     output_shape.visit_type([&](auto as) {
270
271
272
273
        auto alpha_r = as(alpha);
        auto beta_r  = as(beta);

        // use void pointer to select different data type if using fp32 mode
274
275
        alpha_v = &alpha_r;
        beta_v  = &beta_r;
276
277
278
279
280
        if(compute_fp32)
        {
            alpha_v = &alpha;
            beta_v  = &beta;
        }
281
     });
282
283
284
285
286

        auto out_lens   = output_shape.lens();
        rocblas_int m   = out_lens[dim_0];
        rocblas_int n   = out_lens[dim_1];
        rocblas_int k   = inputs[0].get_shape().lens()[dim_1];
287
        auto to_pointer = [&](auto&& arg) { return reinterpret_cast<T*>(arg.data()); };
288
289
        if(inputs[0].get_shape().type() == shape::int8_type and (k % 4) != 0 and int8_x4_format)
        {
290
            MIGRAPHX_THROW("create_gemm_args: k size of int8 type input must be multiple of 4!");
291
292
293
294
295
        }

        auto num_matrices = std::accumulate(
            out_lens.rbegin() + 2, out_lens.rend(), std::size_t{1}, std::multiplies<std::size_t>());

296
297
        switch(rocblas_call){
            case     ROCBLAS_GEMM_EX:
298
            {
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
                m *= num_matrices;

                return pack(

                    // the rocblas_gemm API handles inputs and output matrices as
                    // column-major format. When doing a C = A * B, we actually do
                    // C^T = (B^T) * (A^T). That is the reason we input inputs[1] as
                    // A and inputs[0] as B in calling the rocblas_gemm.
                    // rocblas_invoke(&rocblas_gemm_ex,
                    ctx.get_stream().get_rocblas(),
                    transb ? rocblas_operation_transpose : rocblas_operation_none,
                    transa ? rocblas_operation_transpose : rocblas_operation_none,
                    n,
                    m,
                    k,
                    alpha_v,
                    to_pointer(inputs.at(1)),
                    arg_type,
                    ldb,
                    to_pointer(inputs.at(0)),
                    arg_type,
                    lda,
                    beta_v,
                    to_pointer(inputs[2]),
                    output_type,
                    ldc,
                    is_3inputs ? to_pointer(inputs[3]) : to_pointer(inputs[2]),
                    output_type,
                    ldd,
                    compute_type,
                    rocblas_gemm_algo_standard,
                    0,
                    flag);
            }
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372

            case     ROCBLAS_GEMM_STRIDED_BATCHED_EX:
            default:
            {
                auto a_stride = get_batch_stride(inputs[0]);
                auto b_stride = get_batch_stride(inputs[1]);
                auto c_stride = get_batch_stride(inputs[2]);
                auto d_stride = is_3inputs ? get_batch_stride(inputs[3]) : c_stride;
                return pack(
                    // rocblas_invoke(  &rocblas_gemm_strided_batched_ex,
                    ctx.get_stream().get_rocblas(),
                    transb ? rocblas_operation_transpose : rocblas_operation_none,
                    transa ? rocblas_operation_transpose : rocblas_operation_none,
                    n,
                    m,
                    k,
                    alpha_v,
                    to_pointer(inputs.at(1)),
                    arg_type,
                    ldb,
                    b_stride,
                    to_pointer(inputs.at(0)),
                    arg_type,
                    lda,
                    a_stride,
                    beta_v,
                    to_pointer(inputs[2]),
                    output_type,
                    ldc,
                    c_stride,
                    is_3inputs ? to_pointer(inputs[3]) : to_pointer(inputs[2]),
                    output_type,
                    ldd,
                    d_stride,
                    num_matrices,
                    compute_type,
                    rocblas_gemm_algo_standard,
                    0,
                    flag);
            }
373
374

            // case    ROCBLAS_GEMM_EX_GET_SOLUTIONS:
375
            // default:
376
377
378
379
380
381
382
383
384
            //     // the original macro in rocBLAS-internal/rocBLAS/clients/samples/example_user_driven_tuning.cpp is
            //     //  Note different order of m, n, k
            //     // #define GEMM_EX_ARGS \
            //     //     handle, transa, transb, m, n, k, &alpha, da, type, lda, db, type, ldb, &beta, dc, type, ldc,
            //     //     \
            //     //         dc, type, ldc, type, rocblas_gemm_algo_solution_index
            // #define GEMM_EX_ARGS                                                                               \
            //     handle, transa, transb, m, n, k, alpha_v, da, type, lda, db, type, ldb, beta_v, dc, type, ldc, \
            //         dc, type, ldc, type, rocblas_gemm_algo_solution_index
385
386
387
388
389
390
391
            //         return pack(ctx.get_stream().get_rocblas());
    // Get number of solutions
    // rocblas_int size;
    // CHECK_ROCBLAS_ERROR(
    //     rocblas_gemm_ex_get_solutions(GEMM_EX_ARGS, rocblas_gemm_flags_none, NULL, &size));
        } // end switch

392
393
            // default:
            // MIGRAPHX_THROW ("create_gemm_args(): rocBLAS command not supported");
394
395
}

Shucai Xiao's avatar
Shucai Xiao committed
396
397
398
} // namespace gpu
} // namespace MIGRAPHX_INLINE_NS
} // namespace migraphx