fuse_ops.cpp 9.6 KB
Newer Older
Paul's avatar
Paul committed
1
#include <migraph/gpu/fuse_ops.hpp>
Paul's avatar
Paul committed
2
#include <migraph/matcher.hpp>
Paul's avatar
Paul committed
3
4
#include <migraph/gpu/miopen.hpp>
#include <migraph/gpu/convolution.hpp>
Paul's avatar
Paul committed
5
6
7
8
9
10
11
#include <migraph/gpu/device/add_relu.hpp>
#include <migraph/instruction.hpp>

namespace migraph {

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
41
42
43
44
        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)
            MIGRAPH_THROW("Failed retrieving operator at " + std::to_string(i));
        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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
        auto status = miopenCreateOpBiasForward(fp.get(), &result, t.get());
        if(status != miopenStatusSuccess)
            MIGRAPH_THROW("Creating operator failed");
        return result;
    }

    op_t create_relu()
    {
        op_t result;
        auto status = miopenCreateOpActivationForward(fp.get(), &result, miopenActivationRELU);
        if(status != miopenStatusSuccess)
            MIGRAPH_THROW("Creating operator failed");
        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
74
75
76
        auto status = miopenCreateOpConvForward(fp.get(), &result, cd.get(), t.get());
        if(status != miopenStatusSuccess)
            MIGRAPH_THROW("Creating operator failed");
        return result;
    }
Paul's avatar
Paul committed
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95

    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);
        // miopenFusionPlanGetWorkSpaceSize(ctx.handle.get(), fp.get(), &ws_size, algo);
        return shape{shape::int8_type, {ws_size}};
    }

    void compile(context& ctx)
    {
        auto status = miopenCompileFusionPlan(ctx.handle.get(), fp.get());
        if(status != miopenStatusSuccess)
            MIGRAPH_THROW("Compiling fusion plan failed");
    }

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

Paul's avatar
Paul committed
116
117
118
MIGRAPH_PRED_MATCHER(bias_shape, instruction_ref ins)
{
    auto&& s = ins->get_shape();
Paul's avatar
Paul committed
119
120
    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
121
122
123
}

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

MIGRAPH_PRED_MATCHER(fusable_conv, instruction_ref ins)
{
    if(ins->name() != "gpu::convolution")
        return false;
    auto op = any_cast<miopen_convolution>(ins->get_operator()).op;
Paul's avatar
Paul committed
135
136
    return op.padding == make_array<size_t>(0, 0) and op.stride == make_array<size_t>(1, 1) and
           op.dilation == make_array<size_t>(1, 1);
Paul's avatar
Paul committed
137
138
}

Paul's avatar
Paul committed
139
140
141
142
143
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
144
        check_shapes{inputs, *this}.has(3);
Paul's avatar
Paul committed
145
146
        return inputs.front();
    }
Paul's avatar
Paul committed
147
    argument compute(context&, const shape&, const std::vector<argument>& args) const
Paul's avatar
Paul committed
148
    {
149
        device::add_relu(args.at(2), args.at(0), args.at(1));
Paul's avatar
Paul committed
150
151
152
153
        return args.at(2);
    }
};

Paul's avatar
Paul committed
154
struct match_add_relu
Paul's avatar
Paul committed
155
{
Paul's avatar
Paul committed
156
157
    auto matcher() const
    {
Paul's avatar
Paul committed
158
        return match::name("gpu::relu")(match::arg(0)(match::name("gpu::add").bind("add")));
Paul's avatar
Paul committed
159
    }
Paul's avatar
Paul committed
160

Paul's avatar
Paul committed
161
162
    void apply(program& p, match::matcher_result r) const
    {
Paul's avatar
Paul committed
163
        auto add_ins = r.instructions["add"];
Paul's avatar
Paul committed
164
165
        auto ins     = r.result;
        auto args    = add_ins->inputs();
Paul's avatar
Paul committed
166
        // Use the allocation from the relu operator
Paul's avatar
Paul committed
167
        args.back() = ins->inputs().back();
Paul's avatar
Paul committed
168
        p.replace_instruction(ins, hip_add_relu{}, args);
Paul's avatar
Paul committed
169
    }
Paul's avatar
Paul committed
170
171
};

Paul's avatar
Paul committed
172
173
174
175
176
177
178
struct miopen_conv_bias
{
    op::convolution op;
    fusion f;
    fusion::op_t conv;
    fusion::op_t bias;

Paul's avatar
Paul committed
179
180
    miopen_conv_bias(op::convolution c, const shape& input, const shape& weights, const shape& b)
        : op(c), f(input)
Paul's avatar
Paul committed
181
    {
Paul's avatar
Paul committed
182
183
        conv = f.create_conv(op, weights);
        bias = f.create_bias(b);
Paul's avatar
Paul committed
184
185
186
187
188
189
190
191
192
    }

    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
193
    argument compute(context& ctx, const shape&, const std::vector<argument>& args) const
Paul's avatar
Paul committed
194
    {
Paul's avatar
Paul committed
195
        auto fargs  = make_fused_args();
Paul's avatar
Paul committed
196
197
198
        float alpha = 1, beta = 0;
        miopenSetOpArgsConvForward(fargs.get(), conv, &alpha, &beta, args[1].implicit());
        miopenSetOpArgsBiasForward(fargs.get(), bias, &alpha, &beta, args[3].implicit());
Paul's avatar
Paul committed
199
        return f.execute(ctx, fargs, args[0], args[4]);
Paul's avatar
Paul committed
200
201
202
203
    }

