fuse_ops.cpp 19.6 KB
Newer Older
Paul's avatar
Paul committed
1
2
3
#include <migraphx/gpu/fuse_ops.hpp>
#include <migraphx/matcher.hpp>
#include <migraphx/gpu/miopen.hpp>
kahmed10's avatar
kahmed10 committed
4
#include <migraphx/gpu/clip.hpp>
Paul's avatar
Paul committed
5
#include <migraphx/gpu/convolution.hpp>
6
#include <migraphx/gpu/oper.hpp>
Paul's avatar
Paul committed
7
#include <migraphx/gpu/device/mul_add.hpp>
8
9
10
11
12
#include <migraphx/gpu/device/add_clip.hpp>
#include <migraphx/gpu/device/add_relu.hpp>
#include <migraphx/gpu/device/add_sigmoid.hpp>
#include <migraphx/gpu/device/add_tanh.hpp>
#include <migraphx/gpu/device/mul_add_relu.hpp>
Paul's avatar
Paul committed
13
#include <migraphx/gpu/device/add.hpp>
Paul's avatar
Paul committed
14
#include <migraphx/instruction.hpp>
Paul's avatar
Paul committed
15
#include <migraphx/array.hpp>
kahmed10's avatar
kahmed10 committed
16
#include <migraphx/op/clip.hpp>
Paul's avatar
Paul committed
17
18

namespace migraphx {
Paul's avatar
Paul committed
19
inline namespace MIGRAPHX_INLINE_NS {
Paul's avatar
Paul committed
20
21
namespace gpu {

22
23
MIGRAPHX_DECLARE_ENV_VAR(MIGRAPHX_DISABLE_MIOPEN_FUSION)

Paul's avatar
Paul committed
24
25
26
27
28
29
30
31
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
32
    template <class T>
Paul's avatar
Paul committed
33
34
35
36
37
38
39
40
41
42
    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))
    {
43
        assert(input.standard());
Paul's avatar
Paul committed
44
        auto t = make_tensor(input);
Paul's avatar
Paul committed
45
        fp     = make_fusion_plan(t);
Paul's avatar
Paul committed
46
47
48
49
50
51
52
53
        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
54
            MIGRAPHX_THROW("Failed retrieving operator at " + std::to_string(i));
Paul's avatar
Paul committed
55
56
57
        return result;
    }

Paul's avatar
Paul committed
58
    auto get() const { return fp.get(); }
Paul's avatar
Paul committed
59
60
61
62

    op_t create_bias(const shape& bias)
    {
        op_t result;
Paul's avatar
Paul committed
63
64
        auto b      = shape{bias.type(), {1, bias.lens().at(1), 1, 1}};
        auto t      = keep_alive(make_tensor(b));
Paul's avatar
Paul committed
65
66
        auto status = miopenCreateOpBiasForward(fp.get(), &result, t.get());
        if(status != miopenStatusSuccess)
Paul's avatar
Paul committed
67
            MIGRAPHX_THROW("Creating operator failed");
Paul's avatar
Paul committed
68
69
70
71
72
73
74
75
        return result;
    }

    op_t create_relu()
    {
        op_t result;
        auto status = miopenCreateOpActivationForward(fp.get(), &result, miopenActivationRELU);
        if(status != miopenStatusSuccess)
Paul's avatar
Paul committed
76
            MIGRAPHX_THROW("Creating operator failed");
Paul's avatar
Paul committed
77
78
79
80
81
82
        return result;
    }

