compile_gen.cpp 13.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.
 */
Paul Fultz II's avatar
Paul Fultz II committed
24
#include <migraphx/gpu/compile_gen.hpp>
25
#include <migraphx/gpu/context.hpp>
Paul Fultz II's avatar
Paul Fultz II committed
26
27
28
#include <migraphx/shape.hpp>
#include <migraphx/permutation.hpp>
#include <migraphx/stringutils.hpp>
29
30
31
32
33
34
35
#include <migraphx/module.hpp>
#include <migraphx/dead_code_elimination.hpp>
#include <migraphx/eliminate_common_subexpression.hpp>
#include <migraphx/cpp_generator.hpp>
#include <migraphx/pass_manager.hpp>
#include <migraphx/instruction.hpp>
#include <migraphx/ranges.hpp>
Paul Fultz II's avatar
Paul Fultz II committed
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51

namespace migraphx {
inline namespace MIGRAPHX_INLINE_NS {
namespace gpu {
namespace gen {

static std::vector<std::size_t> vector_sizes(const std::vector<shape>& inputs)
{
    // If all inputs are half then only use half2
    if(std::all_of(inputs.begin(), inputs.end(), [](const auto& s) {
           return s.type() == shape::half_type;
       }))
        return {2};
    return {4, 2};
}

52
53
54
vectorize vectorize::elements(std::size_t axis,
                              const std::vector<shape>& inputs,
                              const std::vector<std::size_t>& sizes)
Paul Fultz II's avatar
Paul Fultz II committed
55
{
Paul Fultz II's avatar
Paul Fultz II committed
56
57
58
    if(std::all_of(
           inputs.begin(), inputs.end(), [&](const auto& s) { return s.lens()[axis] == 1; }))
        return {1, axis};
Paul Fultz II's avatar
Paul Fultz II committed
59
60
61
62
63
64
65
    std::vector<std::size_t> max_vec_size;
    std::transform(inputs.begin(),
                   inputs.end(),
                   std::back_inserter(max_vec_size),
                   [&](const auto& input) -> std::size_t {
                       auto stride = input.strides()[axis];
                       auto len    = input.lens()[axis];
66
                       if(not contains({0, 1}, stride))
Paul Fultz II's avatar
Paul Fultz II committed
67
68
69
                           return 1;
                       if(len == 1 and input.elements() > sizes.front())
                           return sizes.front();
70
71
72
73
74
75
76
77
78
                       auto it = std::find_if(sizes.begin(), sizes.end(), [&](auto vsize) {
                           // The len is divisible by the size and all the strides are divisible by
                           // the size
                           return (len % vsize) == 0 and
                                  std::all_of(
                                      input.strides().begin(), input.strides().end(), [&](auto i) {
                                          return contains({0, 1}, i) or i % vsize == 0;
                                      });
                       });
Paul Fultz II's avatar
Paul Fultz II committed
79
80
81
82
83
84
85
                       if(it != sizes.end())
                           return *it;
                       return 1;
                   });
    return {*std::min_element(max_vec_size.begin(), max_vec_size.end()), axis};
}

86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
vectorize vectorize::elements(context& ctx, std::size_t axis, const std::vector<shape>& inputs)
{
    if(inputs.empty())
        return {1, axis};
    std::size_t n = std::max_element(inputs.begin(),
                                     inputs.end(),
                                     by(std::less<>{}, [](const auto& s) { return s.elements(); }))
                        ->elements();
    std::size_t max_global = ctx.get_current_device().get_cu_count() *
                             ctx.get_current_device().get_max_workitems_per_cu();
    std::size_t over = n / max_global;
    bool broadcasted =
        std::any_of(inputs.begin(), inputs.end(), [](const auto& s) { return s.broadcasted(); });
    std::vector<std::size_t> sizes;
    if(broadcasted and over > 8)
        sizes.push_back(8);
    if(over > 4)
        sizes.push_back(4);
    sizes.push_back(2);
    return elements(axis, inputs, sizes);
}

vectorize vectorize::elements(std::size_t axis, const std::vector<shape>& inputs)
{
    return elements(axis, inputs, vector_sizes(inputs));
}

Paul Fultz II's avatar
Paul Fultz II committed
113
114
115
116
117
118
119
120
std::string vectorize::str() const
{
    return "vectorize<" + to_string(size) + ", " + to_string(axis) + ">()";
}

preload preload::broadcasts(std::size_t axis, const std::vector<shape>& inputs)
{
    const std::size_t max_lds_bytes = 4096;
121
122
123
124
125
126
127
128
129
130
131
132
133
    std::vector<bool> result(inputs.size());
    std::vector<std::size_t> preloaded;
    auto idxs = range(inputs.size());
    std::copy_if(idxs.begin(), idxs.end(), std::back_inserter(preloaded), [&](auto i) {
        return inputs[i].strides()[axis] == 0;
    });
    std::sort(preloaded.begin(), preloaded.end(), by(std::less<>{}, [&](auto i) {
                  return inputs[i].bytes();
              }));

    std::size_t bytes = 0;
    for(auto i : preloaded)
    {
134
        const auto& input = inputs[i];
135
136
137
138
139
        bytes += input.bytes();
        if(bytes > max_lds_bytes)
            break;
        result[i] = true;
    }
Paul Fultz II's avatar
Paul Fultz II committed
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
    return {result};
}

std::string preload::str() const
{
    std::vector<std::string> bool_strs;
    std::transform(args.begin(), std::prev(args.end()), std::back_inserter(bool_strs), [](bool b) {
        if(b)
            return "true";
        return "false";
    });
    return "auto_preload<false, " + join_strings(bool_strs, ", ") + ">(idx)";
}

bool preload::is_preloading() const
{
    return std::accumulate(args.begin(), args.end(), false, std::logical_or<>{});
}

std::size_t find_fast_axis(const std::vector<shape>& inputs)
{
    auto permutation = find_permutation(inputs);
    auto it          = std::max_element(permutation.begin(), permutation.end());
    return it - permutation.begin();
}

std::string make_transformer_args(std::vector<std::string> transformers)
{
    return join_strings(std::move(transformers), ", ");
}

Paul's avatar
Paul committed
171
void generate_pointwise(cpp_generator& gg, const module& pm, const std::string& name)
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
{
    module m = pm;
    run_passes(m, {eliminate_common_subexpression{}, dead_code_elimination{}});
    cpp_generator g;
    g.fmap([](const std::string& fname) { return "migraphx::" + fname; });
    g.add_point_op("where", "${function:where}(${0}, ${1}, ${2})");
    g.add_point_op("prelu", "${function:where}(${0} < 0, ${0} * ${1}, ${0})");
    g.add_point_op("sign", "${function:where}(${0} > 0, 1, ${function:where}(${0} < 0, -1, 0))");
    g.add_point_op("equal", "migraphx::abs(${0} == ${1})");
    g.add_point_op("less", "migraphx::abs(${0} < ${1})");
    g.add_point_op("greater", "migraphx::abs(${0} > ${1})");
    g.add_point_op("not", "migraphx::abs(not ${0})");
    // Add explict conversions
    g.fresult(
        [](const shape& s) { return "migraphx::convert<" + shape::cpp_type(s.type()) + ">"; });
Paul's avatar
Paul committed
187
    gg.create_function(
Paul's avatar
Paul committed
188
        g.generate_module(m).set_attributes({"__device__", "__attribute__((const))"}).set_generic_types(m).set_name(name));
Paul's avatar
Paul committed
189
190
191
192
193
194
195
196
197
198
199
200
}
std::string generate_pointwise(const module& pm, const std::string& name)
{
    cpp_generator g;
    generate_pointwise(g, pm, name);
    return g.str();
}
// TODO: Remvoe from reduce.cpp
static std::size_t get_reduce_elements(const std::vector<shape>& inputs)
{
    return inputs.front().elements() / inputs.back().elements();
}
Paul's avatar
Paul committed
201
202
203
204
// static std::size_t get_reduce_elements(const std::vector<instruction_ref>& inputs)
// {
//     return get_reduce_elements(to_shapes(inputs));
// }
Paul's avatar
Paul committed
205
206
207
208
209

struct reduce_op
{
    std::string input;
    std::string reduction = "";
Paul's avatar
Format  
Paul committed
210
211
212
    std::string init      = "0";
    std::string read      = "op::id{}";
    std::string write     = "op::id{}";
Paul's avatar
Paul committed
213
214
215
216
217
218
219
220
221
222
223
224
225
    std::string str() const
    {
        return write + "(r.reduce(" + reduction + ", " + init + ", " + read + ")(" + input + "))";
    }
    static std::string generate(instruction_ref ins, const std::string& x)
    {
        reduce_op r{x};
        if(ins->name() == "reduce_sum")
        {
            r.reduction = "op::sum{}";
        }
        else if(ins->name() == "reduce_mean")
        {
Paul's avatar
Format  
Paul committed
226
            auto s               = ins->inputs().front()->get_shape();
Paul's avatar
Paul committed
227
228
            auto reduce_elements = s.elements() / ins->get_shape().elements();
            auto reduce_type     = s.type();
Paul's avatar
Format  
Paul committed
229
            r.reduction          = "op::sum{}";
Paul's avatar
Paul committed
230
            std::string mean     = "op::mean<" + std::to_string(reduce_elements) + ">{}";
Paul's avatar
Paul committed
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
            // Use float accumulator when reduction size is too large for half
            if(reduce_type == shape::half_type and reduce_elements > 16384)
                r.read = "compose(" + mean + ", op::convert_to<float>{})";
            else if(contains({shape::float_type, shape::half_type, shape::double_type},
                             reduce_type))
                r.read = mean;
            else
                r.write = mean;
        }
        else if(ins->name() == "reduce_max")
        {
            r.reduction = "op::max{}";
            r.init      = "lowest{}";
        }
        else if(ins->name() == "reduce_min")
        {
            r.reduction = "op::min{}";
            r.init      = "highest{}";
        }
        else if(ins->name() == "reduce_prod")
        {
            r.reduction = "op::product{}";
            r.init      = "1";
        }
        else
        {
            MIGRAPHX_THROW("Unsupported reduce");
        }
        return r.str();
    }
};

Paul's avatar
Paul committed
263
264
static bool use_lazy_inner(instruction_ref ins)
{
Paul's avatar
Format  
Paul committed
265
    if(ins->outputs().size() != 1)
Paul's avatar
Paul committed
266
267
268
269
270
        return false;
    auto output = ins->outputs().front();
    return contains(output->name(), "reduce") or output->name() == "@return";
}

Paul's avatar
Paul committed
271
272
273
274
std::string generate_reduce(const module& rm, const std::string& name)
{
    module m = rm;
    cpp_generator g;
Paul's avatar
Format  
Paul committed
275
    auto ilens    = rm.get_parameter_shapes().begin()->second.lens();
Paul's avatar
Paul committed
276
    std::size_t i = 0;
Paul's avatar
Format  
Paul committed
277
278
    auto f        = g.generate_module(m, [&](instruction_ref ins, const auto& names) {
        if(contains(ins->name(), "reduce"))
Paul's avatar
Paul committed
279
280
281
        {
            return reduce_op::generate(ins, names.at(ins->inputs().front()));
        }
Paul's avatar
Format  
Paul committed
282
        else if(ins->name() == "pointwise")
Paul's avatar
Paul committed
283
284
285
286
        {
            auto pointwise_name = "pointwise" + std::to_string(i);
            i++;
            generate_pointwise(g, *ins->module_inputs().front(), pointwise_name);
Paul's avatar
Paul committed
287
            std::vector<instruction_ref> tensors;
Paul's avatar
Format  
Paul committed
288
289
290
291
292
293
294
            std::copy_if(ins->inputs().begin(),
                         ins->inputs().end(),
                         std::back_inserter(tensors),
                         [&](auto input) {
                             return input->get_shape().lens() == ilens and
                                    not input->get_shape().broadcasted();
                         });
Paul's avatar
Paul committed
295
            auto inner_names = names;
Paul's avatar
Format  
Paul committed
296
            for(auto input : tensors)
Paul's avatar
Paul committed
297
                inner_names[input] += "_lambda_param";
Paul's avatar
Format  
Paul committed
298
299
300
301
            auto call_function =
                pointwise_name + "(" +
                join_strings(cpp_generator::to_args(ins->inputs(), inner_names), ", ") + ")";
            if(tensors.empty())
Paul's avatar
Paul committed
302
                return call_function;
Paul's avatar
Format  
Paul committed
303
            const std::string inner_template =
Paul's avatar
Paul committed
304
305
                "r.${inner}([=](${params}) { return ${call}; })(${args})";
            std::string inner_name = use_lazy_inner(ins) ? "lazy_inner" : "inner";
Paul's avatar
Format  
Paul committed
306
307
            auto args              = cpp_generator::to_args(tensors, names);
            auto params            = cpp_generator::to_args(tensors, inner_names);
Paul's avatar
Format  
Paul committed
308
309
310
            std::transform(
                params.begin(), params.end(), params.begin(), [](auto s) { return "auto " + s; });
            return interpolate_string(inner_template,
Paul's avatar
Paul committed
311
312
                                      {{"inner", inner_name},
                                       {"params", join_strings(params, ", ")},
Paul's avatar
Format  
Paul committed
313
314
                                       {"args", join_strings(args, ", ")},
                                       {"call", call_function}});
Paul's avatar
Paul committed
315
        }
Paul's avatar
Paul committed
316
317
318
319
        else if(ins->name() == "multibroadcast")
        {
            return names.at(ins->inputs().front());
        }
Paul's avatar
Paul committed
320
321
        MIGRAPHX_THROW("Unknown operator: " + ins->name());
    });
Paul's avatar
Paul committed
322
    f.set_attributes({"__device__", "__attribute__((const))"}).set_generic_types(m).set_name(name);
Paul's avatar
Paul committed
323
324
    f.add_generic_param("r");
    g.create_function(f);
325
326
327
328
329
330
331
332
333
334
    return g.str();
}

static std::vector<std::string> get_op_names(const module& m)
{
    std::vector<std::string> result;
    for(auto& ins : m)
    {
        if(starts_with(ins.name(), "@"))
            continue;
Paul's avatar
Paul committed
335
336
        if(ins.name() == "multibroadcast")
            continue;
Paul's avatar
Format  
Paul committed
337
        if(ins.name() == "pointwise")
Paul's avatar
Paul committed
338
339
340
341
342
343
344
345
        {
            auto names = get_op_names(*ins.module_inputs().front());
            result.insert(result.end(), names.begin(), names.end());
        }
        else
        {
            result.push_back(ins.name());
        }
346
347
348
349
350
351
352
353
354
355
    }
    return result;
}

std::string generate_name_from_ops(const module& m)
{
    auto op_names = get_op_names(m);
    return join_strings(op_names, "_");
}

Paul Fultz II's avatar
Paul Fultz II committed
356
357
358
359
} // namespace gen
} // namespace gpu
} // namespace MIGRAPHX_INLINE_NS
} // namespace migraphx