simplify_algebra.cpp 58.6 KB
Newer Older
1
2
3
/*
 * The MIT License (MIT)
 *
4
 * Copyright (c) 2015-2023 Advanced Micro Devices, Inc. All rights reserved.
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
 *
 * 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's avatar
Paul committed
24
#include <migraphx/simplify_algebra.hpp>
Paul's avatar
Paul committed
25
#include <migraphx/dead_code_elimination.hpp>
Paul's avatar
Paul committed
26
#include <migraphx/program.hpp>
27
#include <migraphx/op/concat.hpp>
28
#include <migraphx/op/slice.hpp>
29
#include <migraphx/op/convolution.hpp>
Paul's avatar
Paul committed
30
#include <migraphx/op/broadcast.hpp>
31
32
#include <migraphx/op/reshape.hpp>
#include <migraphx/op/transpose.hpp>
Paul's avatar
Paul committed
33
#include <migraphx/matcher.hpp>
34
#include <migraphx/common.hpp>
Paul's avatar
Paul committed
35
#include <migraphx/literal.hpp>
36
37
38
#include <migraphx/make_op.hpp>
#include <migraphx/serialize.hpp>

39
#include <migraphx/algorithm.hpp>
Shucai Xiao's avatar
Shucai Xiao committed
40
#include <unordered_set>
Paul's avatar
Paul committed
41

Paul's avatar
Paul committed
42
namespace migraphx {
Paul's avatar
Paul committed
43
inline namespace MIGRAPHX_INLINE_NS {
Paul's avatar
Paul committed
44

Paul's avatar
Paul committed
45
auto lit_broadcast() { return match::any_of(match::is_constant(), match::name("broadcast")); }
Paul's avatar
Paul committed
46
auto not_lit_broadcast() { return match::none_of(match::is_constant(), match::name("broadcast")); }
Paul's avatar
Paul committed
47
48
auto op_lit_broadcast(std::string op, std::string x, std::string y)
{
Paul's avatar
Paul committed
49
50
    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
51
52
}

Paul's avatar
Paul committed
53
54
auto conv_const_weights()
{
55
56
57
    return match::name("convolution")(
        match::used_once(),
        match::args(match::none_of(match::is_constant()), match::is_constant().bind("w")));
Paul's avatar
Paul committed
58
59
}

Shucai Xiao's avatar
Shucai Xiao committed
60
61
auto reduction() { return match::name_contains("reduce"); }

62
// conv(x, w) * a => conv(x, a * w)
Paul's avatar
Paul committed
63
64
65
struct find_mul_conv
{
    auto matcher() const
Paul's avatar
Paul committed
66
    {
67
68
69
        return match::name("mul")(
            match::either_arg(0, 1)(conv_const_weights().bind("conv"),
                                    match::name("broadcast", "multibroadcast").bind("a")));
Paul's avatar
Paul committed
70
    }
Paul's avatar
Paul committed
71

72
    void apply(module& m, const match::matcher_result& r) const
Paul's avatar
Paul committed
73
    {
Paul's avatar
Paul committed
74
        auto ins      = r.result;
Paul's avatar
Paul committed
75
        auto conv_ins = r.instructions["conv"];
Paul's avatar
Paul committed
76
77
78
        auto a_ins    = r.instructions["a"];
        auto w_ins    = r.instructions["w"];

79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
        const auto& a_input_lens = a_ins->inputs().front()->get_shape().lens();

        std::size_t num_not_one_dims = std::count_if(
            a_input_lens.cbegin(), a_input_lens.cend(), [](auto dim) { return dim != 1; });
        if(num_not_one_dims > 1)
            return;

        // check broadcasted along channels
        const auto& a_lens    = a_ins->get_shape().lens();
        const auto& a_strides = a_ins->get_shape().strides();

        auto is_broadcasted_axis = [](auto len, auto stride) { return len == 1 or stride == 0; };

        if(a_strides.at(1) != 1)
            return;

        if(not is_broadcasted_axis(a_lens.front(), a_strides.front()))
            return;

        if(not std::equal(a_lens.begin() + 2,
                          a_lens.end(),
                          a_strides.begin() + 2,
                          a_strides.end(),
                          is_broadcasted_axis))
Paul's avatar
Paul committed
103
104
            return;

105
        auto sq    = m.insert_instruction(ins, make_op("squeeze"), a_ins->inputs().front());
106
        auto new_a = m.insert_instruction(
107
            ins, make_op("broadcast", {{"axis", 0}, {"out_lens", w_ins->get_shape().lens()}}), sq);
108
109
        auto new_mul  = m.insert_instruction(ins, make_op("mul"), new_a, w_ins);
        auto new_conv = m.insert_instruction(
Paul's avatar
Paul committed
110
            ins, conv_ins->get_operator(), conv_ins->inputs().front(), new_mul);
111
        m.replace_instruction(ins, new_conv);
Paul's avatar
Paul committed
112
    }
Paul's avatar
Paul committed
113
114
};

115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
struct find_mul_slice_conv
{
    static auto conv()
    {
        return match::name("convolution")(
            match::all_of[match::outputs()](match::name("slice")),
            match::args(match::any(), match::is_constant().bind("w")));
    }
    auto matcher() const
    {
        return match::name("mul")(match::either_arg(0, 1)(
            match::name("slice")(match::used_once(), match::arg(0)(conv().bind("conv")))
                .bind("slice"),
            match::name("broadcast")(match::is_constant()).bind("a")));
    }

131
    void apply(module& m, const match::matcher_result& r) const
132
133
134
135
136
137
138
139
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
    {
        auto ins       = r.result;
        auto slice_ins = r.instructions["slice"];
        auto conv_ins  = r.instructions["conv"];
        auto a_ins     = r.instructions["a"];
        auto w_ins     = r.instructions["w"];

        auto broadcast_op = any_cast<op::broadcast>(a_ins->get_operator());
        if(broadcast_op.axis != 1)
            return;

        auto slice_op = any_cast<op::slice>(slice_ins->get_operator());
        if(slice_op.axes.size() != 1)
            return;
        if(slice_op.axes.front() != 1)
            return;

        auto slice_idx = std::distance(conv_ins, slice_ins);
        if(std::any_of(conv_ins->outputs().begin(), conv_ins->outputs().end(), [&](auto i) {
               if(i == slice_ins)
                   return false;
               if(std::distance(conv_ins, i) < slice_idx)
                   return true;
               auto sop = any_cast<op::slice>(i->get_operator());
               if(sop.axes != slice_op.axes)
                   return true;
               if(std::max(sop.starts.front(), slice_op.starts.front()) <
                  std::min(sop.ends.front(), slice_op.ends.front()))
                   return true;
               return false;
           }))
            return;

        auto w_slice_op  = slice_op;
        w_slice_op.axes  = {0};
167
        auto slice_w_ins = m.insert_instruction(ins, w_slice_op, w_ins);
168

169
        auto new_a = m.insert_instruction(
170
            ins,
171
            make_op("broadcast", {{"axis", 0}, {"out_lens", slice_w_ins->get_shape().lens()}}),
172
            a_ins->inputs().front());
173
        auto new_mul = m.insert_instruction(ins, make_op("mul"), new_a, slice_w_ins);
174
175
176

        std::vector<instruction_ref> sliced_weights;
        if(slice_op.starts.front() != 0)
177
            sliced_weights.push_back(m.insert_instruction(
178
179
180
                ins,
                make_op("slice", {{"axes", {0}}, {"starts", {0}}, {"ends", slice_op.starts}}),
                w_ins));
181
182
183
        sliced_weights.push_back(new_mul);
        int64_t end_axis = w_ins->get_shape().lens().at(0);
        if(slice_op.ends.front() != end_axis)
184
            sliced_weights.push_back(m.insert_instruction(
185
186
187
                ins,
                make_op("slice", {{"axes", {0}}, {"starts", slice_op.ends}, {"ends", {end_axis}}}),
                w_ins));
188

189
        auto new_weights =
190
            m.insert_instruction(ins, make_op("concat", {{"axis", 0}}), sliced_weights);
191

192
        auto new_conv = m.insert_instruction(
193
194
195
            ins, conv_ins->get_operator(), conv_ins->inputs().front(), new_weights);
        assert(conv_ins->get_shape() == new_conv->get_shape());

196
        auto slice1 = m.insert_instruction(ins, slice_op, new_conv);
197
        assert(ins->get_shape().lens() == slice1->get_shape().lens());
198
        m.replace_instruction(ins, slice1);
199
        // TODO: Check each slice doesn't overlap and that it occurs after slice_ins
200
201
        auto outputs = conv_ins->outputs();
        for(auto output : outputs)
202
203
204
205
206
            if(output != slice_ins)
                instruction::replace_argument(output, conv_ins, new_conv);
    }
};

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
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
291
292
293
294
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
struct find_mul_dot
{
    auto matcher() const
    {
        auto is_dot_const_inputs =
            match::name("dot")(match::any_of[match::inputs()](match::is_constant()));
        return match::name("mul")(match::either_arg(0, 1)(
            is_dot_const_inputs.bind("dot"), match::name("broadcast", "multibroadcast").bind("c")));
    }

    void apply(module& m, const match::matcher_result& r) const
    {
        auto ins     = r.result;
        auto dot_ins = r.instructions["dot"];
        auto a_ins   = dot_ins->inputs()[0];
        auto b_ins   = dot_ins->inputs()[1];
        auto c_ins   = r.instructions["c"];

        const auto& c_strides = c_ins->get_shape().strides();

        // There should only be one stride that is not zero
        if(std::count_if(c_strides.begin(), c_strides.end(), [](auto s) { return s != 0; }) > 1)
            return;

        auto add_mul_const = [&](instruction_ref x_ins) {
            if(not x_ins->can_eval())
                return m.end();
            auto broadcast_v        = c_ins->get_operator().to_value();
            broadcast_v["out_lens"] = x_ins->get_shape().lens();

            auto cb_ins =
                m.insert_instruction(ins, make_op(c_ins->name(), broadcast_v), c_ins->inputs());
            return m.insert_instruction(ins, make_op("mul"), x_ins, cb_ins);
        };

        if(c_strides.back() == 1)
        {
            b_ins = add_mul_const(b_ins);
        }
        else if(c_strides[c_strides.size() - 2] == 1)
        {
            a_ins = add_mul_const(a_ins);
        }
        else if(c_ins->get_shape().scalar())
        {
            if(a_ins->can_eval())
                a_ins = add_mul_const(a_ins);
            else
                b_ins = add_mul_const(b_ins);
        }
        else
        {
            return;
        }

        if(contains({a_ins, b_ins}, m.end()))
            return;

        m.replace_instruction(ins, make_op("dot"), a_ins, b_ins);
    }
};

struct find_dot_mul
{
    auto matcher() const
    {
        auto const_broadcast = match::name("broadcast", "multibroadcast")(match::is_constant());
        auto mul             = match::name("mul")(
            match::used_once(),
            match::either_arg(0, 1)(const_broadcast.bind("d"),
                                    match::none_of(match::is_constant()).bind("z")));
        return match::name("dot")(match::either_arg(0, 1)(mul, match::is_constant().bind("c")));
    }

    void apply(module& m, const match::matcher_result& r) const
    {
        auto ins   = r.result;
        auto a_ins = ins->inputs()[0];
        auto b_ins = ins->inputs()[1];
        auto d_ins = r.instructions["d"];
        auto c_ins = r.instructions["c"];
        auto z_ins = r.instructions["z"];

        const auto& d_strides = d_ins->get_shape().strides();

        // There should only be one stride that is not zero
        if(std::count_if(d_strides.begin(), d_strides.end(), [](auto s) { return s != 0; }) > 1)
            return;

        if(not d_ins->get_shape().scalar())
        {
            if(d_strides.back() == 1 and not b_ins->can_eval())
                return;
            if(d_strides[d_strides.size() - 2] == 1 and not a_ins->can_eval())
                return;
        }

        auto broadcast_v = d_ins->get_operator().to_value();
        auto c_lens      = c_ins->get_shape().lens();
        std::vector<int64_t> permutation(c_lens.size());
        std::iota(permutation.begin(), permutation.end(), 0);
        std::swap(permutation.back(), permutation[permutation.size() - 2]);
        c_lens                  = reorder_dims(c_lens, permutation);
        broadcast_v["out_lens"] = c_lens;
        auto db_ins =
            m.insert_instruction(ins, make_op(d_ins->name(), broadcast_v), d_ins->inputs());
        auto db_transpose_ins =
            m.insert_instruction(ins, make_op("transpose", {{"permutation", permutation}}), db_ins);
        auto cd_ins = m.insert_instruction(ins, make_op("mul"), c_ins, db_transpose_ins);

        if(c_ins == b_ins)
        {
            a_ins = z_ins;
            b_ins = cd_ins;
        }
        else
        {
            a_ins = cd_ins;
            b_ins = z_ins;
        }

        m.replace_instruction(ins, make_op("dot"), a_ins, b_ins);
    }
};

332
333
334
335
336
337
// ******************************
//  a * (x + b) => a * x + a * b
// ******************************
// When a * (x + b) is followed by another add of constant, then the
// additional add can be const folded. Also, better fusions can be applied
// when the add comes after.
Paul's avatar
Paul committed
338
339
340
341
342
struct find_mul_add
{
    auto matcher() const
    {
        return match::name("mul")(match::either_arg(0, 1)(
Paul's avatar
Paul committed
343
344
345
            match::name("add")(
                match::either_arg(0, 1)(
                    match::any().bind("x"),
Paul's avatar
Paul committed
346
                    match::any_of(conv_const_weights(), match::is_constant()).bind("b")),
Paul's avatar
Paul committed
347
                match::none_of(match::args(match::is_constant(), match::is_constant())),
Paul's avatar
Paul committed
348
                match::used_once()),
Paul's avatar
Paul committed
349
            match::is_constant().bind("a")));
Paul's avatar
Paul committed
350
351
    }

352
    void apply(module& m, const match::matcher_result& r) const
Paul's avatar
Paul committed
353
    {
Paul's avatar
Paul committed
354
        auto ins   = r.result;
Paul's avatar
Paul committed
355
        auto a_ins = r.instructions["a"];
Paul's avatar
Paul committed
356
        auto b_ins = r.instructions["b"];
Paul's avatar
Paul committed
357
        auto x_ins = r.instructions["x"];
Paul's avatar
Paul committed
358
        assert(x_ins != b_ins);
Paul's avatar
Paul committed
359

360
361
362
        auto ax_ins = m.insert_instruction(ins, make_op("mul"), a_ins, x_ins);
        auto ab_ins = m.insert_instruction(ins, make_op("mul"), a_ins, b_ins);
        m.replace_instruction(ins, make_op("add"), ax_ins, ab_ins);
Paul's avatar
Paul committed
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
395
396
397
398
399
400
401
struct find_dot_add
{
    auto matcher() const
    {
        return match::name("dot")(match::either_arg(0, 1)(
            match::name("add")(
                match::either_arg(0, 1)(match::any().bind("x"),
                                        match::any_of(match::is_constant()).bind("b")),
                match::none_of(match::args(match::is_constant(), match::is_constant())),
                match::used_once()),
            match::is_constant().bind("a")));
    }

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

        const bool flipped = a_ins == ins->inputs().back();

        auto insert_dot = [&](auto x, auto y) {
            if(flipped)
                return m.insert_instruction(ins, make_op("dot"), y, x);
            else
                return m.insert_instruction(ins, make_op("dot"), x, y);
        };

        auto ax_ins = insert_dot(a_ins, x_ins);
        auto ab_ins = insert_dot(a_ins, b_ins);
        m.replace_instruction(ins, make_op("add"), ax_ins, ab_ins);
    }
};

402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
struct find_conv_add
{
    auto matcher() const
    {
        auto add = match::name("add")(
            match::either_arg(0, 1)(match::any().bind("x"),
                                    match::any_of(match::is_constant()).bind("a")),
            match::used_once());
        return match::name("convolution")(match::used_once(),
                                          match::args(add, match::is_constant().bind("w")));
    }

    void apply(module& m, const match::matcher_result& r) const
    {
        auto ins   = r.result;
        auto a_ins = r.instructions["a"];
        auto x_ins = r.instructions["x"];
        auto w_ins = r.instructions["w"];

        auto conv1 = m.insert_instruction(ins, ins->get_operator(), a_ins, w_ins);
        auto conv2 = m.insert_instruction(ins, ins->get_operator(), x_ins, w_ins);

        m.replace_instruction(ins, make_op("add"), conv1, conv2);
    }
};

Paul's avatar
Paul committed
428
struct find_add_lit_broadcast
Paul's avatar
Paul committed
429
430
431
432
433
434
435
{
    auto matcher() const
    {
        return match::name("add")(
            match::either_arg(0, 1)(op_lit_broadcast("add", "a", "x"), lit_broadcast().bind("b")));
    }

436
    void apply(module& m, const match::matcher_result& r) const
Paul's avatar
Paul committed
437
438
439
440
441
442
    {
        auto ins   = r.result;
        auto x_ins = r.instructions["x"];
        auto a_ins = r.instructions["a"];
        auto b_ins = r.instructions["b"];

443
444
        auto sumab = m.insert_instruction(ins, make_op("add"), a_ins, b_ins);
        m.replace_instruction(ins, make_op("add"), x_ins, sumab);
Paul's avatar
Paul committed
445
446
447
448
    }
};

struct find_double_add_lit_broadcast
Paul's avatar
Paul committed
449
{
Paul's avatar
Paul committed
450
451
    auto matcher() const
    {
Paul's avatar
Paul committed
452
        return match::name("add")(
Paul's avatar
Paul committed
453
            match::args(op_lit_broadcast("add", "a", "x"), op_lit_broadcast("add", "b", "y")));
Paul's avatar
Paul committed
454
455
    }

456
    void apply(module& m, const match::matcher_result& r) const
Paul's avatar
Paul committed
457
    {
Paul's avatar
Paul committed
458
459
460
461
462
        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
463
464
465

        instruction_ref sumab;

Paul's avatar
Paul committed
466
        if(a_ins->name() == "broadcast" and b_ins->name() == "broadcast")
Paul's avatar
Paul committed
467
468
469
        {
            if(a_ins->inputs().at(0)->get_shape() != b_ins->inputs().at(0)->get_shape())
                return;
470
            auto op     = a_ins->get_operator();
471
            auto presum = m.insert_instruction(
472
                ins, make_op("add"), a_ins->inputs().at(0), b_ins->inputs().at(0));
473
            sumab = m.insert_instruction(ins, op, presum);
Paul's avatar
Paul committed
474
475
476
        }
        else
        {
477
            sumab = m.insert_instruction(ins, make_op("add"), a_ins, b_ins);
Paul's avatar
Paul committed
478
479
        }

480
481
        auto sumxy = m.insert_instruction(ins, make_op("add"), x_ins, y_ins);
        m.replace_instruction(ins, make_op("add"), sumxy, sumab);
Paul's avatar
Paul committed
482
483
484
    }
};

Paul's avatar
Paul committed
485
486
struct find_inner_broadcast
{
487
    auto matcher() const { return pointwise(match::all_of[match::inputs()](match::broadcast())); }
Paul's avatar
Paul committed
488

489
490
491
492
493
494
495
496
497
    static auto non_scalar_op(const std::string& name)
    {
        return [=](instruction_ref ins) {
            if(ins->get_shape().scalar())
                return false;
            return ins->name() == name;
        };
    }

498
    void apply(module& m, const match::matcher_result& r) const
Paul's avatar
Paul committed
499
    {
500
501
502
503
        auto ins        = r.result;
        auto broadcasts = ins->inputs();
        if(broadcasts.empty())
            return;
504
505
506
507
508
        // Skip if different data types are used
        if(any_of(broadcasts, [&](auto i) {
               return i->get_shape().type() != broadcasts.front()->get_shape().type();
           }))
            return;
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
        bool mixed_broadcasts = any_of(broadcasts, non_scalar_op("broadcast")) and
                                any_of(broadcasts, non_scalar_op("multibroadcast"));
        // If the broadcast is not a single dimension, then dont perform inner_broadcast
        if(mixed_broadcasts and any_of(broadcasts, [&](instruction_ref i) {
               if(i->get_shape().scalar())
                   return false;
               if(i->name() == "multibroadcast")
                   return false;
               auto input       = i->inputs().at(0);
               const auto& lens = input->get_shape().lens();
               return std::count_if(lens.begin(), lens.end(), [&](std::size_t d) {
                          return d == 1;
                      }) < (lens.size() - 1);
           }))
            return;
524
        if(broadcasts.size() > 1)
525
        {
526
527
528
529
530
            auto bcast_strides = broadcasts.front()->get_shape().strides().size();
            std::vector<size_t> common_axis(bcast_strides, 0);
            // go through the strides of each broadcast,
            // keep track of values that are equal to 0 in a dimension
            for(auto i = 0; i < bcast_strides; i++)
531
            {
532
533
534
535
536
                for(const auto& broadcast : broadcasts)
                {
                    if(broadcast->get_shape().strides()[i] == 0)
                        common_axis[i]++;
                }
537
            }
538
539
            // if no common broadcast axis, transformation is not useful
            if(std::find_if(common_axis.begin(), common_axis.end(), [](auto num_common) {
Khalique Ahmed's avatar
Khalique Ahmed committed
540
541
                   return num_common > 1;
               }) == common_axis.end())
542
                return;
543
544
        }

545
546
547
548
        std::vector<instruction_ref> inputs;
        std::transform(broadcasts.begin(),
                       broadcasts.end(),
                       std::back_inserter(inputs),
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
                       [&](instruction_ref i) {
                           auto input = i->inputs().front();
                           if(mixed_broadcasts and not i->get_shape().scalar() and
                              i->get_shape().lens().size() > 1)
                               return m.insert_instruction(i, make_op("squeeze"), input);
                           return input;
                       });

        std::sort(broadcasts.begin(), broadcasts.end(), by(std::less<>{}, [](instruction_ref i) {
                      if(i->get_shape().scalar())
                          return 2;
                      else if(i->name() == "broadcast")
                          return 0;
                      if(i->name() == "multibroadcast")
                          return 1;
                      return 3;
                  }));
566
        auto op = insert_common_op(m, ins, ins->get_operator(), inputs);
Khalique Ahmed's avatar
Khalique Ahmed committed
567
568
569
570
571
572
573
574
575
576
577
        std::vector<shape> broadcast_shapes;
        std::transform(broadcasts.begin(), broadcasts.end(), std::back_inserter(broadcast_shapes), [](auto broadcast){
            return broadcast->get_shape();
        });
        std::vector<shape> common_shapes;
        std::transform(op->inputs().begin(), op->inputs().end(), std::back_inserter(common_shapes), [](auto common){
            return common->get_shape();
        });
        if(broadcast_shapes == common_shapes and std::all_of(op->inputs().begin(), op->inputs().end(), [](auto i){
            return i->name() == "broadcast" or i->name() == "multibroadcast";}))
            return;
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
        m.replace_instruction(ins, broadcasts.front()->get_operator(), op);
    }
};

struct find_dot_broadcast
{
    auto matcher() const
    {
        return match::name("dot")(match::all_of[match::inputs()](match::broadcast()));
    }

    void apply(module& m, const match::matcher_result& r) const
    {
        auto ins = r.result;
        auto a   = ins->inputs()[0];
        auto b   = ins->inputs()[1];
        if(a->get_operator().name() != b->get_operator().name())
            return;
        if(ins->get_shape().lens().size() < 3)
            return;
        auto nbatch_axes      = ins->get_shape().lens().size() - 2;
        const auto& a_strides = a->get_shape().strides();
        const auto& b_strides = b->get_shape().strides();
        // Find leading batch axes that are broadcasted
        auto p =
            std::mismatch(a_strides.begin(),
                          a_strides.begin() + nbatch_axes,
                          b_strides.begin(),
                          b_strides.begin() + nbatch_axes,
                          [](auto astride, auto bstride) { return astride == 0 and bstride == 0; });
        auto naxes = p.first - a_strides.begin();
        assert(naxes <= nbatch_axes);
        std::vector<std::size_t> axes(naxes);
        std::iota(axes.begin(), axes.end(), 0);

        auto insert_broadcast = [&](instruction_ref b_ins) -> instruction_ref {
            auto input = b_ins->inputs()[0];
            std::vector<std::size_t> lens(b_ins->get_shape().lens().begin() + naxes,
                                          b_ins->get_shape().lens().end());
            if(b_ins->name() == "multibroadcast")
            {
                return m.insert_instruction(
                    ins, make_op("multibroadcast", {{"out_lens", lens}}), input);
            }
            else if(b_ins->name() == "broadcast")
            {
                auto v    = b_ins->get_operator().to_value();
                auto axis = v.at("axis").to<std::size_t>() - naxes;
                return m.insert_instruction(
                    ins, make_op("broadcast", {{"axis", axis}, {"out_lens", lens}}), input);
            }
            assert(false);
            return m.end();
        };
        auto a1        = insert_broadcast(a);
        auto b1        = insert_broadcast(b);
        auto dot       = m.insert_instruction(ins, make_op("dot"), a1, b1);
        auto broadcast = m.insert_instruction(
            ins, make_op("multibroadcast", {{"out_lens", ins->get_shape().lens()}}), dot);
        m.replace_instruction(ins, broadcast);
Paul's avatar
Paul committed
638
639
640
    }
};

641
struct find_concat_op
642
643
644
{
    auto matcher() const
    {
645
        return match::name("concat")(match::any_of[match::inputs()](
646
647
            match::any_of(match::pointwise(), match::name("broadcast", "multibroadcast")),
            match::used_once()));
648
649
    }

650
651
    template <class Iterator>
    static std::vector<std::size_t> get_output_lens(Iterator start, Iterator last, std::size_t axis)
652
    {
653
654
655
        assert(start != last);
        std::size_t dim = 0;
        for(auto ins : range(start, last))
656
        {
657
            dim += ins->get_shape().lens().at(axis);
658
        }
659
660
661
        auto lens  = (*start)->get_shape().lens();
        lens[axis] = dim;
        return lens;
662
663
    }

664
665
    static bool is_valid_op(const operation& op)
    {
666
667
        return contains({"broadcast", "multibroadcast"}, op.name()) or
               op.attributes().contains("pointwise");
668
669
    }

670
    void apply(module& m, const match::matcher_result& r) const
671
    {
672
673
        auto ins  = r.result;
        auto axis = any_cast<op::concat>(ins->get_operator()).axis;
674

675
676
677
678
679
680
        auto each = [&](auto start, auto last) -> std::vector<instruction_ref> {
            if(std::distance(start, last) < 2)
                return {start, last};
            auto x = *start;
            if(x->inputs().size() > 2 or x->inputs().empty() or x->outputs().size() > 1)
                return {start, last};
681
682
            auto op = x->get_operator();
            if(not is_valid_op(op))
683
684
685
686
687
688
689
690
691
692
693
694
                return {start, last};
            auto iaxis = axis;
            // Adjust broadcast lens
            if(op.name() == "broadcast")
            {
                auto b = any_cast<op::broadcast>(op);
                if(b.axis != iaxis)
                    return {start, last};
                b.broadcast_lens = get_output_lens(start, last, iaxis);
                op               = b;
                iaxis            = 0;
            }
695
696
697
698
699
700
701
702
703
704
            else if(op.name() == "multibroadcast")
            {
                shape bshape = (*start)->get_shape();
                auto input   = (*start)->inputs()[0];
                if(iaxis >= bshape.strides().size() or bshape.strides()[iaxis] == 0)
                    return {start, last};
                op.from_value({{"out_lens", get_output_lens(start, last, iaxis)}});
                auto delta = bshape.lens().size() - input->get_shape().lens().size();
                iaxis -= delta;
            }
705
706
707
708
709
710
711
712

            std::vector<instruction_ref> concats;
            for(std::size_t i = 0; i < x->inputs().size(); i++)
            {
                std::vector<instruction_ref> inputs;
                std::transform(start, last, std::back_inserter(inputs), [&](auto j) {
                    return j->inputs().at(i);
                });
713
                auto concat =
714
                    m.insert_instruction(ins, make_op("concat", {{"axis", iaxis}}), inputs);
715
716
                concats.push_back(concat);
            }
717
            auto y = m.insert_instruction(ins, op, concats);
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
            return {y};
        };

        std::vector<instruction_ref> args;
        auto update_args = [&](auto start, auto last) {
            auto x = each(start, last);
            args.insert(args.end(), x.begin(), x.end());
        };
        auto pred = [](auto i, auto j) {
            return i->get_operator() == j->get_operator() and
                   i->inputs().size() == i->inputs().size() and
                   i->outputs().size() == i->outputs().size();
        };
        group_unique(ins->inputs().begin(), ins->inputs().end(), update_args, pred);
        if(args.size() == 1)
733
            m.replace_instruction(ins, args.front());
734
        else
735
            m.replace_instruction(ins, make_op("concat", {{"axis", axis}}), args);
736
737
738
    }
};

739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
void move_instructions_back(module& m, instruction_ref pos, std::vector<instruction_ref> inss)
{
    auto start = range(m.begin(), pos);
    for(auto ins : iterator_for(start))
    {
        auto it = std::find(inss.begin(), inss.end(), ins);
        if(it != inss.end())
            inss.erase(it);
    }
    for(auto ins : inss)
    {
        if(not m.has_instruction(ins))
            continue;
        move_instructions_back(m, pos, ins->inputs());
        m.move_instruction(ins, pos);
    }
}

757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
std::vector<instruction_ref> get_splits(instruction_ref ins)
{
    std::vector<instruction_ref> result;
    std::copy_if(ins->outputs().begin(),
                 ins->outputs().end(),
                 std::back_inserter(result),
                 [&](auto i) { return i->name() == "slice"; });
    if(result.size() < 2)
        return {};
    auto get_slice = [](auto& i) -> auto& { return any_cast<op::slice>(i->get_operator()); };
    auto&& axes    = get_slice(result.front()).axes;
    if(std::any_of(result.begin(), result.end(), [&](auto i) { return get_slice(i).axes != axes; }))
        return {};
    auto get_start = [&](auto& i) -> auto& { return get_slice(i).starts; };
    auto get_end   = [&](auto& i) -> auto& { return get_slice(i).ends; };
    std::sort(
        result.begin(), result.end(), [&](auto x, auto y) { return get_start(x) < get_start(y); });
    if(std::any_of(get_start(result.front()).begin(), get_start(result.front()).end(), [&](auto i) {
           return i != 0;
       }))
        return {};
    auto it = std::adjacent_find(
        result.begin(), result.end(), [&](auto x, auto y) { return get_end(x) != get_start(y); });
    if(it != result.end())
        return {};
    for(std::size_t i = 0; i < axes.size(); i++)
    {
        auto axis = axes[i];
        if(ins->get_shape().lens()[axis] != get_slice(result.back()).ends[i])
            return {};
    }
    return result;
}

struct find_splits
{
    auto matcher() const
    {
795
796
797
        return match::any(
            match::any_of[match::outputs()](match::name("slice")(match::any_of[match::outputs()](
                match::pointwise(match::any_of(match::nargs(1), match::nargs(2))), reduction()))));
798
799
    }

Shucai Xiao's avatar
Shucai Xiao committed
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
    static bool is_dependent(const module& m, instruction_ref ins1, instruction_ref ins2)
    {

        std::unordered_set<instruction_ref> traversed;
        return fix<bool>([&](auto self, auto ins) -> bool {
            if(ins == ins2)
                return true;

            if(contains(traversed, ins))
                return false;

            traversed.insert(ins);
            const auto& inputs = ins->inputs();
            return std::any_of(inputs.begin(), inputs.end(), [&](auto in) {
                return m.has_instruction(in) and self(in);
            });
        })(ins1);
    }

819
    static std::vector<std::vector<instruction_ref>>
Shucai Xiao's avatar
Shucai Xiao committed
820
    get_split_groups(const module& m, const std::vector<instruction_ref>& splits)
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
    {
        std::vector<std::vector<instruction_ref>> groups;
        for(auto out : splits.front()->outputs())
        {
            if(out->name() == "slice")
                continue;
            std::vector<instruction_ref> group;
            for(auto split : splits)
            {
                auto it =
                    std::find_if(split->outputs().begin(), split->outputs().end(), [&](auto i) {
                        return i->get_operator() == out->get_operator();
                    });
                if(it == split->outputs().end())
                    break;
                assert((*it)->name() != "slice");
Shucai Xiao's avatar
Shucai Xiao committed
837

838
                // If there is a duplicate bail
Shucai Xiao's avatar
Shucai Xiao committed
839
840
841
842
843
                // there are should be no dependency between instructions in the group
                if(std::any_of(group.begin(), group.end(), [&](auto i) {
                       return is_dependent(m, *it, i) or is_dependent(m, i, *it);
                   }))
                {
844
                    return {};
Shucai Xiao's avatar
Shucai Xiao committed
845
846
                }

847
848
849
850
851
852
853
854
855
                group.push_back(*it);
            }
            if(group.size() != splits.size())
                continue;
            groups.push_back(group);
        }
        return groups;
    }

Shucai Xiao's avatar
Shucai Xiao committed
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
    bool is_fusable(instruction_ref start, instruction_ref split_front) const
    {
        auto op = start->get_operator();
        if(contains(op.name(), "reduce"))
        {
            auto slc         = any_cast<op::slice>(split_front->get_operator());
            auto slc_axes    = slc.axes;
            auto reduce_axes = start->get_operator().to_value()["axes"].to_vector<int64_t>();
            // axes of slice and reduce op cannot have overlap
            if(std::any_of(slc_axes.begin(), slc_axes.end(), [&](auto axis) {
                   return (std::find(reduce_axes.begin(), reduce_axes.end(), axis) !=
                           reduce_axes.end());
               }))
            {
                return false;
            }
        }
        else if(not op.attributes().contains("pointwise"))
        {
            return false;
        }

        return true;
    }

881
    void apply(module& m, const match::matcher_result& r) const
882
    {
Shucai Xiao's avatar
Shucai Xiao committed
883
        auto ins    = r.result;
884
885
886
        auto splits = get_splits(ins);
        if(splits.empty())
            return;
Shucai Xiao's avatar
Shucai Xiao committed
887

888
        for(const auto& group : get_split_groups(m, splits))
889
        {
Shucai Xiao's avatar
Shucai Xiao committed
890
891
892
893
894
            auto start       = group.front();
            auto split_front = splits.front();
            auto op          = start->get_operator();
            if(not is_fusable(start, split_front))
            {
895
                continue;
Shucai Xiao's avatar
Shucai Xiao committed
896
            }
897
898
899
900
901
902

            // Make sure there is no duplicates
            assert(std::none_of(
                std::next(group.begin()), group.end(), [&](auto i) { return i == start; }));

            auto split_idx    = 0;
903
            instruction_ref c = m.end();
904
905
            if(start->inputs().size() == 1)
            {
906
                c = m.insert_instruction(std::next(ins), op, ins);
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
            }
            else if(start->inputs().size() == 2)
            {
                assert(not std::none_of(start->inputs().begin(), start->inputs().end(), [](auto i) {
                    return i->name() == "slice";
                }) && "one argument must be a split");
                auto data_idx = 1;
                if(start->inputs().back()->name() == "slice")
                {
                    split_idx = 1;
                    data_idx  = 0;
                }

                std::vector<instruction_ref> data_args;
                std::transform(group.begin(),
                               group.end(),
                               std::back_inserter(data_args),
                               [&](auto i) { return i->inputs()[data_idx]; });

                // Data arguments must be a constant
                if(std::any_of(data_args.begin(), data_args.end(), [](auto i) {
                       return not i->can_eval();
                   }))
                    return;

932
                move_instructions_back(m, ins, data_args);
933
934
935
936
937
938
939

                auto slice_op = any_cast<op::slice>(splits.front()->get_operator());
                assert(not slice_op.axes.empty());
                if(slice_op.axes.size() > 1)
                    return;
                auto concat_axis = slice_op.axes.front();
                // TODO: Check if axises match
940
                auto concat = m.insert_instruction(
941
                    ins, make_op("concat", {{"axis", concat_axis}}), data_args);
942
943
944
945
946

                std::vector<instruction_ref> args;
                args.resize(2);
                args[split_idx] = ins;
                args[data_idx]  = concat;
947
                c               = m.insert_instruction(std::next(ins), op, args);
948
            }
949
            if(c != m.end())
950
951
952
953
954
955
            {
                for(auto i : group)
                {
                    auto split = i->inputs()[split_idx];
                    assert(split->name() == "slice");
                    // Insert contiguous for reshapes
956
957
                    auto outputs = i->outputs();
                    for(auto output : outputs)
958
                    {
959
                        if(output->name() != "reshape")
960
                            continue;
961
                        auto x = m.insert_instruction(output, make_op("contiguous"), i);
962
                        m.replace_instruction(output, output->get_operator(), x);
963
964
                    }

965
                    m.replace_instruction(i, split->get_operator(), c);
966
967
968
969
970
971
972
973
974
975
976
977
978
979
                }
            }
        }
    }
};

struct find_split_concat
{
    auto matcher() const
    {
        return match::any(match::any_of[match::outputs()](
            match::name("slice")(match::all_of[match::outputs()](match::name("concat")))));
    }

980
    void apply(module& m, const match::matcher_result& r) const
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
    {
        auto ins = r.result;

        auto splits = get_splits(ins);
        if(splits.empty())
            return;
        if(std::any_of(
               splits.begin(), splits.end(), [](auto i) { return i->outputs().size() != 1; }))
            return;
        // Check for concat operator
        auto concat = splits.front()->outputs().front();
        if(std::any_of(splits.begin(), splits.end(), [&](auto i) {
               return i->outputs().front() != concat;
           }))
            return;
        // Check axis match
        auto concat_op = any_cast<op::concat>(concat->get_operator());
        auto split_op  = any_cast<op::slice>(splits.front()->get_operator());
        if(split_op.axes.size() != 1)
            return;
        if(split_op.axes.front() != concat_op.axis)
            return;
        // Replace args
        auto args = concat->inputs();
        auto it =
            std::find_if(args.begin(), args.end(), [&](auto i) { return i == splits.front(); });
        if(std::distance(it, args.end()) < splits.size())
            return;
1009
1010
1011
1012
1013
1014
1015
        // If the slices are not in order then stop
        if(not std::is_sorted(it, it + splits.size(), [](instruction_ref x, instruction_ref y) {
               auto xop = any_cast<op::slice>(x->get_operator());
               auto yop = any_cast<op::slice>(y->get_operator());
               return std::tie(xop.starts, xop.ends) < std::tie(yop.starts, yop.ends);
           }))
            return;
1016
1017
1018
1019
        *it = splits.front()->inputs().front();
        args.erase(std::next(it), it + splits.size());

        if(args.size() == 1)
1020
            m.replace_instruction(concat, args.front());
1021
        else
1022
            m.replace_instruction(concat, concat->get_operator(), args);
1023
1024
1025
    }
};

1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
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];
    }

1065
    void apply(module& m, const match::matcher_result& r) const
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
    {
        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;
1094
                    b_input = m.insert_instruction(
Shucai Xiao's avatar
Shucai Xiao committed
1095
                        ins, make_op("step", {{"axes", {2, 3}}, {"steps", {n, n}}}), b_input);
1096
1097
1098
1099
1100
1101
1102
                }
                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;
1103
                    a_input = m.insert_instruction(
Shucai Xiao's avatar
Shucai Xiao committed
1104
                        ins, make_op("step", {{"axes", {2, 3}}, {"steps", {n, n}}}), a_input);
1105
1106
1107
1108
1109
1110
1111
1112
                }
                else
                    return;
            }
            else
                return;
        }

1113
        auto concat_input =
1114
            m.insert_instruction(ins, make_op("concat", {{"axis", 1}}), a_input, b_input);
1115
        auto concat_weights =
1116
1117
            m.insert_instruction(ins, make_op("concat", {{"axis", 1}}), a_weights, b_weights);
        m.replace_instruction(ins, new_op, concat_input, concat_weights);
1118
1119
1120
    }
};

1121
1122
1123
1124
1125
1126
1127
1128
1129
MIGRAPHX_PRED_MATCHER(horiz_conv_dot, instruction_ref ins)
{
    auto pred = [&](auto name) {
        return [=](auto i) {
            return i->name() == name and i->inputs().front() == ins and
                   i->inputs().at(1)->can_eval();
        };
    };
    auto dots  = std::count_if(ins->outputs().begin(), ins->outputs().end(), pred("dot"));
kahmed10's avatar
kahmed10 committed
1130
    auto qdots = std::count_if(ins->outputs().begin(), ins->outputs().end(), pred("quant_dot"));
1131
    auto convs = std::count_if(ins->outputs().begin(), ins->outputs().end(), pred("convolution"));
kahmed10's avatar
kahmed10 committed
1132
    return (dots >= 2 or convs >= 2 or qdots >= 2);
1133
1134
1135
1136
1137
1138
}

struct find_conv_dot_horiz_fusion
{
    auto matcher() const { return horiz_conv_dot(); }

1139
    void apply(module& m, const match::matcher_result& r) const
1140
1141
1142
1143
1144
1145
    {
        auto ins = r.result;

        auto pred = [](auto i, auto j) {
            if(i->get_operator() != j->get_operator())
                return false;
kahmed10's avatar
kahmed10 committed
1146
            if(not contains({"quant_dot", "dot", "convolution"}, i->name()))
1147
1148
1149
1150
1151
                return true;
            auto x = i->inputs()[1]->get_shape().lens();
            auto y = j->inputs()[1]->get_shape().lens();
            if(x.size() != y.size())
                return false;
1152
            // Check that non-axes match
1153
            int axis = 1;
kahmed10's avatar
kahmed10 committed
1154
            if(i->name() == "dot" or i->name() == "quant_dot")
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
            {
                axis = x.size() - 1;
            }
            return axis_equal(x, y, axis);
        };

        auto each = [&](auto start, auto last) {
            if(std::distance(start, last) < 2)
                return;
            auto&& name = (*start)->name();
kahmed10's avatar
kahmed10 committed
1165
            if(not contains({"quant_dot", "dot", "convolution"}, name))
1166
                return;
1167
1168
1169
1170
1171
1172
1173
            auto op   = (*start)->get_operator();
            int group = 1;
            if(name == "convolution")
                group = any_cast<op::convolution>(op).group;
            // Skip group convolution
            if(group != 1)
                return;
1174
1175
1176
1177
1178
1179
            auto input = (*start)->inputs().front();
            std::vector<instruction_ref> args;
            std::transform(
                start, last, std::back_inserter(args), [&](auto x) { return x->inputs().at(1); });
            int axis        = 1;
            int concat_axis = 0;
kahmed10's avatar
kahmed10 committed
1180
            if(name == "dot" or name == "quant_dot")
1181
1182
1183
1184
1185
            {
                axis        = int(args.front()->get_shape().lens().size() - 1);
                concat_axis = axis;
            }

1186
            move_instructions_back(m, input, args);
1187
            // TODO: Check if axes match
1188
            auto concat =
1189
1190
                m.insert_instruction(input, make_op("concat", {{"axis", concat_axis}}), args);
            auto fused     = m.insert_instruction(std::next(input), op, input, concat);
1191
1192
1193
            int64_t offset = 0;
            for(auto arg : range(start, last))
            {
1194
1195
1196
1197
1198
1199
1200
1201
1202
                auto outputs = arg->outputs();
                for(auto output : outputs)
                {
                    if(output->name() != "reshape")
                        continue;
                    auto x = m.insert_instruction(output, make_op("contiguous"), arg);
                    m.replace_instruction(output, output->get_operator(), x);
                }

1203
                int64_t len = arg->get_shape().lens()[axis];
1204
                m.replace_instruction(
1205
1206
1207
1208
                    arg,
                    make_op("slice",
                            {{"axes", {axis}}, {"starts", {offset}}, {"ends", {offset + len}}}),
                    fused);
1209
1210
1211
1212
1213
1214
1215
1216
1217
                offset += len;
            }
        };

        auto outputs = ins->outputs();
        group_by(outputs.begin(), outputs.end(), each, pred);
    }
};

1218
1219
1220
1221
1222
1223
1224
struct find_div_const
{
    auto matcher() const
    {
        return match::name("div")(match::arg(1)(match::is_constant().bind("c")));
    }

1225
    void apply(module& m, const match::matcher_result& r) const
1226
1227
1228
1229
    {
        auto ins   = r.result;
        auto c_ins = r.instructions["c"];

1230
        auto recip = m.insert_instruction(std::next(c_ins), make_op("recip"), c_ins);
1231
1232
1233

        auto args = ins->inputs();

1234
        m.replace_instruction(ins, make_op("mul"), args.front(), recip);
1235
1236
1237
    }
};

1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
struct find_unit_ops
{
    auto matcher() const
    {
        auto mul_1 = match::name("mul")(
            match::either_arg(0, 1)(match::has_value(1.0f), match::any().bind("x")));
        auto div_1 =
            match::name("div")(match::args(match::any().bind("x"), match::has_value(1.0f)));
        auto add_0 = match::name("add")(
            match::either_arg(0, 1)(match::has_value(0.0f, 1e-12), match::any().bind("x")));
        auto sub_0 =
            match::name("sub")(match::args(match::any().bind("x"), match::has_value(0.0f)));
        return match::any_of(mul_1, div_1, add_0, sub_0);
    }

    void apply(module& m, const match::matcher_result& r) const
    {
        auto ins  = r.result;
        auto c_in = r.instructions["x"];

        m.replace_instruction(ins, c_in);
    }
};

struct find_neg_unit_ops
{
    auto matcher() const
    {
        auto mul_neg_1 = match::name("mul")(
            match::either_arg(0, 1)(match::has_value(-1.0f), match::any().bind("x")));
        auto div_neg_1 =
            match::name("div")(match::args(match::any().bind("x"), match::has_value(-1.0f)));
        auto sub_0 =
            match::name("sub")(match::args(match::has_value(0.0f), match::any().bind("x")));
        return match::any_of(mul_neg_1, div_neg_1, sub_0);
    }

    void apply(module& m, const match::matcher_result& r) const
    {
        auto ins  = r.result;
        auto c_in = r.instructions["x"];

1280
        auto neg = m.insert_instruction(ins, make_op("neg"), c_in);
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
        m.replace_instruction(ins, neg);
    }
};

struct find_zero_ops
{
    auto matcher() const
    {
        auto mul_zero = match::name("mul")(
            match::either_arg(0, 1)(match::has_value(0.0f).bind("x"), match::any()));
        auto div_zero =
            match::name("div")(match::args(match::has_value(0.0f).bind("x"), match::any()));
        return match::any_of(mul_zero, div_zero);
    }

    void apply(module& m, const match::matcher_result& r) const
    {
        auto ins      = r.result;
        auto zero_ins = r.instructions["x"];

        m.replace_instruction(ins, zero_ins);
    }
};

1305
1306
1307
1308
1309
1310
1311
struct find_sub_const
{
    auto matcher() const
    {
        return match::name("sub")(match::arg(1)(match::is_constant().bind("c")));
    }

1312
    void apply(module& m, const match::matcher_result& r) const
1313
1314
1315
1316
    {
        auto ins   = r.result;
        auto c_ins = r.instructions["c"];

1317
        auto neg = m.insert_instruction(std::next(c_ins), make_op("neg"), c_ins);
1318
1319
1320

        auto args = ins->inputs();

1321
        m.replace_instruction(ins, make_op("add"), args.front(), neg);
1322
1323
1324
    }
};

kahmed10's avatar
kahmed10 committed
1325
1326
1327
1328
1329
1330
1331
1332
struct find_rsqrt
{
    auto matcher() const
    {
        return match::name("recip")(match::args(
            match::name("sqrt")(match::used_once(), match::args(match::any().bind("x")))));
    }

1333
    void apply(module& m, const match::matcher_result& r) const
kahmed10's avatar
kahmed10 committed
1334
1335
1336
1337
    {
        auto ins   = r.result;
        auto x_ins = r.instructions["x"];

1338
        m.replace_instruction(ins, make_op("rsqrt"), x_ins);
kahmed10's avatar
kahmed10 committed
1339
1340
1341
    }
};

1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
static bool same_ops(const std::vector<instruction_ref>& vec_ins)
{
    return std::all_of(vec_ins.begin(), vec_ins.end(), [&](auto i) {
        return i->get_operator() == vec_ins.front()->get_operator();
    });
}

struct find_split_reshape
{
    auto matcher() const
    {
        return match::name("reshape")(match::arg(0)(match::name("contiguous")(
                                          match::arg(0)(match::name("slice").bind("slice")))))
            .bind("reshape");
    }

1358
    void apply(module& m, const match::matcher_result& r) const
1359
    {
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
        auto slc   = r.instructions["slice"];
        auto rsp   = r.instructions["reshape"];
        auto input = slc->inputs().front();

        // Only apply simplification when slices are on a single axis
        auto axes = any_cast<op::slice>(slc->get_operator()).axes;
        if(axes.size() > 1)
        {
            return;
        }
1370
1371
1372
1373
1374
1375
1376

        auto split_outputs = get_splits(input);
        if(split_outputs.empty())
        {
            return;
        }

1377
1378
1379
1380
1381
1382
1383
        // Find all the reshapes (similar to rsp) that can be simplified
        std::vector<instruction_ref> conts;
        std::vector<instruction_ref> vec_rsp;

        // Iterate through slice and contiguous outputs to allow simplifications when
        // slice is followed by multiple reshapes
        for(auto& i : split_outputs)
shivadbhavsar's avatar
shivadbhavsar committed
1384
        {
1385
1386
1387
1388
            std::copy_if(i->outputs().begin(),
                         i->outputs().end(),
                         std::back_inserter(conts),
                         [](auto j) { return j->name() == "contiguous"; });
shivadbhavsar's avatar
shivadbhavsar committed
1389
1390
        }

1391
1392
1393
1394
1395
1396
1397
        for(auto& i : conts)
        {
            std::copy_if(i->outputs().begin(),
                         i->outputs().end(),
                         std::back_inserter(vec_rsp),
                         [&](auto j) { return j->get_operator() == rsp->get_operator(); });
        }
1398

1399
1400
        // No simplification needed if there is only one slice -> cont -> reshape
        if(vec_rsp.size() <= 1)
1401
1402
1403
1404
1405
        {
            return;
        }

        // ensure reshape happens after the axis dimension
1406
        auto axis         = axes[0];
1407
1408
1409
        auto slc_lens     = slc->get_shape().lens();
        auto slc_dim_size = std::accumulate(
            slc_lens.begin() + axis, slc_lens.end(), 1, std::multiplies<std::size_t>());
1410
1411
1412
        auto input_lens   = input->get_shape().lens();
        auto input_size   = input->get_shape().elements();
        auto slc_axis_len = input_lens[axis];
1413
1414
1415
1416
1417
1418

        // search the reshape output (standard shape) to decide which axis are
        // in its output corresponding to the slc_dim_size
        auto rsp_lens    = rsp->get_shape().lens();
        auto rsp_strides = rsp->get_shape().strides();
        rsp_strides.insert(rsp_strides.begin(), rsp_strides[0] * rsp_lens[0]);
1419
1420
1421

        auto ait     = std::find(rsp_strides.begin(), rsp_strides.end(), slc_dim_size);
        int rsp_axis = -1;
1422
        if(ait == rsp_strides.end())
1423
1424
1425
        {
            return;
        }
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
        else if(ait == rsp_strides.end() - 1)
        {
            // edge case
            // slice_dim == 1, in that case it could match with last stride of 1.
            // it should accumulate lengths from last dim in that case. discount 1 to avoid going
            // out of bounds.
            assert(slc_dim_size == 1);
            rsp_axis = std::distance(rsp_strides.begin(), ait) - 1;
        }
        else
        {
            rsp_axis = std::distance(rsp_strides.begin(), ait);
        }

1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
        // Calculate reshape output shape
        // Need to find a reshape such that data represented by instructions in vec_rsp can be
        // written as slices of this new reshape. This is done by holding all the dims constant in
        // rsp_lens to compute the required dim for rsp_axis (axis that will be sliced)

        // ex 1:  Input Shape: {2, 12, 4}, Slice Axis: 1, Slices are: (0:4), (4:8), (8:12),
        //        Reshape Outputs: {2, 2, 2, 4}, {2, 2, 2, 4}, {2, 2, 2, 4}
        //        rsp_axis = 1, rsp_out_lens (initial) = {2, 1, 2, 4}, rsp_fixed_size = 2*1*2*4 = 16
        //        rsp_axis_len = 2*12*4 / 16 = 6
        //        rsp_out_lens (final) = {2, 6, 2, 4}

        // ex 2:  Input Shape: {2, 12, 4}, Slice Axis: 1, Slices are: (0:4), (4:8), (8:12),
        //        Reshape Outputs: {2, 16}, {2, 16}, {2, 16}
        //        rsp_axis = 1, rsp_out_lens (initial) = {2, 1}, rsp_fixed_size = 2*1 = 2
        //        rsp_axis_len = 2*12*4 / 2 = 48
        //        rsp_out_lens (final) = {2, 48}
1456
1457

        std::vector<int64_t> rsp_out_lens(rsp_lens.begin(), rsp_lens.end());
1458
1459
1460
        rsp_out_lens[rsp_axis] = 1;
        auto rsp_fixed_size    = std::accumulate(
            rsp_out_lens.begin(), rsp_out_lens.end(), 1, std::multiplies<std::size_t>());
1461

1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
        // cannot create a valid reshape for simplification
        if(input_size % rsp_fixed_size != 0)
        {
            return;
        }
        auto rsp_axis_len      = input_size / rsp_fixed_size;
        rsp_out_lens[rsp_axis] = rsp_axis_len;

        // Calculate new slice start and end indices. Indices are scaled using the new reshape axis
        // and the original slice axis. See examples:

        // ex 1:  Input Shape: {2, 12, 4}, Slice Axis: 1, Slices are: (0:4), (4:8), (8:12),
        //        Reshape Outputs: {2, 2, 2, 4}, {2, 2, 2, 4}, {2, 2, 2, 4}
        //        slc_axis_len = 12, rsp_axis_len = 6
        //        New Starts: {0*6/12, 4*6/12,  8*6/12} = {0, 2, 4}
        //        New Ends:   {4*6/12, 8*6/12, 12*6/12} = {2, 4, 6}

        // ex 2:  Input Shape: {2, 12, 4}, Slice Axis: 1, Slices are: (0:4), (4:8), (8:12),
        //        Reshape Outputs: {2, 16}, {2, 16}, {2, 16}
        //        slc_axis_len = 12, rsp_axis_len = 48
        //        New Starts: {0*48/12, 4*48/12,  8*48/12} = { 0, 16, 32}
        //        New Ends:   {4*48/12, 8*48/12, 12*48/12} = {16, 32, 48}

        std::vector<int64_t> new_starts(vec_rsp.size());
        std::transform(vec_rsp.begin(), vec_rsp.end(), new_starts.begin(), [&](auto is) {
            auto cont   = is->inputs().front();
            auto og_slc = cont->inputs().front();
            return any_cast<op::slice>(og_slc->get_operator()).starts[0] * rsp_axis_len /
                   slc_axis_len;
        });
1492

1493
1494
1495
1496
1497
1498
1499
        std::vector<int64_t> new_ends(vec_rsp.size());
        std::transform(vec_rsp.begin(), vec_rsp.end(), new_ends.begin(), [&](auto is) {
            auto cont   = is->inputs().front();
            auto og_slc = cont->inputs().front();
            return any_cast<op::slice>(og_slc->get_operator()).ends[0] * rsp_axis_len /
                   slc_axis_len;
        });
1500

1501
1502
1503
1504
1505
        // insert the reshape instruction and add contiguous if needed
        if(not input->get_shape().standard())
        {
            input = m.insert_instruction(std::next(input), make_op("contiguous"), input);
        }
1506
        auto rsp_ins = m.insert_instruction(
1507
            std::next(input), make_op("reshape", {{"dims", rsp_out_lens}}), input);
1508
1509

        // replace the original reshape with slice
1510
        for(std::size_t i = 0; i < vec_rsp.size(); ++i)
1511
        {
1512
            m.replace_instruction(
1513
1514
1515
                vec_rsp[i],
                make_op(
                    "slice",
1516
                    {{"axes", {rsp_axis}}, {"starts", {new_starts[i]}}, {"ends", {new_ends[i]}}}),
1517
                rsp_ins);
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
        }
    }
};

struct find_split_transpose
{
    auto matcher() const
    {
        return match::name("transpose")(match::arg(0)(match::name("slice").bind("slice")))
            .bind("trans");
    }

1530
    void apply(module& m, const match::matcher_result& r) const
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
    {
        auto slc   = r.instructions["slice"];
        auto trans = r.instructions["trans"];

        auto input         = slc->inputs().front();
        auto split_outputs = get_splits(input);
        if(split_outputs.empty())
        {
            return;
        }
1541
1542
1543
1544
        if(std::any_of(split_outputs.begin(), split_outputs.end(), [](auto i) {
               return i->outputs().size() != 1;
           }))
            return;
1545
1546
1547
1548
1549
1550
1551
1552

        std::vector<instruction_ref> vec_trans(split_outputs.size());
        std::transform(split_outputs.begin(), split_outputs.end(), vec_trans.begin(), [](auto i) {
            return i->outputs().front();
        });

        // all transpose are the same
        auto perm = any_cast<op::transpose>(trans->get_operator()).dims;
1553
        if(not same_ops(vec_trans))
1554
1555
1556
1557
1558
        {
            return;
        }

        // insert an transpose instruction
1559
        auto tr = m.insert_instruction(
1560
            std::next(input), make_op("transpose", {{"permutation", perm}}), input);
1561
1562
1563
1564
1565

        // compute the axis in the slice
        auto axis = any_cast<op::slice>(slc->get_operator()).axes.front();
        auto it   = std::find(perm.begin(), perm.end(), axis);
        assert(it != perm.end());
Paul Fultz II's avatar
Paul Fultz II committed
1566
        int64_t axis_new = std::distance(perm.begin(), it);
1567
1568
1569
1570
1571
1572
1573

        for(auto in : split_outputs)
        {
            auto oper    = any_cast<op::slice>(in->get_operator());
            auto starts  = oper.starts;
            auto ends    = oper.ends;
            auto tr_orig = in->outputs().front();
1574
            m.replace_instruction(
1575
1576
1577
                tr_orig,
                make_op("slice", {{"axes", {axis_new}}, {"starts", starts}, {"ends", ends}}),
                tr);
1578
1579
1580
1581
        }
    }
};

1582
void simplify_algebra::apply(module& m) const
Paul's avatar
Paul committed
1583
{
Paul's avatar
Paul committed
1584
    // Run simplifications multiple times
1585
    for(int i = 0; i < 8; i++)
Paul's avatar
Paul committed
1586
    {
1587
        match::find_matches(m,
Paul's avatar
Paul committed
1588
                            find_inner_broadcast{},
1589
                            find_dot_broadcast{},
Paul's avatar
Paul committed
1590
1591
                            find_double_add_lit_broadcast{},
                            find_add_lit_broadcast{},
1592
                            find_add_convs{},
1593
                            find_conv_dot_horiz_fusion{},
Paul's avatar
Paul committed
1594
                            find_mul_conv{},
1595
                            find_mul_slice_conv{},
1596
1597
                            find_mul_dot{},
                            find_dot_mul{},
1598
                            find_mul_add{},
1599
1600
1601
                            find_unit_ops{},
                            find_neg_unit_ops{},
                            find_zero_ops{},
1602
                            find_dot_add{},
1603
                            find_conv_add{},
1604
1605
                            find_div_const{},
                            find_sub_const{},
kahmed10's avatar
kahmed10 committed
1606
                            find_rsqrt{},
1607
                            find_concat_op{},
1608
                            find_split_concat{},
1609
1610
1611
                            find_splits{},
                            find_split_reshape{},
                            find_split_transpose{});
1612
        dead_code_elimination{}.apply(m);
Paul's avatar
Paul committed
1613
    }
Paul's avatar
Paul committed
1614
}
Paul's avatar
Paul committed
1615

Paul's avatar
Paul committed
1616
} // namespace MIGRAPHX_INLINE_NS
Paul's avatar
Paul committed
1617
} // namespace migraphx