    op_t create_conv(const op::convolution& op, const shape& weights)
    {
        op_t result;
Paul's avatar
Paul committed
83
84
        auto cd     = keep_alive(make_conv(op));
        auto t      = keep_alive(make_tensor(weights));
Paul's avatar
Paul committed
85
86
        auto status = miopenCreateOpConvForward(fp.get(), &result, cd.get(), t.get());
        if(status != miopenStatusSuccess)
Paul's avatar
Paul committed
87
            MIGRAPHX_THROW("Creating operator failed");
Paul's avatar
Paul committed
88
89
        return result;
    }
Paul's avatar
Paul committed
90
91
92
93
94
95
96
97

    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
98
99
        // miopenFusionPlanGetWorkSpaceSize(ctx.get_stream().get_miopen(), fp.get(), &ws_size,
        // algo);
Paul's avatar
Paul committed
100
101
102
103
104
        return shape{shape::int8_type, {ws_size}};
    }

    void compile(context& ctx)
    {
Paul's avatar
Paul committed
105
        auto status = miopenCompileFusionPlan(ctx.get_stream().get_miopen(), fp.get());
Paul's avatar
Paul committed
106
        if(status != miopenStatusSuccess)
Paul's avatar
Paul committed
107
            MIGRAPHX_THROW("Compiling fusion plan failed");
Paul's avatar
Paul committed
108
109
    }

Paul's avatar
Paul committed
110
111
112
113
    argument execute(context& ctx,
                     const fused_operator_args& fargs,
                     const argument& x,
                     const argument& y) const
Paul's avatar
Paul committed
114
    {
Paul's avatar
Paul committed
115
116
        auto x_td   = make_tensor(x.get_shape());
        auto y_td   = make_tensor(y.get_shape());
Paul's avatar
Paul committed
117
        auto status = miopenExecuteFusionPlan(ctx.get_stream().get_miopen(),
Paul's avatar
Paul committed
118
119
120
121
122
123
                                              fp.get(),
                                              x_td.get(),
                                              x.implicit(),
                                              y_td.get(),
                                              y.implicit(),
                                              fargs.get());
Paul's avatar
Paul committed
124
        if(status != miopenStatusSuccess)
Paul's avatar
Paul committed
125
            MIGRAPHX_THROW("Failed to execute fusion plan");
Paul's avatar
Paul committed
126
127
        return y;
    }
Paul's avatar
Paul committed
128
129
};

Paul's avatar
Paul committed
130
MIGRAPHX_PRED_MATCHER(bias_shape, instruction_ref ins)
Paul's avatar
Paul committed
131
132
{
    auto&& s = ins->get_shape();
Paul's avatar
Paul committed
133
134
    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
135
136
}

Paul's avatar
Paul committed
137
MIGRAPHX_PRED_MATCHER(fusable_conv, instruction_ref ins)
Paul's avatar
Paul committed
138
{
139
140
    if(enabled(MIGRAPHX_DISABLE_MIOPEN_FUSION{}))
        return false;
Paul's avatar
Paul committed
141
142
    if(ins->name() != "gpu::convolution")
        return false;
Paul's avatar
Paul committed
143
144
    if(ins->get_shape().type() != shape::float_type)
        return false;
Paul's avatar
Paul committed
145
146
147
    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
148
    if(conv.op.group > 1)
Khalique's avatar
Khalique committed
149
        return false;
Paul's avatar
Paul committed
150
    if(wei.lens()[1] > 512 and conv.algo != miopenConvolutionFwdAlgoWinograd)
Paul's avatar
Paul committed
151
        return false;
152
153
154
155
156
157

    // Do not fuse non-symmetric input
    auto input_lens = ins->inputs().at(0)->get_shape().lens();
    if(input_lens[2] != input_lens[3] or wei.lens()[2] != wei.lens()[3])
        return false;

Paul's avatar
Paul committed
158
    auto op = conv.op;
159
160
161
162
    // Dont fuse winograd for non-3x3s since there is no fused windograd for those configs
    if(conv.algo == miopenConvolutionFwdAlgoWinograd and wei.lens()[2] != 3 and
       wei.lens()[3] != 3 and op.stride == make_array<size_t>(1, 1))
        return false;
Paul's avatar
Paul committed
163
164
    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
165
166
}

Paul's avatar
Paul committed
167
168
169
170
171
172
173
174
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
175
    argument compute(context& ctx, const shape&, const std::vector<argument>& args) const
