simplify_reshapes.cpp 25.1 KB
Newer Older
1
#include <iterator>
Paul's avatar
Paul committed
2
3
4
#include <migraphx/simplify_reshapes.hpp>
#include <migraphx/program.hpp>
#include <migraphx/instruction.hpp>
5
#include <migraphx/op/as_shape.hpp>
6
#include <migraphx/op/transpose.hpp>
Paul's avatar
Paul committed
7
#include <migraphx/op/concat.hpp>
8
#include <migraphx/op/slice.hpp>
Paul's avatar
Paul committed
9
10
#include <migraphx/iterator_for.hpp>
#include <migraphx/ranges.hpp>
Paul's avatar
Paul committed
11
#include <migraphx/matcher.hpp>
12
#include <migraphx/permutation.hpp>
13
#include <migraphx/dead_code_elimination.hpp>
Paul's avatar
Paul committed
14
#include <unordered_set>
15
#include <migraphx/make_op.hpp>
16
#include <migraphx/tune_axis.hpp>
17

18
#include <map>
Paul's avatar
Paul committed
19

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

Paul's avatar
Paul committed
23
const auto& reshaper_names()
Paul's avatar
Paul committed
24
{
25
26
    // clang-format off
    static const std::unordered_set<std::string> names = {
27
        "flatten",
28
        "reshape",
29
30
31
        "contiguous",
        "squeeze",
        "unsqueeze"
32
33
    };
    // clang-format on
Paul's avatar
Paul committed
34
    return names;
Paul's avatar
Paul committed
35
36
}

Paul's avatar
Paul committed
37
bool is_reshaper(instruction_ref ins) { return contains(reshaper_names(), ins->name()); }
Paul's avatar
Paul committed
38
39
40

instruction_ref find_transpose_input(instruction_ref ins)
{
Paul's avatar
Paul committed
41
    if(ins->inputs().size() != 1)
Paul's avatar
Paul committed
42
        return ins;
Paul's avatar
Paul committed
43
    if(ins->inputs().front()->name() == "contiguous")
Paul's avatar
Paul committed
44
45
46
47
        return find_transpose_input(ins->inputs().front());
    if(ins->inputs().front()->name() == "transpose")
        return ins->inputs().front();
    return ins;
Paul's avatar
Paul committed
48
49
}

50
51
52
53
54
55
56
auto get_transpose_dims(instruction_ref ins)
{
    return any_cast<const op::transpose&>(ins->get_operator()).dims;
}

bool is_no_transpose(const std::vector<int64_t>& dims)
{
Paul's avatar
Paul committed
57
    if(dims.empty())
58
        return true;
Paul's avatar
Paul committed
59
    if(dims.front() != 0)
60
        return false;
Paul's avatar
Paul committed
61
62
    return std::adjacent_find(
               dims.begin(), dims.end(), [](auto x, auto y) { return (y - x) != 1; }) == dims.end();
63
64
}

Paul's avatar
Paul committed
65
struct find_reshaper
Paul's avatar
Paul committed
66
{
Paul's avatar
Paul committed
67
    auto matcher() const
Paul's avatar
Paul committed
68
    {
Paul's avatar
Paul committed
69
70
        return match::name(reshaper_names())(
            match::any_of[match::outputs()](match::name(reshaper_names())));
Paul's avatar
Paul committed
71
72
    }

73
    void apply(module& m, const match::matcher_result& mr) const
Paul's avatar
Paul committed
74
75
76
77
    {
        auto ins = mr.result;
        std::vector<instruction_ref> reshapes{ins};
        while(is_reshaper(reshapes.back()))
Paul's avatar
Paul committed
78
        {
Paul's avatar
Paul committed
79
            assert(!reshapes.back()->inputs().empty());
80
            assert(m.has_instruction(reshapes.back()->inputs().front()));
Paul's avatar
Paul committed
81
82
83
            auto input = reshapes.back()->inputs().front();
            reshapes.push_back(input);
        }
Paul's avatar
Paul committed
84

85
        std::pair<instruction_ref, instruction_ref> r{m.end(), m.end()};
Paul's avatar
Paul committed
86
87
88
89
90
91
        for(auto start : iterator_for(reshapes))
        {
            auto last = std::find_if(reshapes.rbegin(), reshapes.rend(), [&](auto&& i) {
                return i->get_shape() == (*start)->get_shape() and i != (*start);
            });
            if(last != reshapes.rend())
Paul's avatar
Paul committed
92
            {
Paul's avatar
Paul committed
93
94
                r = std::make_pair(*start, *last);
                break;
Paul's avatar
Paul committed
95
96
            }
        }
Paul's avatar
Paul committed
97
        if(r.first != r.second)
Paul's avatar
Paul committed
98
        {
99
            m.replace_instruction(r.first, r.second);
Paul's avatar
Paul committed
100
        }
Paul's avatar
Paul committed
101
102
103
    }
};

