ck_gemm.cpp 7.72 KB
Newer Older
Paul's avatar
Paul committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/*
 * 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.
 */
#include <fstream>
#include <filesystem>
#include <migraphx/gpu/compiler.hpp>
#include <migraphx/make_op.hpp>
#include <migraphx/gpu/context.hpp>

#include <migraphx/gpu/compile_hip_code_object.hpp>
#include <migraphx/gpu/compile_hip.hpp>
Paul's avatar
Paul committed
32
#include <migraphx/gpu/compile_gen.hpp>
Paul's avatar
Paul committed
33
#include <migraphx/ranges.hpp>
Paul's avatar
Paul committed
34
#include <migraphx/env.hpp>
Paul's avatar
Paul committed
35
36
37
38
#include <migraphx/reduce_dims.hpp>
#include <migraphx/stringutils.hpp>
#include <migraphx/module.hpp>
#include <migraphx/env.hpp>
Paul's avatar
Paul committed
39
#include <migraphx/file_buffer.hpp>
Paul's avatar
Paul committed
40

Paul's avatar
Paul committed
41
42
const std::vector<std::string>&
get_instance(std::size_t i, const std::function<bool(const std::vector<std::string>&)>& pred);
Paul's avatar
Paul committed
43

Paul's avatar
Paul committed
44
45
46
47
48
namespace migraphx {
inline namespace MIGRAPHX_INLINE_NS {

namespace gpu {

Paul's avatar
Paul committed
49
50
using namespace migraphx::gpu::gen; // NOLINT

Paul's avatar
Paul committed
51
MIGRAPHX_DECLARE_ENV_VAR(MIGRAPHX_LOG_CK_GEMM);
Paul's avatar
Paul committed
52
MIGRAPHX_DECLARE_ENV_VAR(MIGRAPHX_CK_TUNING);
Paul's avatar
Paul committed
53

Paul's avatar
Paul committed
54
55
56
57
// NOLINTNEXTLINE
static const char* const ck_gemm_kernel = R"__migraphx__(
#include <args.hpp>
#include <migraphx/kernels/ck_gemm.hpp>
Paul's avatar
Paul committed
58
#include <migraphx/kernels/pointwise.hpp>
Paul's avatar
Paul committed
59
60
61

namespace migraphx {

Paul's avatar
Paul committed
62
63
${preamble}

Paul's avatar
Paul committed
64
65
extern "C" {

Paul's avatar
Paul committed
66
__global__ void ${kernel}(${params})
Paul's avatar
Paul committed
67
{
Paul's avatar
Paul committed
68
69
    transform_args(make_tensors(), rotate_last())(${args})([](auto... xs) {
        ck_gemm<CK_DeviceGemmMultipleD<${instance}>>(xs...);
Paul's avatar
Paul committed
70
71
72
73
74
75
76
77
78
    });
}

}

} // namespace migraphx

)__migraphx__";

Paul's avatar
Paul committed
79
80
static std::size_t int_div_ceil(std::size_t x, std::size_t y) { return (x + y - 1) / y; }

81
static std::size_t block_size_index = 15;
Paul's avatar
Paul committed
82

Paul's avatar
Paul committed
83
static std::size_t get_block_size(const std::vector<std::string>& s)
Paul's avatar
Paul committed
84
{
Paul's avatar
Paul committed
85
    return std::stoull(s[block_size_index]);
Paul's avatar
Paul committed
86
87
}

Paul's avatar
Paul committed
88
static std::size_t get_grid_size(const std::vector<std::string>& s, std::size_t m, std::size_t n)
Paul's avatar
Paul committed
89
{
Paul's avatar
Format  
Paul committed
90
91
    auto mpb = std::stoull(s[block_size_index + 1]);
    auto npb = std::stoull(s[block_size_index + 2]);
Paul's avatar
Paul committed
92
93
    return int_div_ceil(m, mpb) * int_div_ceil(n, npb);
}
Paul's avatar
Paul committed
94

Paul's avatar
Format  
Paul committed
95
template <class F, class Action>
Paul's avatar
Paul committed
96
97
98
99
100
101
102
103
auto action_decorate(F f, Action action)
{
    return [=](auto&&... xs) {
        action();
        f(std::forward<decltype(xs)>(xs)...);
    };
}

Paul's avatar
Paul committed
104
105
106
using tuning_entry = std::pair<std::vector<shape>, size_t>;
static std::vector<tuning_entry> read_tuning(const std::string& s)
{
Paul's avatar
Format  
Paul committed
107
    if(not fs::exists(s))
Paul's avatar
Paul committed
108
109
110
111
112
113
114
        return {};
    return from_value<std::vector<tuning_entry>>(from_json_string(read_string(s)));
}

static std::size_t get_tuning_for(const std::vector<shape>& inputs)
{
    static auto tuning = read_tuning(string_value_of(MIGRAPHX_CK_TUNING{}, ""));
Paul's avatar
Format  
Paul committed
115
    if(tuning.empty())
Paul's avatar
Paul committed
116
        std::cout << "*********** Warning: No CK tuning!" << std::endl;
Paul's avatar
Format  
Paul committed
117
    auto it = std::find_if(
Paul's avatar
Format  
Paul committed
118
        tuning.begin(), tuning.end(), [&](const auto& p) { return p.first == inputs; });
Paul's avatar
Format  
Paul committed
119
120
    if(it == tuning.end())
    {
Paul's avatar
Paul committed
121
        std::cout << "*********** Warning: CK tuning missing for config!" << std::endl;
Paul's avatar
Paul committed
122
        return 4;
Paul's avatar
Paul committed
123
    }
Paul's avatar
Paul committed
124
125
126
    return it->second;
}

Paul's avatar
Paul committed
127
128
struct ck_gemm_compiler : compiler<ck_gemm_compiler>
{
Paul's avatar
Paul committed
129
130
    static std::string get_layout(const shape& s)
    {
Paul's avatar
Format  
Paul committed
131
132
        return s.transposed() ? "ck::tensor_layout::gemm::ColumnMajor"
                              : "ck::tensor_layout::gemm::RowMajor";
Paul's avatar
Paul committed
133
134
135
    }

    static std::string get_type(const shape& s)
Paul's avatar
Paul committed
136
    {
Paul's avatar
Format  
Paul committed
137
        if(s.type() == shape::half_type)
Paul's avatar
Paul committed
138
139
140
            return "ck::half_t";
        return shape::cpp_type(s.type());
    }
Paul's avatar
Paul committed
141

Paul's avatar
Format  
Paul committed
142
    template <class Iterator, class F>
Paul's avatar
Paul committed
143
144
145
146
147
148
149
    static std::string ck_tuple(Iterator start, Iterator last, F f)
    {
        std::vector<std::string> s;
        std::transform(start, last, std::back_inserter(s), f);
        return "ck::Tuple<" + join_strings(s, ",") + ">";
    }

Paul's avatar
Paul committed
150
151
152
153
    std::vector<std::string> names() const { return {"ck_gemm", "gpu::ck_gemm"}; }

    operation compile_op(context& /* ctx */, const std::vector<shape>& inputs, const value& v) const
    {
Paul's avatar
Paul committed
154
155
        auto a_shape = inputs[0];
        auto b_shape = inputs[1];
Paul's avatar
Paul committed
156
        auto c_shape = inputs.back();
Paul's avatar
Paul committed
157

Paul's avatar
Format  
Paul committed
158
159
        auto m = c_shape.lens().front();
        auto n = c_shape.lens().back();
Paul's avatar
Paul committed
160

Paul's avatar
Format  
Paul committed
161
        auto i        = v.get("tuning_val", get_tuning_for(inputs));
Paul's avatar
Paul committed
162
        auto instance = get_instance(i, [&](const auto& x) -> bool {
Paul's avatar
Format  
Paul committed
163
            return get_layout(a_shape) == x[0] and get_layout(b_shape) == x[1] and
164
165
                   get_layout(c_shape) == x[3] and get_type(a_shape) == x[4] and
                   get_type(b_shape) == x[5] and get_type(c_shape) == x[9];
Paul's avatar
Paul committed
166
        });
Paul's avatar
Paul committed
167
        assert(inputs.size() < 4 or v.contains("post"));
Paul's avatar
Format  
Paul committed
168
        if(v.contains("post"))
Paul's avatar
Paul committed
169
170
        {
            assert(instance[2] == "ck::Tuple<>");
Paul's avatar
Format  
Paul committed
171
            instance[2] = ck_tuple(inputs.begin() + 2, inputs.end() - 1, &get_layout);
Paul's avatar
Paul committed
172
            assert(instance[8] == "ck::Tuple<>");
Paul's avatar
Format  
Paul committed
173
            instance[8] = ck_tuple(inputs.begin() + 2, inputs.end() - 1, &get_type);
Paul's avatar
Paul committed
174
175
176
177
            assert(instance[12] == "ck_passthrough");
            instance[12] = v.at("post").to<std::string>();
        }

Paul's avatar
Paul committed
178
        hip_compile_options options;
Paul's avatar
Paul committed
179
        auto block_size = get_block_size(instance);
Paul's avatar
Format  
Paul committed
180
        auto grid_size  = get_grid_size(instance, m, n);
Paul's avatar
Paul committed
181
        options.set_launch_params(v, grid_size * block_size, block_size);
Paul's avatar
Paul committed
182
        options.inputs         = inputs;
Paul's avatar
Paul committed
183
        options.output         = c_shape;
Paul's avatar
Paul committed
184
        options.kernel_name    = v.get("kernel", "ck_gemm_kernel");
Paul's avatar
Paul committed
185
186
        options.virtual_inputs = inputs;

Paul's avatar
Format  
Paul committed
187
188
189
190
191
192
        auto src = interpolate_string(ck_gemm_kernel,
                                      {{"instance", join_strings(instance, ",")},
                                       {"params", enum_params(inputs.size(), "void * private_p")},
                                       {"args", enum_params(inputs.size(), "private_p")},
                                       {"preamble", v.get("preamble", std::string{})},
                                       {"kernel", options.kernel_name}});
Paul's avatar
Format  
Paul committed
193

Paul's avatar
Paul committed
194
195
196
197
198
        return compile_hip_code_object(src, options);
    }

    compiler_replace compile(context& ctx, instruction_ref ins, const operation& op) const
    {
Paul's avatar
Format  
Paul committed
199
200
        auto v      = op.to_value();
        v["kernel"] = "ck_gemm_kernel";
Paul's avatar
Paul committed
201
202
203
        if(not ins->module_inputs().empty())
        {
            auto* pm      = ins->module_inputs().front();
Paul's avatar
Format  
Paul committed
204
205
206
            v["preamble"] = generate_pointwise(*pm, "post_ck_gemm_function") +
                            "\nMIGRAPHX_LIFT_CLASS(post_ck_gemm, post_ck_gemm_function);";
            v["post"]   = "ck_function_adaptor<post_ck_gemm>";
Paul's avatar
Paul committed
207
            v["kernel"] = "ck_gemm_" + generate_name_from_ops(*pm) + "_kernel";
Paul's avatar
Format  
Paul committed
208
        }
Paul's avatar
Paul committed
209

Paul's avatar
Paul committed
210
        auto shapes = to_shapes(ins->inputs());
Paul's avatar
Paul committed
211
        return action_decorate(replace(compile_op(ctx, shapes, v)), [=] {
Paul's avatar
Format  
Paul committed
212
            if(enabled(MIGRAPHX_LOG_CK_GEMM{}))
Paul's avatar
Paul committed
213
214
                std::cout << "ck_gemm: " << to_json_string(to_value(shapes)) << std::endl;
        });
Paul's avatar
Paul committed
215
216
217
218
219
220
    }
};

} // namespace gpu
} // namespace MIGRAPHX_INLINE_NS
} // namespace migraphx