Paul's avatar
Paul committed
176
    {
Paul's avatar
Paul committed
177
        device::add(ctx.get_stream().get(), args.at(3), args.at(0), args.at(1), args.at(2));
Paul's avatar
Paul committed
178
179
        return args.at(3);
    }
Paul's avatar
Paul committed
180
181
182
183
    std::ptrdiff_t output_alias(const std::vector<shape>& shapes) const
    {
        return shapes.size() - 1;
    }
Paul's avatar
Paul committed
184
185
};

kahmed10's avatar
kahmed10 committed
186
187
188
189
190
struct hip_triadd_clip
{
    std::string name() const { return "hip::triadd_clip"; }
    shape compute_shape(const std::vector<shape>& inputs) const
    {
kahmed10's avatar
kahmed10 committed
191
        check_shapes{inputs, *this}.has(6);
kahmed10's avatar
kahmed10 committed
192
193
194
195
196
        return inputs.front();
    }
    argument compute(context& ctx, const shape&, const std::vector<argument>& args) const
    {
        device::add_clip(ctx.get_stream().get(),
kahmed10's avatar
kahmed10 committed
197
                         args.at(5),
kahmed10's avatar
kahmed10 committed
198
199
200
                         args.at(0),
                         args.at(1),
                         args.at(2),
kahmed10's avatar
kahmed10 committed
201
202
203
                         args.at(3),
                         args.at(4));
        return args.at(5);
kahmed10's avatar
kahmed10 committed
204
205
206
207
208
209
210
211
212
213
214
215
    }
    std::ptrdiff_t output_alias(const std::vector<shape>& shapes) const
    {
        return shapes.size() - 1;
    }
};

struct hip_add_clip
{
    std::string name() const { return "hip::add_clip"; }
    shape compute_shape(const std::vector<shape>& inputs) const
    {
kahmed10's avatar
kahmed10 committed
216
        check_shapes{inputs, *this}.has(5);
kahmed10's avatar
kahmed10 committed
217
218
219
220
221
        return inputs.front();
    }
    argument compute(context& ctx, const shape&, const std::vector<argument>& args) const
    {
        device::add_clip(
kahmed10's avatar
kahmed10 committed
222
223
            ctx.get_stream().get(), args.at(4), args.at(0), args.at(1), args.at(2), args.at(3));
        return args.at(4);
kahmed10's avatar
kahmed10 committed
224
225
226
227
228
229
230
    }
    std::ptrdiff_t output_alias(const std::vector<shape>& shapes) const
    {
        return shapes.size() - 1;
    }
};

231
struct hip_triadd_relu : ternary_device<hip_triadd_relu, &device::add_relu>
Paul's avatar
Paul committed
232
233
234
{
};

235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
struct hip_triadd_sigmoid : ternary_device<hip_triadd_sigmoid, &device::add_sigmoid>
{
};

struct hip_triadd_tanh : ternary_device<hip_triadd_tanh, &device::add_tanh>
{
};

struct hip_add_relu : binary_device<hip_add_relu, &device::add_relu>
{
};

struct hip_add_sigmoid : binary_device<hip_add_relu, &device::add_sigmoid>
{
};

struct hip_add_tanh : binary_device<hip_add_tanh, &device::add_tanh>
Paul's avatar
Paul committed
252
253
254
{
};

Paul's avatar
Paul committed
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
struct hip_mul_add
{
    std::string name() const { return "hip::mul_add"; }
    shape compute_shape(const std::vector<shape>& inputs) const
    {
        check_shapes{inputs, *this}.has(4);
        return inputs.front();
    }
    argument compute(context& ctx, const shape&, const std::vector<argument>& args) const
    {
        device::mul_add(ctx.get_stream().get(), args.at(3), args.at(0), args.at(1), args.at(2));
        return args.at(3);
    }
    std::ptrdiff_t output_alias(const std::vector<shape>& shapes) const
    {
        return shapes.size() - 1;
    }
};