Paul's avatar
Paul committed
104
105
106
107
108
struct find_nop_reshapes
{
    auto matcher() const
    {
        auto reshapes = reshaper_names();
109
110
111
        reshapes.insert("as_shape");
        reshapes.insert("broadcast");
        reshapes.insert("concat");
Paul Fultz II's avatar
Paul Fultz II committed
112
        reshapes.insert("convert");
113
114
        reshapes.insert("multibroadcast");
        reshapes.insert("pad");
Paul's avatar
Paul committed
115
        reshapes.insert("slice");
116
        reshapes.insert("transpose");
Paul's avatar
Paul committed
117
        return match::name(reshapes)(match::same_shape(match::arg(0)));
Paul's avatar
Paul committed
118
119
    }

120
    void apply(module& m, const match::matcher_result& mr) const
Paul's avatar
Paul committed
121
122
    {
        auto ins = mr.result;
123
        m.replace_instruction(ins, ins->inputs().front());
Paul's avatar
Paul committed
124
125
126
    }
};

Paul's avatar
Paul committed
127
128
129
130
struct find_transpose
{
    auto matcher() const
    {
Paul's avatar
Format  
Paul committed
131
132
133
134
        auto output_not_transpose =
            match::none_of(match::skip_output(match::name("contiguous"))(match::name("transpose")));
        auto input_has_transpose =
            match::skip(match::name("contiguous"))(match::args(match::name("transpose")));
Paul's avatar
Paul committed
135
        return match::name("transpose")(output_not_transpose, input_has_transpose);
Paul's avatar
Paul committed
136
137
    }

138
    void apply(module& m, const match::matcher_result& mr) const
Paul's avatar
Paul committed
139
140
    {
        auto ins = mr.result;
Paul's avatar
Paul committed
141
142
        auto x   = ins;
        auto t   = ins;
Paul's avatar
Paul committed
143
144
145
146
147
148
149
150
151
152
153
154
        std::vector<std::int64_t> dims(ins->get_shape().lens().size());
        std::iota(dims.begin(), dims.end(), 0);
        do
        {
            dims = reorder_dims(get_transpose_dims(t), dims);
            x    = t;
            t    = find_transpose_input(x);
        } while(x != t and t->name() == "transpose");
        if(t == ins or t->name() != "transpose")
            return;
        if(is_no_transpose(dims))
        {
155
            m.replace_instruction(ins, t->inputs().front());
Paul's avatar
Paul committed
156
157
        }
        else
Paul's avatar
Paul committed
158
        {
159
            m.replace_instruction(
160
                ins, make_op("transpose", {{"permutation", dims}}), t->inputs().front());
Paul's avatar
Paul committed
161
        }
Paul's avatar
Paul committed
162
    }
Paul's avatar
Paul committed
163
164
};

165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
struct find_nested_convert
{
    auto matcher() const { return match::name("convert")(match::arg(0)(match::name("convert"))); }

