"llama/make/gpu.make" did not exist on "217903ab5111124041b3bb9d7a04d9101f2f32b2"
fuse_ops.cpp 12.8 KB
Newer Older
Paul's avatar
Paul committed
1
2
3
4
5
6
7
8
#include <migraphx/gpu/fuse_ops.hpp>
#include <migraphx/matcher.hpp>
#include <migraphx/gpu/miopen.hpp>
#include <migraphx/gpu/convolution.hpp>
#include <migraphx/gpu/device/add_relu.hpp>
#include <migraphx/instruction.hpp>

namespace migraphx {
Paul's avatar
Paul committed
9
inline namespace MIGRAPHX_INLINE_NS {
Paul's avatar
Paul committed
10
11
namespace gpu {

Paul's avatar
Paul committed
12
13
14
15
16
17
18
19
struct fusion
{
    using op_t = miopenFusionOpDescriptor_t;
    shared<fusion_plan_descriptor> fp;

    // Used as a temporary hack to keep descriptor references alive
    std::vector<std::shared_ptr<void>> storage;

Paul's avatar
Paul committed
20
    template <class T>
Paul's avatar
Paul committed
21
22
23
24
25
26
27
28
29
30
31
    auto keep_alive(T x)
    {
        auto result = share(std::move(x));
        storage.push_back(result);
        return result;
    }

    fusion(const shape& input)
    // : fp(make_fusion_plan(input))
    {
        auto t = make_tensor(input);
Paul's avatar
Paul committed
32
        fp     = make_fusion_plan(t);
Paul's avatar
Paul committed
33
34
35
36
37
38
39
40
        keep_alive(std::move(t));
    }

    op_t operator[](std::size_t i) const
    {
        op_t result;
        auto status = miopenFusionPlanGetOp(fp.get(), i, &result);
        if(status != miopenStatusSuccess)
Paul's avatar
Paul committed
41
            MIGRAPHX_THROW("Failed retrieving operator at " + std::to_string(i));
Paul's avatar
Paul committed
42
43
44
        return result;
    }

Paul's avatar
Paul committed
45
    auto get() const { return fp.get(); }
Paul's avatar
Paul committed
46
47
48
49

    op_t create_bias(const shape& bias)
    {
        op_t result;
Paul's avatar
Paul committed
50
51
        auto b      = shape{bias.type(), {1, bias.lens().at(1), 1, 1}};
        auto t      = keep_alive(make_tensor(b));
Paul's avatar
Paul committed
52
53
        auto status = miopenCreateOpBiasForward(fp.get(), &result, t.get());
        if(status != miopenStatusSuccess)
Paul's avatar
Paul committed
54
            MIGRAPHX_THROW("Creating operator failed");
Paul's avatar
Paul committed
55
56
57
58
59
60
61
62
        return result;
    }

    op_t create_relu()
    {
        op_t result;
        auto status = miopenCreateOpActivationForward(fp.get(), &result, miopenActivationRELU);
        if(status != miopenStatusSuccess)
Paul's avatar
Paul committed
63
            MIGRAPHX_THROW("Creating operator failed");
Paul's avatar
Paul committed
64
65
66
67
68
69
        return result;
    }

    op_t create_conv(const op::convolution& op, const shape& weights)
    {
        op_t result;
Paul's avatar
Paul committed
70
71
        auto cd     = keep_alive(make_conv(op));
        auto t      = keep_alive(make_tensor(weights));
Paul's avatar
Paul committed
72
73
        auto status = miopenCreateOpConvForward(fp.get(), &result, cd.get(), t.get());
        if(status != miopenStatusSuccess)
Paul's avatar
Paul committed
74
            MIGRAPHX_THROW("Creating operator failed");
Paul's avatar
Paul committed
75
76
        return result;
    }
Paul's avatar
Paul committed
77
78
79
80
81
82
83
84

    shape get_workspace(context&)
    {
        // TODO: Use zero workspace for now
        std::size_t ws_size = 0;
        // int algo_count = 1;
        // miopenConvFwdAlgorithm_t algo;
        // miopenFusionPlanConvolutionGetAlgo(fp.get(), 1, &algo_count, &algo);
Paul's avatar
Paul committed
85
86
        // miopenFusionPlanGetWorkSpaceSize(ctx.get_stream().get_miopen(), fp.get(), &ws_size,
        // algo);
Paul's avatar
Paul committed
87
88
89
90
91
        return shape{shape::int8_type, {ws_size}};
    }

    void compile(context& ctx)
    {
Paul's avatar
Paul committed
92
        auto status = miopenCompileFusionPlan(ctx.get_stream().get_miopen(), fp.get());
Paul's avatar
Paul committed
93
        if(status != miopenStatusSuccess)
Paul's avatar
Paul committed
94
            MIGRAPHX_THROW("Compiling fusion plan failed");
Paul's avatar
Paul committed
95
96
    }

Paul's avatar
Paul committed
97
98
99
100
    argument execute(context& ctx,
                     const fused_operator_args& fargs,
                     const argument& x,
                     const argument& y) const
Paul's avatar
Paul committed
101
    {
Paul's avatar
Paul committed
102
103
        auto x_td   = make_tensor(x.get_shape());
        auto y_td   = make_tensor(y.get_shape());
Paul's avatar
Paul committed
104
        auto status = miopenExecuteFusionPlan(ctx.get_stream().get_miopen(),
Paul's avatar
Paul committed
105
106
107
108
109
110
                                              fp.get(),
                                              x_td.get(),
                                              x.implicit(),
                                              y_td.get(),
                                              y.implicit(),
                                              fargs.get());
Paul's avatar
Paul committed
111
        if(status != miopenStatusSuccess)
Paul's avatar
Paul committed
112
            MIGRAPHX_THROW("Failed to execute fusion plan");
Paul's avatar
Paul committed
113
114
        return y;
    }
Paul's avatar
Paul committed
115
116
};

Paul's avatar
Paul committed
117
MIGRAPHX_PRED_MATCHER(bias_shape, instruction_ref ins)
Paul's avatar
Paul committed
118
119
{
    auto&& s = ins->get_shape();
Paul's avatar
Paul committed
120
121
    return s.broadcasted() and s.strides().size() == 4 and s.strides()[0] == 0 and
           s.strides()[1] != 0 and s.strides()[2] == 0 and s.strides()[3] == 0;
Paul's avatar
Paul committed
122
123
124
}

// TODO: Move to another header
Paul's avatar
Paul committed
125
126
template <class T, class... Ts>
std::array<T, sizeof...(Ts) + 1> make_array(T x, Ts... xs)
Paul's avatar
Paul committed
127
128
{
    return {std::move(x), std::move(static_cast<T>(xs))...};
Paul's avatar
Paul committed
129
}
Paul's avatar
Paul committed
130

Paul's avatar
Paul committed
131
MIGRAPHX_PRED_MATCHER(fusable_conv, instruction_ref ins)
Paul's avatar
Paul committed
132
133
134
{
    if(ins->name() != "gpu::convolution")
        return false;
Paul's avatar
Paul committed
135
136
    if(ins->get_shape().type() != shape::float_type)
        return false;
Paul's avatar
Paul committed
137
138
139
    auto wei = ins->inputs().at(1)->get_shape();
    assert(wei.lens().size() == 4);
    auto conv = any_cast<miopen_convolution>(ins->get_operator());
Khalique's avatar
Khalique committed
140
    if(conv.op.group > 1)
Khalique's avatar
Khalique committed
141
        return false;
Paul's avatar
Paul committed
142
    if(wei.lens()[1] > 512 and conv.algo != miopenConvolutionFwdAlgoWinograd)
Paul's avatar
Paul committed
143
144
        return false;
    auto op = conv.op;
Paul's avatar
Paul committed
145
146
    return contains({{0, 0}, {1, 1}, {2, 2}}, op.padding) and
           contains({{0, 0}, {1, 1}}, op.stride) and op.dilation == make_array<size_t>(1, 1);
Paul's avatar
Paul committed
147
148
}

Paul's avatar
Paul committed
149
150
151
152
153
154
155
156
struct hip_triadd
{
    std::string name() const { return "hip::triadd"; }
    shape compute_shape(const std::vector<shape>& inputs) const
    {
        check_shapes{inputs, *this}.has(4);
        return inputs.front();
    }
Paul's avatar
Paul committed
157
    argument compute(context& ctx, const shape&, const std::vector<argument>& args) const
Paul's avatar
Paul committed
158
    {
Paul's avatar
Paul committed
159
        device::add(ctx.get_stream().get(), args.at(3), args.at(0), args.at(1), args.at(2));
Paul's avatar
Paul committed
160
161
        return args.at(3);
    }
Paul's avatar
Paul committed
162
    int output_alias(const std::vector<shape>& shapes) const { return shapes.size() - 1; }
Paul's avatar
Paul committed
163
164
165
166
167
168
169
170
171
172
};

struct hip_triadd_relu
{
    std::string name() const { return "hip::triadd_relu"; }
    shape compute_shape(const std::vector<shape>& inputs) const
    {
        check_shapes{inputs, *this}.has(4);
        return inputs.front();
    }
Paul's avatar
Paul committed
173
    argument compute(context& ctx, const shape&, const std::vector<argument>& args) const
Paul's avatar
Paul committed
174
    {
Paul's avatar
Paul committed
175
        device::add_relu(ctx.get_stream().get(), args.at(3), args.at(0), args.at(1), args.at(2));
Paul's avatar
Paul committed
176
177
        return args.at(3);
    }
Paul's avatar
Paul committed
178
    int output_alias(const std::vector<shape>& shapes) const { return shapes.size() - 1; }
Paul's avatar
Paul committed
179
180
};

Paul's avatar
Paul committed
181
182
183
184
185
struct hip_add_relu
{
    std::string name() const { return "hip::add_relu"; }
    shape compute_shape(const std::vector<shape>& inputs) const
    {
Paul's avatar
Paul committed
186
        check_shapes{inputs, *this}.has(3);
Paul's avatar
Paul committed
187
188
        return inputs.front();
    }
Paul's avatar
Paul committed
189
    argument compute(context& ctx, const shape&, const std::vector<argument>& args) const
Paul's avatar
Paul committed
190
    {
Paul's avatar
Paul committed
191
        device::add_relu(ctx.get_stream().get(), args.at(2), args.at(0), args.at(1));
Paul's avatar
Paul committed
192
193
        return args.at(2);
    }
Paul's avatar
Paul committed
194
    int output_alias(const std::vector<shape>& shapes) const { return shapes.size() - 1; }
Paul's avatar
Paul committed
195
196
};

Paul's avatar
Paul committed
197
struct find_add_relu
Paul's avatar
Paul committed
198
{
Paul's avatar
Paul committed
199
200
    auto matcher() const
    {
Paul's avatar
Paul committed
201
202
        return match::name("gpu::relu")(match::arg(0)(
            match::any_of(match::name("gpu::add"), match::name("hip::triadd")).bind("add")));
Paul's avatar
Paul committed
203
    }
Paul's avatar
Paul committed
204

Paul's avatar
Paul committed
205
206
    void apply(program& p, match::matcher_result r) const
    {
Paul's avatar
Paul committed
207
        auto add_ins = r.instructions["add"];
Paul's avatar
Paul committed
208
209
        auto ins     = r.result;
        auto args    = add_ins->inputs();
Paul's avatar
Paul committed
210
        // Use the allocation from the relu operator
Paul's avatar
Paul committed
211
        args.back() = ins->inputs().back();
Paul's avatar
Paul committed
212
213
214
215
216
217
218
        if(add_ins->name() == "gpu::add")
            p.replace_instruction(ins, hip_add_relu{}, args);
        else if(add_ins->name() == "hip::triadd")
            p.replace_instruction(ins, hip_triadd_relu{}, args);
    }
};

Paul's avatar
Paul committed
219
struct find_triadd
Paul's avatar
Paul committed
220
221
222
{
    auto matcher() const
    {
Paul's avatar
Paul committed
223
224
        return match::name("gpu::add")(match::either_arg(0, 1)(match::name("gpu::add").bind("add"),
                                                               match::any().bind("input")));
Paul's avatar
Paul committed
225
226
227
228
    }

    void apply(program& p, match::matcher_result r) const
    {
Paul's avatar
Paul committed
229
230
231
        auto add_ins        = r.instructions["add"];
        auto input_ins      = r.instructions["input"];
        auto ins            = r.result;
Paul's avatar
Paul committed
232
233
234
235
236
237
238
239
240
241
242
        auto args           = add_ins->inputs();
        auto is_broadcasted = [](auto arg) { return arg->get_shape().broadcasted(); };
        if(std::count_if(args.begin(), args.end(), is_broadcasted) > 1)
            return;
        args.insert(args.begin(), input_ins);
        // Ensure the last arguments is the broadcasted one
        auto it = std::find_if(args.begin(), args.end(), is_broadcasted);
        if(it != args.end())
            std::swap(*it, *std::prev(args.end(), 2));
        args.back() = ins->inputs().back();
        p.replace_instruction(ins, hip_triadd{}, args);
Paul's avatar
Paul committed
243
    }
Paul's avatar
Paul committed
244
245
};

Paul's avatar
Paul committed
246
247
248
249
250
251
252
struct miopen_conv_bias
{
    op::convolution op;
    fusion f;
    fusion::op_t conv;
    fusion::op_t bias;

Paul's avatar
Paul committed
253
254
    miopen_conv_bias(op::convolution c, const shape& input, const shape& weights, const shape& b)
        : op(c), f(input)
Paul's avatar
Paul committed
255
    {
Paul's avatar
Paul committed
256
257
        conv = f.create_conv(op, weights);
        bias = f.create_bias(b);
Paul's avatar
Paul committed
258
259
260
261
262
263
264
265
266
    }

    std::string name() const { return "gpu::conv_bias"; }
    shape compute_shape(const std::vector<shape>& inputs) const
    {
        check_shapes{inputs, *this}.has(5);
        // TODO: Check slices
        return op.compute_shape({inputs.at(0), inputs.at(1)});
    }
Paul's avatar
Paul committed
267
    argument compute(context& ctx, const shape&, const std::vector<argument>& args) const
Paul's avatar
Paul committed
268
    {
Paul's avatar
Paul committed
269
        auto fargs  = make_fused_args();
Paul's avatar
Paul committed
270
        float alpha = 1;
Paul's avatar
Paul committed
271
        float beta  = 0;
Paul's avatar
Paul committed
272
273
        miopenSetOpArgsConvForward(fargs.get(), conv, &alpha, &beta, args[1].implicit());
        miopenSetOpArgsBiasForward(fargs.get(), bias, &alpha, &beta, args[3].implicit());
Paul's avatar
Paul committed
274
        return f.execute(ctx, fargs, args[0], args[4]);
Paul's avatar
Paul committed
275
276
    }

Paul's avatar
Paul committed
277
278
    void finalize(context& ctx, const shape&, const std::vector<shape>&) { f.compile(ctx); }
    shape get_workspace(context& ctx) { return f.get_workspace(ctx); }
Paul's avatar
Paul committed
279
    int output_alias(const std::vector<shape>& shapes) const { return shapes.size() - 1; }
Paul's avatar
Paul committed
280
281
};

Paul's avatar
Add cbr  
Paul committed
282
283
284
285
286
287
struct miopen_conv_bias_relu
{
    op::convolution op;
    fusion f;
    fusion::op_t conv;
    fusion::op_t bias;
Paul's avatar
Paul committed
288
    fusion::op_t relu;
Paul's avatar
Add cbr  
Paul committed
289

Paul's avatar
Paul committed
290
291
292
293
294
    miopen_conv_bias_relu(op::convolution c,
                          const shape& input,
                          const shape& weights,
                          const shape& b)
        : op(c), f(input)
Paul's avatar
Add cbr  
Paul committed
295
    {
Paul's avatar
Paul committed
296
297
298
        conv = f.create_conv(op, weights);
        bias = f.create_bias(b);
        relu = f.create_relu();
Paul's avatar
Add cbr  
Paul committed
299
300
301
302
303
304
305
306
307
    }

    std::string name() const { return "gpu::conv_bias_relu"; }
    shape compute_shape(const std::vector<shape>& inputs) const
    {
        check_shapes{inputs, *this}.has(5);
        // TODO: Check slices
        return op.compute_shape({inputs.at(0), inputs.at(1)});
    }
Paul's avatar
Paul committed
308
    argument compute(context& ctx, const shape&, const std::vector<argument>& args) const
Paul's avatar
Add cbr  
Paul committed
309
310
    {
        auto fargs  = make_fused_args();
Paul's avatar
Paul committed
311
        float alpha = 1;
Paul's avatar
Paul committed
312
        float beta  = 0;
Paul's avatar
Add cbr  
Paul committed
313
314
        miopenSetOpArgsConvForward(fargs.get(), conv, &alpha, &beta, args[1].implicit());
        miopenSetOpArgsBiasForward(fargs.get(), bias, &alpha, &beta, args[3].implicit());
Paul's avatar
Paul committed
315
316
        miopenSetOpArgsActivForward(fargs.get(), relu, &alpha, &beta, 0, 0, 0);
        return f.execute(ctx, fargs, args[0], args[4]);
Paul's avatar
Add cbr  
Paul committed
317
    }
Paul's avatar
Paul committed
318
319
    void finalize(context& ctx, const shape&, const std::vector<shape>&) { f.compile(ctx); }
    shape get_workspace(context& ctx) { return f.get_workspace(ctx); }
Paul's avatar
Paul committed
320
    int output_alias(const std::vector<shape>& shapes) const { return shapes.size() - 1; }
Paul's avatar
Add cbr  
Paul committed
321
322
};

Paul's avatar
Paul committed
323
template <class... Ms>
Paul's avatar
Add cbr  
Paul committed
324
325
auto conv_bias(Ms... ms)
{
Paul's avatar
Paul committed
326
    return match::name("gpu::add")(
Paul's avatar
Paul committed
327
328
        match::either_arg(0, 1)(bias_shape(match::used_once()).bind("bias"),
                                fusable_conv(match::used_once()).bind("conv")),
Paul's avatar
Paul committed
329
        ms...);
Paul's avatar
Paul committed
330
331
}

Paul's avatar
Paul committed
332
template <class Op>
Paul's avatar
Paul committed
333
334
335
336
337
338
339
340
341
342
343
void apply_conv_bias(context& ctx, program& p, match::matcher_result r)
{
    auto conv_ins    = r.instructions["conv"];
    auto bias_ins    = r.instructions["bias"];
    auto ins         = r.result;
    auto input_ins   = conv_ins->inputs().at(0);
    auto weights_ins = conv_ins->inputs().at(1);
    auto conv_op     = any_cast<miopen_convolution>(conv_ins->get_operator()).op;
    auto alloc_ins   = ins->inputs().back();
    auto old_ws_ins  = conv_ins->inputs().at(2);

Paul's avatar
Paul committed
344
    Op cb{conv_op, input_ins->get_shape(), weights_ins->get_shape(), bias_ins->get_shape()};
Paul's avatar
Paul committed
345
    // TODO: Insert ws allocation
Paul's avatar
Paul committed
346
    auto ws = cb.get_workspace(ctx);
Paul's avatar
Paul committed
347
348

    p.replace_instruction(ins, cb, input_ins, weights_ins, old_ws_ins, bias_ins, alloc_ins);
Paul's avatar
Add cbr  
Paul committed
349
350
}

Paul's avatar
Paul committed
351
struct find_conv_bias
Paul's avatar
Paul committed
352
{
Paul's avatar
Paul committed
353
    context* ctx = nullptr;
Paul's avatar
Paul committed
354
355
    auto matcher() const
    {
Paul's avatar
Add cbr  
Paul committed
356
        return conv_bias(match::none_of(match::output(match::name("gpu::relu"))));
Paul's avatar
Paul committed
357
358
359
360
    }

    void apply(program& p, match::matcher_result r) const
    {
Paul's avatar
Paul committed
361
        apply_conv_bias<miopen_conv_bias>(*ctx, p, std::move(r));
Paul's avatar
Paul committed
362
363
364
    }
};

Paul's avatar
Paul committed
365
struct find_conv_bias_relu
Paul's avatar
Add cbr  
Paul committed
366
367
{
    context* ctx = nullptr;
Paul's avatar
Paul committed
368
    auto matcher() const { return match::name("gpu::relu")(match::arg(0)(conv_bias())); }
Paul's avatar
Add cbr  
Paul committed
369
370
371

    void apply(program& p, match::matcher_result r) const
    {
Paul's avatar
Paul committed
372
        apply_conv_bias<miopen_conv_bias_relu>(*ctx, p, std::move(r));
Paul's avatar
Add cbr  
Paul committed
373
374
375
    }
};

Paul's avatar
Paul committed
376
377
void fuse_ops::apply(program& p) const
{
Paul's avatar
Paul committed
378
    // clang-format off
Paul's avatar
Paul committed
379
    match::find_matches(p, find_triadd{});
Paul's avatar
Paul committed
380
    match::find_matches(p, 
Paul's avatar
Paul committed
381
382
383
        find_conv_bias_relu{ctx},
        find_conv_bias{ctx},
        find_add_relu{}
Paul's avatar
Paul committed
384
385
    );
    // clang-format on
Paul's avatar
Paul committed
386
}
Paul's avatar
Paul committed
387
388

} // namespace gpu
Paul's avatar
Paul committed
389
} // namespace MIGRAPHX_INLINE_NS
Paul's avatar
Paul committed
390
} // namespace migraphx