Paul's avatar
Paul committed
274
275
276
277
278
279
280
281
282
283
struct hip_mul_add_relu
{
    std::string name() const { return "hip::mul_add_relu"; }
    shape compute_shape(const std::vector<shape>& inputs) const
    {
        check_shapes{inputs, *this}.has(4);
        return inputs.front();
    }
    argument compute(context& ctx, const shape&, const std::vector<argument>& args) const
    {
Paul's avatar
Paul committed
284
285
        device::mul_add_relu(
            ctx.get_stream().get(), args.at(3), args.at(0), args.at(1), args.at(2));
Paul's avatar
Paul committed
286
287
288
289
290
291
292
293
        return args.at(3);
    }
    std::ptrdiff_t output_alias(const std::vector<shape>& shapes) const
    {
        return shapes.size() - 1;
    }
};

Paul's avatar
Paul committed
294
295
296
void move_broadcasted_back(std::vector<instruction_ref>& args)
{
    // Ensure the last arguments is the broadcasted one
Paul's avatar
Paul committed
297
    auto last = std::prev(args.end());
Paul's avatar
Paul committed
298
299
    auto it =
        std::find_if(args.begin(), last, [](auto arg) { return arg->get_shape().broadcasted(); });
Paul's avatar
Paul committed
300
301
    if(it != last)
        std::swap(*it, *std::prev(last));
Paul's avatar
Paul committed
302
303
304
305
306
}

void move_standard_front(std::vector<instruction_ref>& args)
{
    // Ensure the first arguments is the standard one
Paul's avatar
Paul committed
307
    auto last = std::prev(args.end());
Paul's avatar
Paul committed
308
309
    auto it =
        std::find_if(args.begin(), last, [](auto arg) { return arg->get_shape().standard(); });
Paul's avatar
Paul committed
310
    if(it != last)
Paul's avatar
Paul committed
311
312
313
        std::swap(*it, args.front());
}

kahmed10's avatar
kahmed10 committed
314
315
316
317
318
319
320
321
322
323
324
325
326
struct find_add_clip
{
    auto matcher() const
    {
        return match::name(std::unordered_set<std::string>{"gpu::clip", "gpu::clipped_relu"})(
            match::arg(0)(match::any_of(match::name("gpu::add"),
                                        match::name("hip::triadd"),
                                        match::any_of[match::inputs()](match::standard_shape()))
                              .bind("add")));
    }

    void apply(program& p, match::matcher_result r) const
    {
kahmed10's avatar
kahmed10 committed
327
328
329
330
331
332
333
334
335
336
        auto add_ins  = r.instructions["add"];
        auto ins      = r.result;
        auto ins_args = ins->inputs();
        auto add_args = add_ins->inputs();
        move_standard_front(add_args);
        move_broadcasted_back(add_args);

        // Use the allocation from the clip operator
        add_args.pop_back();
        add_args.insert(add_args.end(), std::next(ins_args.begin()), ins_args.end());
kahmed10's avatar
kahmed10 committed
337
        if(add_ins->name() == "gpu::add")
kahmed10's avatar
kahmed10 committed
338
            p.replace_instruction(ins, hip_add_clip{}, add_args);
kahmed10's avatar
kahmed10 committed
339
        else if(add_ins->name() == "hip::triadd")
kahmed10's avatar
kahmed10 committed
340
            p.replace_instruction(ins, hip_triadd_clip{}, add_args);
kahmed10's avatar
kahmed10 committed
341
342
343
    }
};