    void apply(module& m, const match::matcher_result& mr) const
    {
        auto ins   = mr.result;
        auto x     = ins->inputs().front();
        auto input = x->inputs().front();

        if(ins->get_shape() != input->get_shape())
            return;

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

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
struct find_nested_slice
{
    auto matcher() const { return match::name("slice")(match::arg(0)(match::name("slice"))); }

    using axes_map = std::map<std::size_t, std::pair<std::size_t, std::size_t>>;

    static axes_map get_axes(instruction_ref ins)
    {
        axes_map result;
        auto op = any_cast<op::slice>(ins->get_operator());
        for(std::size_t i = 0; i < op.axes.size(); i++)
        {
            result[op.axes[i]] = std::make_pair(op.starts[i], op.ends[i]);
        }
        return result;
    }

    static axes_map merge(const axes_map& m1, const axes_map& m2)
    {
        axes_map result;
        // Non overlapping
        for(auto&& p : m1)
        {
            if(contains(m2, p.first))
                continue;
            result[p.first] = p.second;
        }
        for(auto&& p : m2)
        {
            if(contains(m1, p.first))
                continue;
            result[p.first] = p.second;
        }
        // Overlapping
        for(auto&& p1 : m1)
        {
            if(not contains(m2, p1.first))
                continue;
            auto&& v1        = p1.second;
            auto&& v2        = m2.at(p1.first);
            auto start       = v1.first + v2.first;
            auto end         = start + (v2.second - v2.first);
            result[p1.first] = std::make_pair(start, end);
        }
        return result;
    }

229
    void apply(module& m, const match::matcher_result& mr) const
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
    {
        auto ins   = mr.result;
        auto slice = ins->inputs().front();
        auto input = slice->inputs().front();

        auto a1 = get_axes(ins);
        auto a2 = get_axes(slice);

        auto axes = merge(a2, a1);

        auto op = op::slice{};
        for(auto&& pp : axes)
        {
            op.axes.push_back(pp.first);
            op.starts.push_back(pp.second.first);
            op.ends.push_back(pp.second.second);
        }
247
        m.replace_instruction(ins, op, input);
248
249
250
    }
};

Paul's avatar
Paul committed
251
252
253
254
struct find_concat_transpose
{
    auto matcher() const
    {
255
        return match::name("concat")(match::all_of[match::inputs()](match::transpose_shape()));
Paul's avatar
Paul committed
256
257
    }

258
    void apply(module& m, const match::matcher_result& mr) const
Paul's avatar
Paul committed
259
    {
Shucai Xiao's avatar
Shucai Xiao committed
260
261
262
        auto ins          = mr.result;
        auto trans_inputs = ins->inputs();
        auto s            = trans_inputs.front()->get_shape();
Paul's avatar
Paul committed
263
        assert(s.transposed());
Shucai Xiao's avatar
Shucai Xiao committed
264
265
266
267
268
269
270
271
272
273
274
275
276
        auto op          = any_cast<op::concat>(ins->get_operator());
        auto permutation = find_permutation(s);

        // permutation should be the same for all inputs
        if(!std::all_of(trans_inputs.begin(), trans_inputs.end(), [&](auto in) {
               return (find_permutation(in->get_shape()) == permutation);
           }))
        {
            return;
        }

        // axis could be a negative value
        int64_t n_dim = static_cast<int64_t>(s.lens().size());
277
        op.axis       = tune_axis(n_dim, op.axis, op.name());
Shucai Xiao's avatar
Shucai Xiao committed
278

Paul's avatar
Paul committed
279
        auto ipermutation = invert_permutation(permutation);
Paul's avatar
Paul committed
280
        op.axis           = ipermutation[op.axis];
Paul's avatar
Paul committed
281
282
283

        std::vector<instruction_ref> inputs;
        std::transform(
Paul's avatar
Paul committed
284
            ins->inputs().begin(), ins->inputs().end(), std::back_inserter(inputs), [&](auto i) {
285
                return m.insert_instruction(
286
                    ins, make_op("transpose", {{"permutation", permutation}}), i);
Paul's avatar
Paul committed
287
            });
288
289
        auto concat = m.insert_instruction(ins, op, inputs);
        auto t      = m.insert_instruction(
290
            ins, make_op("transpose", {{"permutation", ipermutation}}), concat);
Paul's avatar
Paul committed
291
        assert(ins->get_shape().lens() == t->get_shape().lens());
292
        m.replace_instruction(ins, t);
Paul's avatar
Paul committed
293
294
295
    }
};

Paul Fultz II's avatar
Paul Fultz II committed
296
297
298
299
300
301
302
303
304
305
306
307
308
struct find_nested_concat
{
    auto matcher() const
    {
        return match::name("concat")(match::any_of[match::inputs()](match::name("concat")));
    }

    static std::size_t get_axis(instruction_ref ins)
    {
        auto op = any_cast<op::concat>(ins->get_operator());
        return op.axis;
    }

309
    void apply(module& m, const match::matcher_result& mr) const
Paul Fultz II's avatar
Paul Fultz II committed
310
311
312
313
314
315
316
317
318
319
320
321
322
    {
        auto ins  = mr.result;
        auto axis = get_axis(ins);
        std::vector<instruction_ref> args;
        fix([&](auto self, auto&& inputs) {
            for(auto&& i : inputs)
            {
                if(i->name() == "concat" and get_axis(i) == axis and i->outputs().size() == 1)
                    self(i->inputs());
                else
                    args.push_back(i);
            }
        })(ins->inputs());
323
        m.replace_instruction(ins, ins->get_operator(), args);
Paul Fultz II's avatar
Paul Fultz II committed
324
325
326
    }
};

327
328
329
330
331
332
333
334
struct find_resize
{
    auto matcher() const
    {
        return match::name("gather")(
            match::args(match::name("reshape").bind("data"), match::is_constant().bind("ind")));
    }

335
    void apply(module& m, const match::matcher_result& r) const
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
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
    {
        auto ins     = r.result;
        auto ins_rsp = r.instructions["data"];
        auto ins_ind = r.instructions["ind"];

        // resize input shape
        if(ins_rsp->get_shape().lens().size() != 1)
        {
            return;
        }

        // resize output shape
        const auto& in_shape  = ins_rsp->inputs().front()->get_shape();
        const auto& out_shape = ins->get_shape();
        // check if output shape is multiple of input shape
        const auto& in_lens  = in_shape.lens();
        const auto& out_lens = out_shape.lens();
        if(in_lens.size() != out_lens.size())
        {
            return;
        }

        // output shape must be multiple of input shape
        std::vector<bool> is_multi(in_lens.size());
        std::transform(
            in_lens.begin(), in_lens.end(), out_lens.begin(), is_multi.begin(), [](auto x, auto y) {
                return (y % x == 0);
            });
        if(not std::all_of(is_multi.begin(), is_multi.end(), [](auto b) { return b; }))
        {
            return;
        }

        // output must be multiple of inputs
        std::vector<std::size_t> scales(in_lens.size());
        std::transform(
            in_lens.begin(), in_lens.end(), out_lens.begin(), scales.begin(), [](auto x, auto y) {
                return y / x;
            });

        // if ind is not constant, cannot optimize
        std::vector<int> vec_ind;
        auto arg_ind = ins_ind->eval();
        if(arg_ind.empty())
        {
            return;
        }
        arg_ind.visit([&](auto v) { vec_ind.assign(v.begin(), v.end()); });
384
        if(not all_of(range(out_shape.elements()), [&](auto i) {
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
               auto out_idx = out_shape.multi(i);
               auto in_idx  = out_idx;
               std::transform(out_idx.begin(),
                              out_idx.end(),
                              scales.begin(),
                              in_idx.begin(),
                              [&](auto io, auto scale) { return io - (io % scale); });
               return vec_ind[i] == vec_ind[out_shape.index(in_idx)];
           }))
        {
            return;
        }

        // wrap up shapes for multibroadcast
        std::vector<std::pair<std::size_t, std::size_t>> dim_scales;
        std::transform(in_lens.begin(),
                       in_lens.end(),
                       out_lens.begin(),
                       std::back_inserter(dim_scales),
                       [](auto x, auto y) { return std::make_pair(x, y / x); });

        std::vector<int64_t> in_dims;
        std::vector<int64_t> out_dims;
        for(auto& isp : dim_scales)
        {
            in_dims.push_back(isp.first);
            out_dims.push_back(isp.first * isp.second);
            if(isp.first == 1 or isp.second == 1)
            {
                continue;
            }

            out_dims.back() = isp.first;
            in_dims.push_back(1);
            out_dims.push_back(isp.second);
        }

        auto in_rsp   = ins_rsp->inputs().front();
423
        auto rsp_data = m.insert_instruction(
424
            ins_rsp, migraphx::make_op("reshape", {{"dims", in_dims}}), in_rsp);
425
        auto mb_rsp = m.insert_instruction(
426
            ins_rsp, migraphx::make_op("multibroadcast", {{"out_lens", out_dims}}), rsp_data);
427
        auto std_mb = m.insert_instruction(ins, migraphx::make_op("contiguous"), mb_rsp);
428
        std::vector<int64_t> rsp_dims(out_lens.begin(), out_lens.end());
429
        m.replace_instruction(ins, migraphx::make_op("reshape", {{"dims", rsp_dims}}), std_mb);
430
431
432
433
434
435
436
437
438
439
440
441
    }
};

struct find_where_op
{
    auto matcher() const
    {
        return match::name("gather")(
            match::args(match::name("reshape")(match::arg(0)(match::name("concat").bind("data"))),
                        match::is_constant().bind("ind")));
    }

442
    void apply(module& m, const match::matcher_result& r) const
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
    {
        auto ins     = r.result;
        auto concat  = r.instructions["data"];
        auto ins_ind = r.instructions["ind"];
        std::vector<bool> vec_ind;
        auto arg_ind = ins_ind->eval();
        arg_ind.visit([&](auto v) { vec_ind.assign(v.begin(), v.end()); });
        // ind has to be the same value
        auto val = vec_ind.front();
        if(not std::all_of(vec_ind.begin(), vec_ind.end(), [&](auto v) { return (v == val); }))
        {
            return;
        }

        // concat axis must be 0
        auto op = any_cast<op::concat>(concat->get_operator());
        if(op.axis != 0)
        {
            return;
        }

        // check concat inputs, it has to be 2 and have the same shape
        const auto& inputs = concat->inputs();
        if(inputs.size() != 2)
        {
            return;
        }
        if(inputs.at(0)->get_shape() != inputs.at(1)->get_shape())
        {
            return;
        }
        if(inputs.at(0)->get_shape().lens() != ins_ind->get_shape().lens())
        {
            return;
        }

        if(val)
        {
481
            m.replace_instruction(ins, inputs.at(0));
482
483
484
        }
        else
        {
485
            m.replace_instruction(ins, inputs.at(1));
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
        }
    }
};

struct find_reshape_cont
{
    auto matcher() const
    {
        return match::pointwise(
            match::nargs(2),
            match::either_arg(0, 1)(
                match::name("reshape")(match::args(match::name("contiguous").bind("cont")))
                    .bind("rsp"),
                match::any()));
    }

502
    void apply(module& m, const match::matcher_result& r) const
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
    {
        auto ins      = r.result;
        auto ins_cont = r.instructions["cont"];
        auto in_ins   = r.instructions["rsp"];

        auto cont_input = ins_cont->inputs().front();
        auto lens       = cont_input->get_shape().lens();
        std::vector<int64_t> dims(lens.begin(), lens.end());

        if(in_ins->get_shape() != ins->get_shape())
        {
            return;
        }

        if(not std::all_of(ins->inputs().begin(), ins->inputs().end(), [](auto i) {
               return i->get_shape().standard();
           }))
        {
            return;
        }

        auto out_lens = ins->get_shape().lens();
        std::vector<int64_t> out_dims(out_lens.begin(), out_lens.end());
        std::vector<instruction_ref> inputs;
        for(const auto& in : ins->inputs())
        {
            if(in == in_ins)
            {
                inputs.push_back(cont_input);
            }
            else
            {
                inputs.push_back(
536
                    m.insert_instruction(ins, make_op("reshape", {{"dims", dims}}), in));
537
538
            }
        }
539
540
        auto out = m.insert_instruction(ins, ins->get_operator(), inputs);
        m.replace_instruction(ins, make_op("reshape", {{"dims", out_dims}}), out);
541
542
543
    }
};

544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
// match sequence of transpose --> contiguous --> reshaper_op
auto match_transpose_contiguous_reshaper()
{
    return match::name({"reshape", "squeeze", "unsqueeze"})(
               match::used_once(),
               match::args(
                   match::name("contiguous")(
                       match::used_once(), match::args(match::transpose_shape().bind("trans_ins")))
                       .bind("cont_ins")))
        .bind("reshaper_ins");
};

// finds the pattern of transpose --> contiguous --> reshaper_op --> unary
// application of this matcher moves the unary operation before the contiguous so it becomes
// transpose --> unary --> contiguous --> reshaper_op. later pointwise sub-module can be created out
// of unary --> contiguous --> reshaper_op. Such pattern appears in depthToSpace or spaceToDepth
// operator.
struct find_transpose_contiguous_reshaper_unary
{
    auto matcher() const
    {
565
566
567
        return pointwise(match::used_once(),
                         match::nargs(1),
                         match::args(match_transpose_contiguous_reshaper()));
568
569
    }

570
    void apply(module& m, const match::matcher_result& r) const
571
572
573
574
575
576
    {
        auto ins           = r.result;
        auto reshaper_ins  = r.instructions["reshaper_ins"];
        auto trans_ins     = r.instructions["trans_ins"];
        auto cont_ins      = r.instructions["cont_ins"];
        auto unary_op_name = ins->get_operator().name();
577
578
        auto unary_ins     = m.insert_instruction(cont_ins, make_op(unary_op_name), trans_ins);
        auto new_cont_ins  = m.insert_instruction(cont_ins, make_op("contiguous"), unary_ins);
579
        // older cont and reshape are removed by deadcode elimination
580
        m.replace_instruction(ins, reshaper_ins->get_operator(), new_cont_ins);
581
582
583
    }
};

Paul's avatar
Paul committed
584
struct find_slice_transpose
Paul's avatar
Paul committed
585
586
587
{
    auto matcher() const
    {
Paul's avatar
Format  
Paul committed
588
589
        return match::any(match::any_of[match::outputs()](
            match::name("slice")(match::output(match::name("transpose")))));
Paul's avatar
Paul committed
590
591
592
593
594
    }

    static std::vector<int64_t> find_common_perm(const std::vector<instruction_ref>& transposes)
    {
        std::map<std::vector<int64_t>, int64_t> count;
Paul's avatar
Format  
Paul committed
595
        for(auto t : transposes)
Paul's avatar
Paul committed
596
597
598
599
600
        {
            auto perm = t->get_operator().to_value()["permutation"].to_vector<int64_t>();
            count[perm]++;
        }
        return std::max_element(
Paul's avatar
Format  
Paul committed
601
602
                   count.begin(), count.end(), by(std::less<>{}, [](auto&& p) { return p.second; }))
            ->first;
Paul's avatar
Paul committed
603
604
605
606
    }

    void apply(module& m, const match::matcher_result& r) const
    {
Paul's avatar
Format  
Paul committed
607
        auto ins = r.result;
Paul's avatar
Paul committed
608
        std::vector<instruction_ref> splits;
Paul's avatar
Format  
Paul committed
609
610
611
612
613
614
615
616
        std::copy_if(ins->outputs().begin(),
                     ins->outputs().end(),
                     std::back_inserter(splits),
                     [&](instruction_ref out) {
                         return out->name() == "slice" and out->outputs().size() == 1 and
                                out->outputs().front()->name() == "transpose";
                     });
        if(splits.size() < 2)
Paul's avatar
Paul committed
617
618
            return;
        std::vector<instruction_ref> transposes;
Paul's avatar
Format  
Paul committed
619
620
621
622
623
        std::transform(splits.begin(),
                       splits.end(),
                       std::back_inserter(transposes),
                       [](auto split) { return split->outputs().front(); });
        auto perm  = find_common_perm(transposes);
Paul's avatar
Paul committed
624
        auto iperm = invert_permutation(perm);
Paul's avatar
Format  
Paul committed
625
626
627
        auto pre   = m.insert_instruction(
            std::next(ins), make_op("transpose", {{"permutation", perm}}), ins);
        for(auto i : range(transposes.size()))
Paul's avatar
Paul committed
628
629
        {
            auto split = splits[i];
Paul's avatar
Format  
Paul committed
630
631
            auto t     = transposes[i];
            auto op    = any_cast<op::slice>(split->get_operator());
Paul's avatar
Paul committed
632
633
634
            std::transform(op.axes.begin(), op.axes.end(), op.axes.begin(), [&](auto axis) {
                return iperm[axis];
            });
Paul's avatar
Paul committed
635
            auto new_ins = m.insert_instruction(t, op, pre);
Paul's avatar
Format  
Paul committed
636
            if(t->get_operator() != pre->get_operator())
Paul's avatar
Paul committed
637
638
            {
                auto curr = t->get_operator().to_value()["permutation"].to_vector<int64_t>();
Paul's avatar
Format  
Paul committed
639
640
                new_ins   = m.insert_instruction(
                    t, make_op("transpose", {{"permutation", reorder_dims(iperm, curr)}}), new_ins);
Paul's avatar
Paul committed
641
642
643
644
645
646
            }
            m.replace_instruction(t, new_ins);
        }
    }
};

Paul's avatar
Paul committed
647
648
649
650
651
652
653
654
655
656
657
struct find_transpose_slice
{
    auto matcher() const
    {
        return match::name("transpose")(match::all_of[match::outputs()](match::name("slice")));
    }

    static std::vector<int64_t> slice_distance(const op::slice& op)
    {
        assert(op.starts.size() == op.ends.size());
        std::vector<int64_t> result(op.starts.size());
Paul's avatar
Format  
Paul committed
658
659
        std::transform(
            op.ends.begin(), op.ends.end(), op.starts.begin(), result.begin(), std::minus<>{});
Paul's avatar
Paul committed
660
661
662
663
664
        return result;
    }

    void apply(module& m, const match::matcher_result& r) const
    {
Paul's avatar
Format  
Paul committed
665
        auto ins    = r.result;
Paul's avatar
Paul committed
666
        auto slices = ins->outputs();
Paul's avatar
Format  
Paul committed
667
        if(slices.empty())
Paul's avatar
Paul committed
668
            return;
Paul's avatar
Format  
Paul committed
669
        auto slice     = any_cast<op::slice>(slices.front()->get_operator());
Paul's avatar
Paul committed
670
671
        auto sdistance = slice_distance(slice);
        // Check all distances and axes are the same
Paul's avatar
Format  
Paul committed
672
673
674
675
        if(std::any_of(slices.begin(), slices.end(), [&](auto sins) {
               auto s = any_cast<op::slice>(sins->get_operator());
               return s.axes != slice.axes or slice_distance(s) != sdistance;
           }))
Paul's avatar
Paul committed
676
677
678
            return;
        // Check distances are divisible by axes
        auto mod_by_distance = [&](const auto& v, auto f) {
Paul's avatar
Format  
Paul committed
679
680
681
682
683
684
685
686
687
688
            return std::inner_product(v.begin(),
                                      v.end(),
                                      sdistance.begin(),
                                      0,
                                      std::plus<>{},
                                      [&](auto x, auto d) -> uint64_t {
                                          if(d == 0)
                                              return 1;
                                          return f(x) % d;
                                      });
Paul's avatar
Paul committed
689
        };
Paul's avatar
Format  
Paul committed
690
691
        if(mod_by_distance(slice.axes, [&](auto x) { return ins->get_shape().lens()[x]; }) != 0 or
           mod_by_distance(slice.starts, id{}) != 0 or mod_by_distance(slice.ends, id{}) != 0)
Paul's avatar
Paul committed
692
693
            return;
        // TODO: Handle multiple axes
Paul's avatar
Format  
Paul committed
694
        if(sdistance.size() != 1)
Paul's avatar
Paul committed
695
696
697
            return;
        auto axis = slice.axes.front();
        // Skip if axis would be packed
Paul's avatar
Format  
Paul committed
698
699
700
        if(std::all_of(ins->get_shape().lens().begin(),
                       ins->get_shape().lens().begin() + axis,
                       [](auto x) { return x == 1; }))
Paul's avatar
Paul committed
701
            return;
Paul's avatar
Paul committed
702
        // Compute axis before transpose to use for unsqueeeze
Paul's avatar
Format  
Paul committed
703
        auto perm    = ins->get_operator().to_value()["permutation"].to_vector<int64_t>();
Paul's avatar
Paul committed
704
        auto preaxis = std::find(perm.begin(), perm.end(), axis) - perm.begin();
Paul's avatar
Paul committed
705
        // Make unsqeeze
Paul's avatar
Format  
Paul committed
706
        auto unsqueeze = m.insert_instruction(
Paul's avatar
Paul committed
707
            ins, make_op("unsqueeze", {{"axes", {preaxis}}, {"steps", sdistance}}), ins->inputs());
Paul's avatar
Paul committed
708
709
        // Make transpose
        std::transform(perm.begin(), perm.end(), perm.begin(), [&](auto i) {
Paul's avatar
Paul committed
710
            if(i > preaxis)
Paul's avatar
Paul committed
711
712
713
                return i + 1;
            return i;
        });
Paul's avatar
Format  
Paul committed
714
        perm.insert(perm.begin(), preaxis + 1);
Paul's avatar
Format  
Paul committed
715
716
        auto transpose =
            m.insert_instruction(ins, make_op("transpose", {{"permutation", perm}}), unsqueeze);
Paul's avatar
Paul committed
717
        // Slice and sqeeze
Paul's avatar
Format  
Paul committed
718
        for(auto s : slices)
Paul's avatar
Paul committed
719
        {
Paul's avatar
Format  
Paul committed
720
721
722
723
            auto op        = any_cast<op::slice>(s->get_operator());
            op.axes        = {0};
            op.starts      = {op.starts.front() / sdistance.front()};
            op.ends        = {op.ends.front() / sdistance.front()};
Paul's avatar
Paul committed
724
            auto slice_ins = m.insert_instruction(ins, op, transpose);
Paul's avatar
Format  
Paul committed
725
726
            auto squeeze =
                m.insert_instruction(ins, make_op("squeeze", {{"axes", {0}}}), slice_ins);
Paul's avatar
Paul committed
727
728
729
730
731
            m.replace_instruction(s, squeeze);
        }
    }
};

732
void simplify_reshapes::apply(module& m) const
Paul's avatar
Paul committed
733
{
Paul's avatar
Paul committed
734
    for(int i = 0; i < 4; i++)
Paul's avatar
Paul committed
735
    {
736
        match::find_matches(m,
737
738
739
                            find_where_op{},
                            find_resize{},
                            find_reshape_cont{},
740
741
742
743
                            find_nop_reshapes{},
                            find_reshaper{},
                            find_transpose{},
                            find_concat_transpose{},
744
                            find_nested_convert{},
745
                            find_nested_slice{},
746
                            find_nested_concat{},
Paul's avatar
Paul committed
747
                            find_transpose_slice{},
Paul's avatar
Paul committed
748
                            find_slice_transpose{},
749
                            find_transpose_contiguous_reshaper_unary{});
750
        dead_code_elimination{}.apply(m);
Paul's avatar
Paul committed
751
    }
Paul's avatar
Paul committed
752
753
}

Paul's avatar
Paul committed
754
} // namespace MIGRAPHX_INLINE_NS
Paul's avatar
Paul committed
755
} // namespace migraphx