simplify_algebra.cpp 14 KB
Newer Older
Paul's avatar
Paul committed
1
#include <migraphx/simplify_algebra.hpp>
Paul's avatar
Paul committed
2
#include <migraphx/dead_code_elimination.hpp>
Paul's avatar
Paul committed
3
#include <migraphx/program.hpp>
4
#include <migraphx/op/add.hpp>
Paul's avatar
Paul committed
5
#include <migraphx/op/mul.hpp>
6
7
8
#include <migraphx/op/concat.hpp>
#include <migraphx/op/convolution.hpp>
#include <migraphx/op/as_shape.hpp>
Paul's avatar
Paul committed
9
#include <migraphx/op/broadcast.hpp>
10
11
#include <migraphx/op/neg.hpp>
#include <migraphx/op/recip.hpp>
kahmed10's avatar
kahmed10 committed
12
#include <migraphx/op/rsqrt.hpp>
Paul's avatar
Paul committed
13
14
#include <migraphx/matcher.hpp>
#include <migraphx/literal.hpp>
Paul's avatar
Paul committed
15

Paul's avatar
Paul committed
16
namespace migraphx {
Paul's avatar
Paul committed
17
inline namespace MIGRAPHX_INLINE_NS {
Paul's avatar
Paul committed
18

Paul's avatar
Paul committed
19
auto lit_broadcast() { return match::any_of(match::is_constant(), match::name("broadcast")); }
Paul's avatar
Paul committed
20
auto not_lit_broadcast() { return match::none_of(match::is_constant(), match::name("broadcast")); }
Paul's avatar
Paul committed
21
22
auto op_lit_broadcast(std::string op, std::string x, std::string y)
{
Paul's avatar
Paul committed
23
24
    return match::name(std::move(op))(match::either_arg(0, 1)(
        lit_broadcast().bind(std::move(x)), not_lit_broadcast().bind(std::move(y))));
Paul's avatar
Paul committed
25
26
}

Paul's avatar
Paul committed
27
28
auto conv_const_weights()
{
Paul's avatar
Paul committed
29
    return match::name("convolution")(match::used_once(),
Paul's avatar
Paul committed
30
                                      match::args(match::any(), match::is_constant().bind("w")));
Paul's avatar
Paul committed
31
32
}

33
34
35
36
37
38
39
40
41
MIGRAPHX_PRED_MATCHER(args_has_same_ops, instruction_ref ins)
{
    if(ins->inputs().empty())
        return true;
    return std::all_of(ins->inputs().begin(), ins->inputs().end(), [&](auto j) {
        return j->get_operator() == ins->inputs().front()->get_operator();
    });
}

Paul's avatar
Paul committed
42
43
44
struct find_mul_conv
{
    auto matcher() const
Paul's avatar
Paul committed
45
    {
Paul's avatar
Paul committed
46
47
        return match::name("mul")(match::either_arg(0, 1)(conv_const_weights().bind("conv"),
                                                          match::name("broadcast").bind("a")));
Paul's avatar
Paul committed
48
    }
Paul's avatar
Paul committed
49
50

    void apply(program& p, match::matcher_result r) const
Paul's avatar
Paul committed
51
    {
Paul's avatar
Paul committed
52
        auto ins      = r.result;
Paul's avatar
Paul committed
53
        auto conv_ins = r.instructions["conv"];
Paul's avatar
Paul committed
54
55
56
        auto a_ins    = r.instructions["a"];
        auto w_ins    = r.instructions["w"];

Paul's avatar
Paul committed
57
        auto broadcast_op = any_cast<op::broadcast>(a_ins->get_operator());
Paul's avatar
Paul committed
58
        if(broadcast_op.axis != 1)
Paul's avatar
Paul committed
59
60
            return;

Paul's avatar
Paul committed
61
62
63
64
65
        auto new_a = p.insert_instruction(
            ins, op::broadcast{0, w_ins->get_shape().lens()}, a_ins->inputs().front());
        auto new_mul  = p.insert_instruction(ins, op::mul{}, new_a, w_ins);
        auto new_conv = p.insert_instruction(
            ins, conv_ins->get_operator(), conv_ins->inputs().front(), new_mul);
Paul's avatar
Paul committed
66
        p.replace_instruction(ins, new_conv);
Paul's avatar
Paul committed
67
    }
Paul's avatar
Paul committed
68
69
};

Paul's avatar
Paul committed
70
// a * (x + b) => a * x + a * b
Paul's avatar
Paul committed
71
72
73
74
75
struct find_mul_add
{
    auto matcher() const
    {
        return match::name("mul")(match::either_arg(0, 1)(
Paul's avatar
Paul committed
76
77
78
            match::name("add")(
                match::either_arg(0, 1)(
                    match::any().bind("x"),
Paul's avatar
Paul committed
79
                    match::any_of(conv_const_weights(), match::is_constant()).bind("b")),
Paul's avatar
Paul committed
80
                match::none_of(match::args(match::is_constant(), match::is_constant())),
Paul's avatar
Paul committed
81
                match::used_once()),
Paul's avatar
Paul committed
82
            match::is_constant().bind("a")));
Paul's avatar
Paul committed
83
84
85
86
    }

    void apply(program& p, match::matcher_result r) const
    {
Paul's avatar
Paul committed
87
        auto ins   = r.result;
Paul's avatar
Paul committed
88
        auto a_ins = r.instructions["a"];
Paul's avatar
Paul committed
89
        auto b_ins = r.instructions["b"];
Paul's avatar
Paul committed
90
        auto x_ins = r.instructions["x"];
Paul's avatar
Paul committed
91
        assert(x_ins != b_ins);
Paul's avatar
Paul committed
92

Paul's avatar
Paul committed
93
94
95
        auto ax_ins = p.insert_instruction(ins, op::mul{}, a_ins, x_ins);
        auto ab_ins = p.insert_instruction(ins, op::mul{}, a_ins, b_ins);
        p.replace_instruction(ins, op::add{}, ax_ins, ab_ins);
Paul's avatar
Paul committed
96
97
98
    }
};

Paul's avatar
Paul committed
99
struct find_add_lit_broadcast
Paul's avatar
Paul committed
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
{
    auto matcher() const
    {
        return match::name("add")(
            match::either_arg(0, 1)(op_lit_broadcast("add", "a", "x"), lit_broadcast().bind("b")));
    }

    void apply(program& p, match::matcher_result r) const
    {
        auto ins   = r.result;
        auto x_ins = r.instructions["x"];
        auto a_ins = r.instructions["a"];
        auto b_ins = r.instructions["b"];

        auto sumab = p.insert_instruction(ins, op::add{}, a_ins, b_ins);
        p.replace_instruction(ins, op::add{}, x_ins, sumab);
    }
};

struct find_double_add_lit_broadcast
Paul's avatar
Paul committed
120
{
Paul's avatar
Paul committed
121
122
    auto matcher() const
    {
Paul's avatar
Paul committed
123
        return match::name("add")(
Paul's avatar
Paul committed
124
            match::args(op_lit_broadcast("add", "a", "x"), op_lit_broadcast("add", "b", "y")));
Paul's avatar
Paul committed
125
126
127
128
    }

    void apply(program& p, match::matcher_result r) const
    {
Paul's avatar
Paul committed
129
130
131
132
133
        auto ins   = r.result;
        auto x_ins = r.instructions["x"];
        auto y_ins = r.instructions["y"];
        auto a_ins = r.instructions["a"];
        auto b_ins = r.instructions["b"];
Paul's avatar
Paul committed
134
135
136

        instruction_ref sumab;

Paul's avatar
Paul committed
137
        if(a_ins->name() == "broadcast" and b_ins->name() == "broadcast")
Paul's avatar
Paul committed
138
139
140
        {
            if(a_ins->inputs().at(0)->get_shape() != b_ins->inputs().at(0)->get_shape())
                return;
Paul's avatar
Paul committed
141
142
143
144
            auto op = a_ins->get_operator();
            auto presum =
                p.insert_instruction(ins, op::add{}, a_ins->inputs().at(0), b_ins->inputs().at(0));
            sumab = p.insert_instruction(ins, op, presum);
Paul's avatar
Paul committed
145
146
147
148
149
150
151
152
153
154
155
        }
        else
        {
            sumab = p.insert_instruction(ins, op::add{}, a_ins, b_ins);
        }

        auto sumxy = p.insert_instruction(ins, op::add{}, x_ins, y_ins);
        p.replace_instruction(ins, op::add{}, sumxy, sumab);
    }
};

Paul's avatar
Paul committed
156
157
158
159
struct find_inner_broadcast
{
    auto matcher() const
    {
Paul's avatar
Paul committed
160
161
        return match::name("mul", "add")(
            match::args(match::name("broadcast").bind("x"), match::name("broadcast").bind("y")));
Paul's avatar
Paul committed
162
163
164
165
166
167
168
169
170
171
172
    }

    void apply(program& p, match::matcher_result r) const
    {
        auto ins   = r.result;
        auto x_ins = r.instructions["x"];
        auto y_ins = r.instructions["y"];

        auto xbroadcast = any_cast<op::broadcast>(x_ins->get_operator());
        auto ybroadcast = any_cast<op::broadcast>(y_ins->get_operator());

Paul's avatar
Paul committed
173
        if(xbroadcast.axis != ybroadcast.axis)
Paul's avatar
Paul committed
174
175
            return;

Paul's avatar
Paul committed
176
177
        auto op = p.insert_instruction(
            ins, ins->get_operator(), x_ins->inputs().front(), y_ins->inputs().front());
Paul's avatar
Paul committed
178
179
180
181
        p.replace_instruction(ins, xbroadcast, op);
    }
};

182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
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
struct find_concat_unary
{
    auto matcher() const
    {
        return match::name("concat")(args_has_same_ops(),
                                     match::arg(0)(match::nargs(1),
                                                   match::name("relu", "broadcast").bind("x"),
                                                   match::used_once()));
    }

    void apply(program& p, match::matcher_result r) const
    {
        auto ins  = r.result;
        auto x    = r.instructions["x"];
        auto op   = x->get_operator();
        auto axis = any_cast<op::concat>(ins->get_operator()).axis;
        // Adjust broadcast lens
        if(op.name() == "broadcast")
        {
            auto b = any_cast<op::broadcast>(op);
            if(b.axis != axis)
                return;
            b.broadcast_lens = ins->get_shape().lens();
            op               = b;
            axis             = 0;
        }

        auto inputs = ins->inputs();
        std::transform(inputs.begin(), inputs.end(), inputs.begin(), [&](auto i) {
            return i->inputs().front();
        });
        auto concat = p.insert_instruction(ins, op::concat{axis}, inputs);
        p.replace_instruction(ins, op, concat);
    }
};

struct find_concat_binary
{
    auto matcher() const
    {
        return match::name("concat")(args_has_same_ops(),
                                     match::arg(0)(match::nargs(2),
                                                   match::name("add", "multiply").bind("x"),
                                                   match::used_once()));
    }

    void apply(program& p, match::matcher_result r) const
    {
        auto ins       = r.result;
        auto x         = r.instructions["x"];
        auto op        = x->get_operator();
        auto concat_op = ins->get_operator();

        auto xinputs = ins->inputs();
        std::transform(xinputs.begin(), xinputs.end(), xinputs.begin(), [&](auto i) {
            return i->inputs().front();
        });
        auto yinputs = ins->inputs();
        std::transform(yinputs.begin(), yinputs.end(), yinputs.begin(), [&](auto i) {
            return i->inputs().back();
        });
        auto xconcat = p.insert_instruction(ins, concat_op, xinputs);
        auto yconcat = p.insert_instruction(ins, concat_op, yinputs);
        p.replace_instruction(ins, op, xconcat, yconcat);
    }
};

249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
bool axis_equal(const std::vector<std::size_t>& x,
                const std::vector<std::size_t>& y,
                std::size_t axis)
{
    return x.size() == y.size() and x.size() > axis and
           std::equal(x.begin(), x.begin() + axis, y.begin()) and
           std::equal(x.begin() + axis + 1, x.end(), y.begin() + axis + 1);
}

bool axis_shape_equal(const shape& x, const shape& y, std::size_t axis)
{
    // TODO: Check strides
    return axis_equal(x.lens(), y.lens(), axis);
}

struct find_add_convs
{
    auto matcher() const
    {
        return match::name("add")(
            match::args(conv_const_weights().bind("a"), conv_const_weights().bind("b")));
    }

    static bool symmetrical_strides(const op::convolution& op)
    {
        return op.stride[0] == op.stride[1];
    }

    static std::size_t compute_stride_factor(const op::convolution& x, const op::convolution& y)
    {
        if(not symmetrical_strides(x))
            return 0;
        if(not symmetrical_strides(y))
            return 0;
        if((x.stride[0] % y.stride[0]) != 0)
            return 0;
        return x.stride[0] / y.stride[0];
    }

    static shape compute_stride_shape(const shape& input, std::size_t n)
    {
        return {input.type(),
291
292
293
294
                {input.lens()[0],
                 input.lens()[1],
                 std::size_t(std::max<std::ptrdiff_t>(1, (input.lens()[2] - 1) / n + 1)),
                 std::size_t(std::max<std::ptrdiff_t>(1, (input.lens()[3] - 1) / n + 1))},
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
                {input.strides()[0],
                 input.strides()[1],
                 input.strides()[2] * n,
                 input.strides()[3] * n}};
    }

    void apply(program& p, match::matcher_result r) const
    {
        auto ins       = r.result;
        auto a_conv    = r.instructions["a"];
        auto a_input   = a_conv->inputs().at(0);
        auto a_weights = a_conv->inputs().at(1);
        auto b_conv    = r.instructions["b"];
        auto b_input   = b_conv->inputs().at(0);
        auto b_weights = b_conv->inputs().at(1);

        if(not axis_shape_equal(a_weights->get_shape(), b_weights->get_shape(), 1))
            return;

        auto a_op   = any_cast<op::convolution>(a_conv->get_operator());
        auto b_op   = any_cast<op::convolution>(b_conv->get_operator());
        auto new_op = a_op;

        if(a_op != b_op)
        {
            if(std::tie(a_op.padding, a_op.dilation, a_op.group) ==
                   std::tie(b_op.padding, b_op.dilation, b_op.group) and
               a_weights->get_shape().lens()[2] == 1 and a_weights->get_shape().lens()[3] == 1)
            {
                if(a_op.stride < b_op.stride)
                {
                    auto n = compute_stride_factor(b_op, a_op);
                    if(n == 0)
                        return;
                    new_op  = a_op;
                    b_input = p.insert_instruction(
                        ins, op::as_shape{compute_stride_shape(b_input->get_shape(), n)}, b_input);
                }
                else if(b_op.stride < a_op.stride)
                {
                    auto n = compute_stride_factor(a_op, b_op);
                    if(n == 0)
                        return;
                    new_op  = b_op;
                    a_input = p.insert_instruction(
                        ins, op::as_shape{compute_stride_shape(a_input->get_shape(), n)}, a_input);
                }
                else
                    return;
            }
            else
                return;
        }

        auto concat_input   = p.insert_instruction(ins, op::concat{1}, a_input, b_input);
        auto concat_weights = p.insert_instruction(ins, op::concat{1}, a_weights, b_weights);
        p.replace_instruction(ins, new_op, concat_input, concat_weights);
    }
};

355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
struct find_div_const
{
    auto matcher() const
    {
        return match::name("div")(match::arg(1)(match::is_constant().bind("c")));
    }

    void apply(program& p, match::matcher_result r) const
    {
        auto ins   = r.result;
        auto c_ins = r.instructions["c"];

        auto recip = p.insert_instruction(std::next(c_ins), op::recip{}, c_ins);

        auto args = ins->inputs();

        p.replace_instruction(ins, op::mul{}, args.front(), recip);
    }
};

struct find_sub_const
{
    auto matcher() const
    {
        return match::name("sub")(match::arg(1)(match::is_constant().bind("c")));
    }

    void apply(program& p, match::matcher_result r) const
    {
        auto ins   = r.result;
        auto c_ins = r.instructions["c"];

        auto neg = p.insert_instruction(std::next(c_ins), op::neg{}, c_ins);

        auto args = ins->inputs();

        p.replace_instruction(ins, op::add{}, args.front(), neg);
    }
};

kahmed10's avatar
kahmed10 committed
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
struct find_rsqrt
{
    auto matcher() const
    {
        return match::name("recip")(match::args(
            match::name("sqrt")(match::used_once(), match::args(match::any().bind("x")))));
    }

    void apply(program& p, match::matcher_result r) const
    {
        auto ins   = r.result;
        auto x_ins = r.instructions["x"];

        p.replace_instruction(ins, op::rsqrt{}, x_ins);
    }
};

Paul's avatar
Paul committed
412
413
void simplify_algebra::apply(program& p) const
{
Paul's avatar
Paul committed
414
    // Run simplifications multiple times
Paul's avatar
Paul committed
415
    for(int i = 0; i < 4; i++)
Paul's avatar
Paul committed
416
    {
Paul's avatar
Paul committed
417
        match::find_matches(p,
Paul's avatar
Paul committed
418
                            find_inner_broadcast{},
Paul's avatar
Paul committed
419
420
                            find_double_add_lit_broadcast{},
                            find_add_lit_broadcast{},
421
                            find_add_convs{},
Paul's avatar
Paul committed
422
                            find_mul_conv{},
423
                            find_mul_add{},
424
425
                            find_div_const{},
                            find_sub_const{},
kahmed10's avatar
kahmed10 committed
426
                            find_rsqrt{},
427
428
                            find_concat_unary{},
                            find_concat_binary{});
Paul's avatar
Paul committed
429
430
        dead_code_elimination{}.apply(p);
    }
Paul's avatar
Paul committed
431
}
Paul's avatar
Paul committed
432

Paul's avatar
Paul committed
433
} // namespace MIGRAPHX_INLINE_NS
Paul's avatar
Paul committed
434
} // namespace migraphx