344
struct find_add_unary
Paul's avatar
Paul committed
345
{
346
347
348
    std::string op_name;
    operation binary_add_op;
    operation ternary_add_op;
Paul's avatar
Paul committed
349
350
    auto matcher() const
    {
351
        return match::name(op_name)(match::arg(0)(
Paul's avatar
Paul committed
352
            match::used_once(),
Paul's avatar
Paul committed
353
354
355
356
357
            match::any_of(match::name("gpu::add"),
                          match::name("hip::triadd"),
                          match::any_of(match::name("@literal"),
                                        match::any_of[match::inputs()](match::standard_shape())))
                .bind("add")));
Paul's avatar
Paul committed
358
    }
Paul's avatar
Paul committed
359

Paul's avatar
Paul committed
360
361
    void apply(program& p, match::matcher_result r) const
    {
Paul's avatar
Paul committed
362
        auto add_ins = r.instructions["add"];
Paul's avatar
Paul committed
363
364
        auto ins     = r.result;
        auto args    = add_ins->inputs();
Paul's avatar
Paul committed
365
366
367
        move_standard_front(args);
        move_broadcasted_back(args);

Paul's avatar
Paul committed
368
        // Use the allocation from the relu operator
Paul's avatar
Paul committed
369
        args.back() = ins->inputs().back();
Paul's avatar
Paul committed
370
        if(add_ins->name() == "gpu::add")
371
            p.replace_instruction(ins, binary_add_op, args);
Paul's avatar
Paul committed
372
        else if(add_ins->name() == "hip::triadd")
373
            p.replace_instruction(ins, ternary_add_op, args);
Paul's avatar
Paul committed
374
375
376
    }
};

Paul's avatar
Paul committed
377
struct find_triadd
Paul's avatar
Paul committed
378
379
380
{
    auto matcher() const
    {
Paul's avatar
Paul committed
381
        return match::name("gpu::add")(match::either_arg(0, 1)(
Paul's avatar
Paul committed
382
            match::name("gpu::add")(match::used_once()).bind("add"),
Paul's avatar
Paul committed
383
384
385
            match::any(match::any_of(match::name("@literal"),
                                     match::any_of[match::inputs()](match::standard_shape())))
                .bind("input")));
Paul's avatar
Paul committed
386
387
388
389
    }

    void apply(program& p, match::matcher_result r) const
    {
Paul's avatar
Paul committed
390
391
392
393
        auto add_ins   = r.instructions["add"];
        auto input_ins = r.instructions["input"];
        auto ins       = r.result;
        auto args      = add_ins->inputs();
394
395
        assert(add_ins != input_ins);

Paul's avatar
Paul committed
396
397
398
399
        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);
Paul's avatar
Paul committed
400
401
402
        move_standard_front(args);
        move_broadcasted_back(args);

Paul's avatar
Paul committed
403
404
        args.back() = ins->inputs().back();
        p.replace_instruction(ins, hip_triadd{}, args);
Paul's avatar
Paul committed
405
    }
Paul's avatar
Paul committed
406
407
};

Paul's avatar
Paul committed
408
409
410
411
struct find_mul_add
{
    auto matcher() const
    {
Paul's avatar
Paul committed
412
413
        return match::name("gpu::add")(match::either_arg(0, 1)(
            match::name("gpu::mul")(match::used_once()).bind("mul"), match::any().bind("b")));
Paul's avatar
Paul committed
414
415
416
417
    }

    void apply(program& p, match::matcher_result r) const
    {
Paul's avatar
Paul committed
418
419
420
421
        auto mul_ins = r.instructions["mul"];
        auto b_ins   = r.instructions["b"];
        auto ins     = r.result;
        auto args    = mul_ins->inputs();
Paul's avatar
Paul committed
422
423
424
425
426
427
428
429
430
431
432
        assert(mul_ins != b_ins);

        move_standard_front(args);
        move_broadcasted_back(args);
        args.insert(std::prev(args.end()), b_ins);

        args.back() = ins->inputs().back();
        p.replace_instruction(ins, hip_mul_add{}, args);
    }
};

Paul's avatar
Paul committed
433
434
435
436
struct find_mul_add_relu
{
    auto matcher() const
    {
Paul's avatar
Paul committed
437
438
        return match::name("gpu::relu")(
            match::arg(0)(match::name("hip::mul_add")(match::used_once()).bind("mul_add")));
Paul's avatar
Paul committed
439
440
441
442
443
    }