    shape compile(context& ctx)
    {
Paul's avatar
Paul committed
204
205
        f.compile(ctx);
        return f.get_workspace(ctx);
Paul's avatar
Paul committed
206
207
208
    }
};

Paul's avatar
Add cbr  
Paul committed
209
210
211
212
213
214
struct miopen_conv_bias_relu
{
    op::convolution op;
    fusion f;
    fusion::op_t conv;
    fusion::op_t bias;
Paul's avatar
Paul committed
215
    fusion::op_t relu;
Paul's avatar
Add cbr  
Paul committed
216

Paul's avatar
Paul committed
217
218
219
220
221
    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
222
    {
Paul's avatar
Paul committed
223
224
225
        conv = f.create_conv(op, weights);
        bias = f.create_bias(b);
        relu = f.create_relu();
Paul's avatar
Add cbr  
Paul committed
226
227
228
229
230
231
232
233
234
    }

    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
235
    argument compute(context& ctx, const shape&, const std::vector<argument>& args) const
Paul's avatar
Add cbr  
Paul committed
236
237
238
239
240
    {
        auto fargs  = make_fused_args();
        float alpha = 1, beta = 0;
        miopenSetOpArgsConvForward(fargs.get(), conv, &alpha, &beta, args[1].implicit());
        miopenSetOpArgsBiasForward(fargs.get(), bias, &alpha, &beta, args[3].implicit());
Paul's avatar
Paul committed
241
242
        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
243
244
245
246
    }

    shape compile(context& ctx)
    {
Paul's avatar
Paul committed
247
248
        f.compile(ctx);
        return f.get_workspace(ctx);
Paul's avatar
Add cbr  
Paul committed
249
250
251
    }
};

Paul's avatar
Paul committed
252
template <class... Ms>
Paul's avatar
Add cbr  
Paul committed
253
254
auto conv_bias(Ms... ms)
{
Paul's avatar
Paul committed
255
256
    return match::name("gpu::add")(match::either_arg(0, 1)(match::arg(0)(bias_shape(match::output())).bind("bias"),
                                                           fusable_conv(match::output()).bind("conv")), match::output(),
Paul's avatar
Paul committed
257
                                   ms...);
Paul's avatar
Paul committed
258
259
}

Paul's avatar
Paul committed
260
template <class Op>
Paul's avatar
Paul committed
261
262
263
264
265
266
267
268
269
270
271
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
272
    Op cb{conv_op, input_ins->get_shape(), weights_ins->get_shape(), bias_ins->get_shape()};
Paul's avatar
Paul committed
273
274
275
276
    // TODO: Insert ws allocation
    auto ws = cb.compile(ctx);

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

Paul's avatar
Paul committed
279
280
struct match_conv_bias
{
Paul's avatar
Paul committed
281
    context* ctx = nullptr;
Paul's avatar
Paul committed
282
283
    auto matcher() const
    {
Paul's avatar
Add cbr  
Paul committed
284
        return conv_bias(match::none_of(match::output(match::name("gpu::relu"))));
Paul's avatar
Paul committed
285
286
287
288
    }

    void apply(program& p, match::matcher_result r) const
    {
Paul's avatar
Paul committed
289
        apply_conv_bias<miopen_conv_bias>(*ctx, p, std::move(r));
Paul's avatar
Paul committed
290
291
292
    }
};

Paul's avatar
Add cbr  
Paul committed
293
294
295
struct match_conv_bias_relu
{
    context* ctx = nullptr;
Paul's avatar
Paul committed
296
    auto matcher() const { return match::name("gpu::relu")(match::arg(0)(conv_bias())); }
Paul's avatar
Add cbr  
Paul committed
297
298
299

    void apply(program& p, match::matcher_result r) const
    {
Paul's avatar
Paul committed
300
        apply_conv_bias<miopen_conv_bias_relu>(*ctx, p, std::move(r));
Paul's avatar
Add cbr  
Paul committed
301
302
303
    }
};

Paul's avatar
Paul committed
304
305
void fuse_ops::apply(program& p) const
{
Paul's avatar
Paul committed
306
307
    // match::find_matches(p, match_conv_bias_relu{ctx}, match_conv_bias{ctx}, match_add_relu{});
    match::find_matches(p, match_conv_bias{ctx}, match_add_relu{});
Paul's avatar
Paul committed
308
}
Paul's avatar
Paul committed
309
310
311
312

} // namespace gpu

} // namespace migraph