reduce.cpp 12.3 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.
 */
24
25
26
27
#include <migraphx/gpu/compiler.hpp>
#include <migraphx/gpu/context.hpp>
#include <migraphx/gpu/compile_hip_code_object.hpp>
#include <migraphx/gpu/compile_hip.hpp>
Paul Fultz II's avatar
Paul Fultz II committed
28
#include <migraphx/gpu/compile_gen.hpp>
29
30
31
32
33
34
#include <migraphx/reduce_dims.hpp>

namespace migraphx {
inline namespace MIGRAPHX_INLINE_NS {
namespace gpu {

Paul Fultz II's avatar
Paul Fultz II committed
35
36
using namespace migraphx::gpu::gen; // NOLINT

37
38
39
static const char* const simple_reduce_kernel = R"__migraphx__(
#include <migraphx/kernels/index.hpp>
#include <migraphx/kernels/reduce.hpp>
Paul Fultz II's avatar
Paul Fultz II committed
40
#include <migraphx/kernels/vectorize.hpp>
41
42
43
44
45
46
47
#include <args.hpp>

namespace migraphx {

${preamble}

extern "C" {
Paul Fultz II's avatar
Paul Fultz II committed
48
MIGRAPHX_GLOBAL void reduce_kernel(void* input_p, void* output_p) 
49
{
Paul Fultz II's avatar
Paul Fultz II committed
50
51
    
    transform_args(make_tensors(), ${transformers})(input_p, output_p)([](auto input, auto output) {
52

Paul Fultz II's avatar
Paul Fultz II committed
53
        simple_reduce<reduce::${algo}>(${reduction}, ${init}, input, output, ${read}, ${write});
54
55
56
57
58
59
60
61
62
    });
}
    
}

} // namespace migraphx

)__migraphx__";

Paul Fultz II's avatar
Paul Fultz II committed
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
static std::vector<std::size_t> get_reduce_lens(const std::vector<std::size_t>& input_lens,
                                                const std::vector<std::size_t>& output_lens)
{
    std::vector<std::size_t> reduce_lens;
    std::transform(output_lens.begin(),
                   output_lens.end(),
                   input_lens.begin(),
                   std::back_inserter(reduce_lens),
                   [](auto x, auto y) -> std::size_t {
                       if(x == y)
                           return 1;
                       else
                           return y;
                   });
    return reduce_lens;
}

Paul Fultz II's avatar
Paul Fultz II committed
80
81
82
83
84
85
86
template <class T>
static shape get_reduced_shape(const shape& s, const std::vector<T>& axes)
{
    auto lens = s.lens();
    std::fill(lens.begin(), lens.end(), 1);
    for(const auto& axis : axes)
        lens[axis] = s.lens()[axis];
87
    return s.with_lens(lens);
Paul Fultz II's avatar
Paul Fultz II committed
88
89
90
91
92
93
94
95
}

template <class T>
static shape get_output_shape(const shape& s, const std::vector<T>& axes)
{
    auto lens = s.lens();
    for(const auto& axis : axes)
        lens[axis] = 1;
96
    return s.with_lens(lens);
Paul Fultz II's avatar
Paul Fultz II committed
97
98
99
}

template <class ReduceLens>
Paul's avatar
Paul committed
100
static std::string get_reduce_algo(context& ctx, const std::vector<shape>& inputs, ReduceLens rlens)
Paul Fultz II's avatar
Paul Fultz II committed
101
102
{
    const auto init = std::numeric_limits<std::size_t>::max();
Paul's avatar
Format  
Paul committed
103
    auto relements  = std::accumulate(rlens.begin(), rlens.end(), 1, std::multiplies<>{});
Paul Fultz II's avatar
Paul Fultz II committed
104
105
106
107
108
109
110
111
112
113
    // The minimum stride
    auto min_stride = std::inner_product(
        rlens.begin(),
        rlens.end(),
        inputs.front().strides().begin(),
        init,
        [](auto x, auto y) { return std::min(x, y); },
        [](auto len, auto stride) { return len == 1 ? init : stride; });
    if(min_stride > 2)
        return "lane";
Paul's avatar
Format  
Paul committed
114
    if(relements <= ctx.get_current_device().get_wavefront_size())
Paul's avatar
Paul committed
115
        return "wave";
Paul Fultz II's avatar
Paul Fultz II committed
116
117
118
    return "block";
}

Paul's avatar
Paul committed
119
static std::string get_reduce_algo(context& ctx, const std::vector<shape>& inputs)
Paul Fultz II's avatar
Paul Fultz II committed
120
121
{
    auto rlens = get_reduce_lens(inputs.front().lens(), inputs.back().lens());
Paul's avatar
Paul committed
122
123
124
125
126
127
    return get_reduce_algo(ctx, inputs, rlens);
}

static std::size_t compute_subwave_size(context& ctx, std::size_t n)
{
    std::size_t max_wavefront_size = ctx.get_current_device().get_wavefront_size();
Paul's avatar
Format  
Paul committed
128
    std::size_t wavefront_size     = 1;
Paul's avatar
Paul committed
129
    while(wavefront_size <= n and wavefront_size < max_wavefront_size)
Paul's avatar
Paul committed
130
131
        wavefront_size *= 2;
    return wavefront_size;
Paul Fultz II's avatar
Paul Fultz II committed
132
133
134
}

struct simple_reduce_compiler : compiler<simple_reduce_compiler>
135
136
137
{
    std::vector<std::string> names() const
    {
Paul Fultz II's avatar
Paul Fultz II committed
138
139
140
141
142
143
144
145
146
147
148
        return {"simple_reduce",
                "reduce_sum",
                "reduce_mean",
                "reduce_max",
                "reduce_min",
                "reduce_prod"};
    }

    static std::size_t get_reduce_elements(const std::vector<shape>& inputs)
    {
        return inputs.front().elements() / inputs.back().elements();
149
150
151
152
153
    }

    operation compile_op(context& ctx, const std::vector<shape>& inputs, const value& v) const
    {
        hip_compile_options options;
Paul Fultz II's avatar
Paul Fultz II committed
154
155
156
157
158
159
        options.inputs         = inputs;
        options.output         = inputs.back();
        options.virtual_inputs = reduce_dims(inputs);
        auto faxis             = find_fast_axis({options.virtual_inputs.front()});
        vectorize vec{};
        auto nelements = options.virtual_inputs.back().elements();
Paul's avatar
Paul committed
160
161
        auto algo      = v.get("algo", get_reduce_algo(ctx, options.virtual_inputs));
        if(algo == "block" or algo == "wave")
Paul Fultz II's avatar
Paul Fultz II committed
162
        {
163
164
165
166
            // Vectorize if the axis is a reduction axis
            if(options.virtual_inputs.back().lens()[faxis] == 1)
                vec = vectorize::elements(ctx, faxis, options.virtual_inputs);
            auto relements  = get_reduce_elements(options.virtual_inputs) / vec.size;
Paul's avatar
Paul committed
167
168
            if(algo == "block")
            {
Paul's avatar
Paul committed
169
                auto block_size = compute_block_size(ctx, relements, 256);
Paul's avatar
Paul committed
170
171
172
173
174
175
176
177
                if(relements >= block_size * 256)
                    algo = "block_large";
                options.set_launch_params(
                    v, compute_global_for(ctx, nelements * block_size, 256), block_size);
            }
            else
            {
                auto subwave_size = compute_subwave_size(ctx, relements);
Paul's avatar
Format  
Paul committed
178
179
180
181
                algo              = "subwave<" + std::to_string(subwave_size) + ">";
                options.set_launch_params(v,
                                          compute_global_for(ctx, nelements * subwave_size, 256),
                                          ctx.get_current_device().get_wavefront_size());
Paul's avatar
Paul committed
182
            }
Paul Fultz II's avatar
Paul Fultz II committed
183
184
185
        }
        else if(algo == "lane")
        {
Paul Fultz II's avatar
Paul Fultz II committed
186
            options.set_launch_params(v, compute_global_for(ctx, nelements, 256));
Paul Fultz II's avatar
Paul Fultz II committed
187
188
189
190
191
        }
        else
        {
            MIGRAPHX_THROW("Unknown reduce algo: " + algo);
        }
Paul Fultz II's avatar
Paul Fultz II committed
192
193
194
        options.kernel_name  = "reduce_kernel";
        std::string identity = "[](auto x) { return x; }";
        auto src             = interpolate_string(simple_reduce_kernel,
195
196
197
198
                                      {{"reduction", v.at("reduction").to<std::string>()},
                                       {"init", v.get("init", std::string{"0"})},
                                       {"read", v.get("read", identity)},
                                       {"write", v.get("write", identity)},
Paul Fultz II's avatar
Paul Fultz II committed
199
                                       {"algo", algo},
Paul Fultz II's avatar
Paul Fultz II committed
200
                                       {"transformers", make_transformer_args(vec)},
201
                                       {"preamble", v.get("preamble", std::string{})}});
Paul Fultz II's avatar
Paul Fultz II committed
202
        options.params += "-Wno-float-equal";
203
204
205
206
207
        return compile_hip_code_object(src, options);
    }

    compiler_replace compile(context& ctx, instruction_ref ins, const operation& op) const
    {
208
        value v = value::object{};
Paul Fultz II's avatar
Paul Fultz II committed
209
210
211
212
213
214
        reduce_op r{};
        r.set(ins, op);
        v["reduction"] = r.reduction;
        v["read"]      = r.read;
        v["write"]     = r.write;
        v["init"]      = r.init;
215
        return compile_op(ctx, to_shapes(ins->inputs()), v);
Paul Fultz II's avatar
Paul Fultz II committed
216
217
218
219
220
221
222
223
224
225
226
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
    }
};

static const char* const fused_reduce_kernel = R"__migraphx__(
#include <migraphx/kernels/index.hpp>
#include <migraphx/kernels/reduce.hpp>
#include <migraphx/kernels/pointwise.hpp>
#include <migraphx/kernels/vectorize.hpp>
#include <args.hpp>

namespace migraphx {

${preamble}

extern "C" {
MIGRAPHX_GLOBAL void ${kernel}(${params})
{
    transform_args(make_tensors(), rotate_last(), ${transformers})(${args})([](auto y, auto... xs) {
        fused_reduce<reduce::${algo}, ${reduced}>(y, partial(${lambda})(xs...));
    });
}
    
}

} // namespace migraphx

)__migraphx__";

struct fused_reduce_compiler : compiler<fused_reduce_compiler>
{
    std::vector<std::string> names() const { return {"fused_reduce"}; }