    void apply(program& p, match::matcher_result r) const
    {
        auto mul_add_ins = r.instructions["mul_add"];
Paul's avatar
Paul committed
444
445
        auto ins         = r.result;
        auto args        = mul_add_ins->inputs();
Paul's avatar
Paul committed
446
447
448
449
450
451
452

        // Use the allocation from the relu operator
        args.back() = ins->inputs().back();
        p.replace_instruction(ins, hip_mul_add_relu{}, args);
    }
};

Paul's avatar
Paul committed
453
454
455
456
457
458
459
struct miopen_conv_bias
{
    op::convolution op;
    fusion f;
    fusion::op_t conv;
    fusion::op_t bias;

Paul's avatar
Paul committed
460
461
462
463
464
465
    template <class Self, class F>
    static auto reflect(Self& self, F f)
    {
        return op::convolution::reflect(self.op, f);
    }

Paul's avatar
Paul committed
466
467
    miopen_conv_bias(op::convolution c, const shape& input, const shape& weights, const shape& b)
        : op(c), f(input)
Paul's avatar
Paul committed
468
    {
Paul's avatar
Paul committed
469
470
        conv = f.create_conv(op, weights);
        bias = f.create_bias(b);
Paul's avatar
Paul committed
471
472
473
474
475
476
477
478
479
    }

    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
480
    argument compute(context& ctx, const shape&, const std::vector<argument>& args) const
Paul's avatar
Paul committed
481
    {
Paul's avatar
Paul committed
482
        auto fargs  = make_fused_args();
Paul's avatar
Paul committed
483
        float alpha = 1;
Paul's avatar
Paul committed
484
        float beta  = 0;
Paul's avatar
Paul committed
485
486
        miopenSetOpArgsConvForward(fargs.get(), conv, &alpha, &beta, args[1].implicit());
        miopenSetOpArgsBiasForward(fargs.get(), bias, &alpha, &beta, args[3].implicit());
Paul's avatar
Paul committed
487
        return f.execute(ctx, fargs, args[0], args[4]);
Paul's avatar
Paul committed
488
489
    }

Paul's avatar
Paul committed
490
491
    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
492
493
494
495
    std::ptrdiff_t output_alias(const std::vector<shape>& shapes) const
    {
        return shapes.size() - 1;
    }
Paul's avatar
Paul committed
496
497
};

Paul's avatar
Add cbr  
Paul committed
498
499
500
501
502
503
struct miopen_conv_bias_relu
{
    op::convolution op;
    fusion f;
    fusion::op_t conv;
    fusion::op_t bias;
Paul's avatar
Paul committed
504
    fusion::op_t relu;
Paul's avatar
Add cbr  
Paul committed
505

Paul's avatar
Paul committed
506
507
508
509
510
511
    template <class Self, class F>
    static auto reflect(Self& self, F f)
    {
        return op::convolution::reflect(self.op, f);
    }

Paul's avatar
Paul committed
512
513
514
515
516
    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
517
    {
Paul's avatar
Paul committed
518
519
520
        conv = f.create_conv(op, weights);
        bias = f.create_bias(b);
        relu = f.create_relu();
Paul's avatar
Add cbr  
Paul committed
521
522
523
524
525
526
527
528
529
    }

    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
530
    argument compute(context& ctx, const shape&, const std::vector<argument>& args) const
Paul's avatar
Add cbr  
Paul committed
531
532
    {
        auto fargs  = make_fused_args();
Paul's avatar
Paul committed
533
        float alpha = 1;
Paul's avatar
Paul committed
534
        float beta  = 0;
Paul's avatar
Add cbr  
Paul committed
535
536
        miopenSetOpArgsConvForward(fargs.get(), conv, &alpha, &beta, args[1].implicit());
        miopenSetOpArgsBiasForward(fargs.get(), bias, &alpha, &beta, args[3].implicit());
Paul's avatar
Paul committed
537
538
        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
539
    }
Paul's avatar
Paul committed
540
541
    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
542
543
544
545
    std::ptrdiff_t output_alias(const std::vector<shape>& shapes) const
    {
        return shapes.size() - 1;
    }
Paul's avatar
Add cbr  
Paul committed
546
547
};