    operation compile_op(context& ctx, const std::vector<shape>& inputs, const value& v) const
    {
        auto axes           = v.at("axes").to_vector<std::size_t>();
        auto virtual_inputs = inputs;
        virtual_inputs.push_back(get_reduced_shape(inputs.front(), axes));
        virtual_inputs.push_back(get_output_shape(inputs.front(), axes));
254
        virtual_inputs           = reduce_dims(normalize_permutation(virtual_inputs));
Paul Fultz II's avatar
Paul Fultz II committed
255
256
257
258
259
260
261
262
263
264
265
266
        auto reduce_output_shape = virtual_inputs.back();
        virtual_inputs.pop_back();
        auto reduction_shape = virtual_inputs.back();
        virtual_inputs.pop_back();

        hip_compile_options options;
        options.inputs         = inputs;
        options.output         = inputs.back();
        options.virtual_inputs = virtual_inputs;
        auto faxis             = find_fast_axis({options.virtual_inputs.front()});
        vectorize vec{};
        auto nelements = reduce_output_shape.elements();
Paul's avatar
Format  
Paul committed
267
268
        auto algo =
            v.get("algo", get_reduce_algo(ctx, options.virtual_inputs, reduction_shape.lens()));
Paul's avatar
Paul committed
269
        if(algo == "block" or algo == "wave")
270
        {
Paul Fultz II's avatar
Paul Fultz II committed
271
272
273
274
            // Vectorize if the axis is a reduction axis
            if(reduce_output_shape.lens()[faxis] == 1)
                vec = vectorize::elements(ctx, faxis, options.virtual_inputs);
            auto relements  = reduction_shape.elements() / vec.size;
Paul's avatar
Format  
Paul committed
275
            if(algo == "block")
Paul's avatar
Paul committed
276
            {
Paul's avatar
Paul committed
277
                auto block_size = compute_block_size(ctx, relements, 256);
Paul's avatar
Paul committed
278
279
280
281
282
283
284
285
                if(relements >= block_size * 256)
                    algo = "block_large";
                options.set_launch_params(
                    v, compute_global_for(ctx, nelements * block_size, 256), block_size);
            }
            else
            {
                auto subwave_size = compute_subwave_size(ctx, relements);
Paul's avatar
Format  
Paul committed
286
287
288
289
                algo              = "subwave<" + std::to_string(subwave_size) + ">";
                options.set_launch_params(v,
                                          compute_global_for(ctx, nelements * subwave_size, 256),
                                          ctx.get_current_device().get_wavefront_size());
Paul's avatar
Paul committed
290
            }
291
        }
Paul Fultz II's avatar
Paul Fultz II committed
292
        else if(algo == "lane")
293
        {
Paul Fultz II's avatar
Paul Fultz II committed
294
            options.set_launch_params(v, compute_global_for(ctx, nelements, 256));
295
296
297
        }
        else
        {
Paul Fultz II's avatar
Paul Fultz II committed
298
            MIGRAPHX_THROW("Unknown reduce algo: " + algo);
299
        }
Paul Fultz II's avatar
Paul Fultz II committed
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
        options.kernel_name = v.get("kernel", "reduce_kernel");
        auto src            = interpolate_string(
            fused_reduce_kernel,
            {{"kernel", options.kernel_name},
             {"params", enum_params(inputs.size(), "void * private_p")},
             {"args", enum_params(inputs.size(), "private_p")},
             {"algo", algo},
             {"reduced", "decltype(" + generate_make_shape(reduce_output_shape) + ")"},
             {"lambda", v.at("lambda").to<std::string>()},
             {"transformers", make_transformer_args(vec)},
             {"preamble", v.get("preamble", std::string{})}});
        options.params += "-Wno-float-equal";
        return compile_hip_code_object(src, options);
    }

    compiler_replace compile(context& ctx, instruction_ref ins, const operation& op) const
    {
        assert(not ins->module_inputs().empty());
        auto v        = op.to_value();
        auto* rm      = ins->module_inputs().front();
        v["preamble"] = generate_reduce(*rm, "fused_reduce_op");
        v["lambda"]   = "MIGRAPHX_LIFT(fused_reduce_op)";
        v["kernel"]   = generate_name_from_ops(*rm) + "_kernel";
323
        return compile_op(ctx, to_shapes(ins->inputs()), v);
324
325
326
327
328
    }
};
} // namespace gpu
} // namespace MIGRAPHX_INLINE_NS
} // namespace migraphx