Paul's avatar
Paul committed
548
template <class... Ms>
Paul's avatar
Add cbr  
Paul committed
549
550
auto conv_bias(Ms... ms)
{
Paul's avatar
Paul committed
551
    return match::name("gpu::add")(
Paul's avatar
Paul committed
552
553
        match::either_arg(0, 1)(bias_shape(match::used_once()).bind("bias"),
                                fusable_conv(match::used_once()).bind("conv")),
Paul's avatar
Paul committed
554
        ms...);
Paul's avatar
Paul committed
555
556
}

Paul's avatar
Paul committed
557
template <class Op>
Paul's avatar
Paul committed
558
559
560
561
562
563
564
565
566
567
568
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
569
    Op cb{conv_op, input_ins->get_shape(), weights_ins->get_shape(), bias_ins->get_shape()};
Paul's avatar
Paul committed
570
    // TODO: Insert ws allocation
Paul's avatar
Paul committed
571
    auto ws = cb.get_workspace(ctx);
Paul's avatar
Paul committed
572
    (void)ws;
Paul's avatar
Paul committed
573
    p.replace_instruction(ins, cb, input_ins, weights_ins, old_ws_ins, bias_ins, alloc_ins);
Paul's avatar
Add cbr  
Paul committed
574
575
}

Paul's avatar
Paul committed
576
struct find_conv_bias
Paul's avatar
Paul committed
577
{
Paul's avatar
Paul committed
578
    context* ctx = nullptr;
Paul's avatar
Paul committed
579
580
    auto matcher() const
    {
kahmed10's avatar
kahmed10 committed
581
582
        return conv_bias(match::none_of(
            match::output(match::name(std::unordered_set<std::string>{"gpu::relu"}))));
Paul's avatar
Paul committed
583
584
585
586
    }

    void apply(program& p, match::matcher_result r) const
    {
Paul's avatar
Paul committed
587
        apply_conv_bias<miopen_conv_bias>(*ctx, p, std::move(r));
Paul's avatar
Paul committed
588
589
590
    }
};

Paul's avatar
Paul committed
591
struct find_conv_bias_relu
Paul's avatar
Add cbr  
Paul committed
592
593
{
    context* ctx = nullptr;
Paul's avatar
Paul committed
594
    auto matcher() const { return match::name("gpu::relu")(match::arg(0)(conv_bias())); }
Paul's avatar
Add cbr  
Paul committed
595
596
597

    void apply(program& p, match::matcher_result r) const
    {
Paul's avatar
Paul committed
598
        apply_conv_bias<miopen_conv_bias_relu>(*ctx, p, std::move(r));
Paul's avatar
Add cbr  
Paul committed
599
600
601
    }
};

Paul's avatar
Paul committed
602
603
void fuse_ops::apply(program& p) const
{
Paul's avatar
Paul committed
604
    // clang-format off
Paul's avatar
Paul committed
605
    match::find_matches(p, find_triadd{});
Paul's avatar
Paul committed
606
    match::find_matches(p, 
Paul's avatar
Paul committed
607
608
        find_conv_bias_relu{ctx},
        find_conv_bias{ctx},
Paul's avatar
Paul committed
609
610
        find_mul_add{},
        find_mul_add_relu{},
611
612
        find_add_unary{"gpu::relu", hip_add_relu{}, hip_triadd_relu{}},
        find_add_unary{"gpu::sigmoid", hip_add_sigmoid{}, hip_triadd_sigmoid{}},
kahmed10's avatar
kahmed10 committed
613
614
        find_add_unary{"gpu::tanh", hip_add_tanh{}, hip_triadd_tanh{}},
        find_add_clip{}
Paul's avatar
Paul committed
615
616
    );
    // clang-format on
Paul's avatar
Paul committed
617
}
Paul's avatar
Paul committed
618
619

} // namespace gpu
Paul's avatar
Paul committed
620
} // namespace MIGRAPHX_INLINE_NS
Paul's avatar
Paul committed
621
} // namespace migraphx