instruction.cpp 15.9 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2015-2022 Advanced Micro Devices, Inc. All rights reserved.
 *
 * 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/make_op.hpp>
Paul's avatar
Paul committed
25
26
27
#include <migraphx/instruction.hpp>
#include <migraphx/builtin.hpp>
#include <migraphx/erase.hpp>
Shucai Xiao's avatar
Shucai Xiao committed
28
29
#include <migraphx/module.hpp>
#include <migraphx/ranges.hpp>
Paul's avatar
Paul committed
30

Paul's avatar
Paul committed
31
namespace migraphx {
Paul's avatar
Paul committed
32
inline namespace MIGRAPHX_INLINE_NS {
Paul's avatar
Paul committed
33

34
35
36
37
38
39
template <class T>
auto equal_to(const T& x)
{
    return [&](const T& y) { return std::equal_to<T>{}(x, y); };
}

Paul's avatar
Paul committed
40
41
42
43
instruction::instruction(operation o, shape r, std::vector<instruction_ref> args)
    : op(std::move(o)), result(std::move(r)), arguments(std::move(args))
{
}
Paul's avatar
Paul committed
44

Shucai Xiao's avatar
Shucai Xiao committed
45
46
47
48
49
50
51
52
53
54
55
instruction::instruction(operation o,
                         shape r,
                         std::vector<instruction_ref> args,
                         std::vector<module_ref> modules)
    : op(std::move(o)),
      result(std::move(r)),
      arguments(std::move(args)),
      module_args(std::move(modules))
{
}

Paul's avatar
Paul committed
56
57
58
59
instruction::instruction(literal l)
    : op(builtin::literal{}), result(l.get_shape()), lit(std::move(l))
{
}
Paul's avatar
Paul committed
60

Paul's avatar
Paul committed
61
62
63
void instruction::replace(const shape& r)
{
    if(r != result)
Paul's avatar
Paul committed
64
    {
Paul's avatar
Paul committed
65
66
        result = r;
        for(auto&& ins : output)
Paul's avatar
Paul committed
67
        {
Lakhinder Walia's avatar
Lakhinder Walia committed
68
            assert(ins->name() == "@return" or ins->name().front() != '@');
Paul's avatar
Paul committed
69
            ins->recompute_shape();
Paul's avatar
Paul committed
70
71
        }
    }
Paul's avatar
Paul committed
72
}
Paul's avatar
Paul committed
73

Paul's avatar
Paul committed
74
void instruction::replace(operation o)
Paul's avatar
Paul committed
75
{
76
77
    normalized = false;
    op         = std::move(o);
Paul's avatar
Paul committed
78
79
80
    recompute_shape();
}

Shucai Xiao's avatar
Shucai Xiao committed
81
void instruction::recompute_shape() { replace(compute_shape(op, arguments, module_args)); }
Paul's avatar
Paul committed
82

Paul's avatar
Paul committed
83
84
85
void instruction::clear_arguments()
{
    for(auto&& arg : arguments)
Paul's avatar
Paul committed
86
    {
Paul's avatar
Paul committed
87
        arg->remove_output(*this);
Paul's avatar
Paul committed
88
    }
Paul's avatar
Paul committed
89
    arguments.clear();
Shucai Xiao's avatar
Shucai Xiao committed
90
    module_args.clear();
Paul's avatar
Paul committed
91
92
93
94
95
96
}

bool operator==(const instruction& i, instruction_ref ref)
{
    return std::addressof(i) == std::addressof(*ref);
}
Paul's avatar
Paul committed
97

Shucai Xiao's avatar
Shucai Xiao committed
98
bool instruction::valid(instruction_ref start, bool check_order) const
Paul's avatar
Paul committed
99
100
101
{
    return valid() && std::all_of(arguments.begin(), arguments.end(), [&](instruction_ref i) {
               auto self = std::find(i->outputs().begin(), i->outputs().end(), *this);
Shucai Xiao's avatar
Shucai Xiao committed
102
103
104
               bool ret  = self != i->outputs().end();
               if(check_order)
               {
105
                   // check arguments for this instruction before this instruction
Shucai Xiao's avatar
Shucai Xiao committed
106
107
108
                   ret = ret and (std::distance(start, i) < std::distance(start, *self));
               }
               return ret;
Paul's avatar
Paul committed
109
110
111
112
113
114
115
           });
}

bool instruction::valid() const
{
    shape computed;
    if(op.name() == "@literal")
Paul's avatar
Paul committed
116
    {
Paul's avatar
Paul committed
117
        computed = lit.get_shape();
Paul's avatar
Paul committed
118
    }
Paul's avatar
Paul committed
119
    else if(op.name() == "@param")
Paul's avatar
Paul committed
120
    {
Paul's avatar
Paul committed
121
        computed = result;
Paul's avatar
Paul committed
122
    }
Paul's avatar
Paul committed
123
    else
Paul's avatar
Paul committed
124
    {
Paul's avatar
Paul committed
125
        try
Paul's avatar
Paul committed
126
        {
Shucai Xiao's avatar
Shucai Xiao committed
127
            computed = compute_shape(op, arguments, module_args);
Paul's avatar
Paul committed
128
        }
Paul's avatar
Paul committed
129
        catch(migraphx::exception&)
Paul's avatar
Paul committed
130
        {
Paul's avatar
Paul committed
131
            return false;
Paul's avatar
Paul committed
132
133
        }
    }
134

Shucai Xiao's avatar
Shucai Xiao committed
135
136
    return (result == computed) &&
           std::all_of(output.begin(), output.end(), [&](instruction_ref i) {
Paul's avatar
Paul committed
137
138
139
               return std::find(i->inputs().begin(), i->inputs().end(), *this) != i->inputs().end();
           });
}
Paul's avatar
Paul committed
140

Paul's avatar
Paul committed
141
shape instruction::get_shape() const { return result; }
Lakhinder Walia's avatar
Lakhinder Walia committed
142

Paul's avatar
Paul committed
143
144
145
146
147
const literal& instruction::get_literal() const
{
    assert(op.name() == "@literal");
    return lit;
}
Paul's avatar
Paul committed
148

Paul's avatar
Paul committed
149
const operation& instruction::get_operator() const { return op; }
Paul's avatar
Paul committed
150

Paul's avatar
Paul committed
151
std::string instruction::name() const { return op.name(); }
Paul's avatar
Paul committed
152

Paul's avatar
Paul committed
153
const std::vector<instruction_ref>& instruction::inputs() const { return arguments; }
Paul's avatar
Paul committed
154

Shucai Xiao's avatar
Shucai Xiao committed
155
156
const std::vector<module_ref>& instruction::module_inputs() const { return module_args; }

Paul's avatar
Paul committed
157
const std::vector<instruction_ref>& instruction::outputs() const { return output; }
Paul's avatar
Paul committed
158

Paul's avatar
Paul committed
159
160
bool operator==(const instruction& x, const instruction& y)
{
161
162
163
164
165
166
167
    if(not std::equal(x.arguments.begin(),
                      x.arguments.end(),
                      y.arguments.begin(),
                      y.arguments.end(),
                      std::equal_to<instruction_ref>{}))
        return false;
    if(std::tie(x.result, x.op, x.module_args) != std::tie(y.result, y.op, y.module_args))
Paul's avatar
Paul committed
168
169
170
171
172
        return false;
    if(x.name() == "@literal")
        return x.lit == y.lit;
    return true;
}
Paul's avatar
Paul committed
173

174
bool operator!=(const instruction& x, const instruction& y) { return not(x == y); }
Paul's avatar
Paul committed
175

Paul's avatar
Paul committed
176
bool operator==(instruction_ref ref, const instruction& i) { return i == ref; }
Paul's avatar
Paul committed
177

178
bool operator!=(const instruction& i, instruction_ref ref) { return not(i == ref); }
Paul's avatar
Paul committed
179

180
bool operator!=(instruction_ref ref, const instruction& i) { return not(i == ref); }
Paul's avatar
Paul committed
181

Paul's avatar
Paul committed
182
183
void instruction::add_output(instruction_ref ins)
{
184
    if(std::find_if(output.begin(), output.end(), equal_to(ins)) == output.end())
Paul's avatar
Paul committed
185
186
        output.push_back(ins);
}
Paul's avatar
Paul committed
187

Paul's avatar
Paul committed
188
189
190
191
192
void instruction::backreference(instruction_ref ref)
{
    for(auto&& arg : ref->inputs())
        arg->add_output(ref);
}
Paul's avatar
Paul committed
193

Paul's avatar
Paul committed
194
195
196
197
198
199
200
201
void instruction::replace_argument(instruction_ref ins,
                                   instruction_ref old,
                                   instruction_ref new_ins)
{
    ins->replace_argument(old, new_ins);
    backreference(ins);
    ins->recompute_shape();
}
Paul's avatar
Paul committed
202

Shucai Xiao's avatar
Shucai Xiao committed
203
204
205
206
207
208
209
void instruction::replace_mod_argument(instruction_ref ins, module_ref old, module_ref new_mod)
{
    ins->replace_mod_argument(old, new_mod);
    backreference(ins);
    ins->recompute_shape();
}

Paul's avatar
Paul committed
210
211
212
213
214
215
216
217
void instruction::replace(instruction_ref ins,
                          operation o,
                          const shape& r,
                          std::vector<instruction_ref> args)
{
    ins->replace(std::move(o), r, std::move(args));
    backreference(ins);
}
Paul's avatar
Paul committed
218

Shucai Xiao's avatar
Shucai Xiao committed
219
220
221
222
223
224
225
226
227
228
void instruction::replace(instruction_ref ins,
                          operation o,
                          const shape& r,
                          std::vector<instruction_ref> args,
                          std::vector<module_ref> module_args)
{
    ins->replace(std::move(o), r, std::move(args), std::move(module_args));
    backreference(ins);
}

Paul's avatar
Paul committed
229
230
void instruction::replace(operation o, const shape& r, std::vector<instruction_ref> args)
{
231
232
    normalized = false;
    op         = std::move(o);
Paul's avatar
Paul committed
233
234
235
    replace(r);
    replace(std::move(args));
}
Paul's avatar
Paul committed
236

Shucai Xiao's avatar
Shucai Xiao committed
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
void instruction::replace(operation o,
                          const shape& r,
                          std::vector<instruction_ref> args,
                          std::vector<module_ref> mdl_args)
{
    op = std::move(o);
    replace(r);
    replace(std::move(args), std::move(mdl_args));
}

void instruction::replace_refs(
    instruction_ref ins,
    const std::unordered_map<instruction_ref, instruction_ref>& map_insts,
    const std::unordered_map<module_ref, module_ref>& map_mods)
{
    const auto& args = ins->inputs();
    for(const auto& arg : args)
    {
        if(contains(map_insts, arg))
        {
            instruction::replace_argument(ins, arg, map_insts.at(arg));
        }
    }

    const auto& module_args = ins->module_inputs();
    if(module_args.empty())
        return;

    for(const auto& mod : module_args)
    {
        if(contains(map_mods, mod))
        {
            instruction::replace_mod_argument(ins, mod, map_mods.at(mod));
        }
    }
}

Paul's avatar
Paul committed
274
275
276
277
278
void instruction::replace(std::vector<instruction_ref> args)
{
    clear_arguments();
    arguments = std::move(args);
}
Paul's avatar
Paul committed
279

Shucai Xiao's avatar
Shucai Xiao committed
280
281
282
283
284
285
286
void instruction::replace(std::vector<instruction_ref> args, std::vector<module_ref> mdl_args)
{
    clear_arguments();
    arguments   = std::move(args);
    module_args = std::move(mdl_args);
}

Paul's avatar
Paul committed
287
288
void instruction::replace_argument(instruction_ref old, instruction_ref new_ins)
{
289
290
    assert(std::any_of(arguments.begin(), arguments.end(), equal_to(old)));
    std::replace_if(arguments.begin(), arguments.end(), equal_to(old), new_ins);
Paul's avatar
Paul committed
291
292
    old->remove_output(*this);
}
Paul's avatar
Paul committed
293

Shucai Xiao's avatar
Shucai Xiao committed
294
295
296
297
298
299
void instruction::replace_mod_argument(module_ref old, module_ref new_mod)
{
    assert(std::any_of(module_args.begin(), module_args.end(), [&](auto i) { return i == old; }));
    std::replace(module_args.begin(), module_args.end(), old, new_mod);
}

300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
bool instruction::is_undefined() const
{
    if(op.name() == "undefined")
    {
        return true;
    }
    else if(this->inputs().empty())
    {
        return false;
    }
    else
    {
        return std::all_of(this->inputs().begin(), this->inputs().end(), [](auto arg) {
            return arg->is_undefined();
        });
    }
}

Paul's avatar
Paul committed
318
319
320
321
322
323
bool instruction::can_eval() const
{
    if(op.name() == "@literal")
    {
        return true;
    }
Paul's avatar
Paul committed
324
    else if(is_context_free(op))
Paul's avatar
Paul committed
325
    {
Paul's avatar
Paul committed
326
327
        return std::all_of(
            this->inputs().begin(), this->inputs().end(), [](auto arg) { return arg->can_eval(); });
Paul's avatar
Paul committed
328
329
330
331
332
333
334
    }
    else
    {
        return false;
    }
}

Paul's avatar
Paul committed
335
336
337
338
339
340
341
template<class InstructionRef>
static bool is_low_precision_float(InstructionRef ins)
{
    auto t = ins->get_shape().type();
    return contains({shape::float_type, shape::half_type}, t);
}

Paul's avatar
Paul committed
342
argument instruction::eval(bool check_eval) const
Paul's avatar
Paul committed
343
{
Paul's avatar
Paul committed
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
384
385
386
387
388
389
390
391
#if 0
    if (not this->can_eval())
        return {};

    auto r = fix<argument>([](auto self, auto ins) -> argument {
        if (ins->name() == "@literal")
        {
            if (is_low_precision_float(ins))
            {
                auto dlit = transform(ins->get_literal(), [](auto x) -> double {return x;});
                return dlit.get_argument();
            }
            return ins->get_literal().get_argument();
        }
        if (ins->name() == "convert")
        {
            if (is_low_precision_float(ins))
            {
                auto x = self(ins->inputs().front());
                if(is_low_precision_float(ins->inputs().front()))
                {
                    return x;
                }
                auto convert = make_op("convert", {{"target_type", to_value(shape::double_type)}});
                auto s = convert.compute_shape({x.get_shape()});
                return convert.compute(s, {x});
            }
        }
        if(is_context_free(ins->get_operator()))
        {
            std::vector<argument> args;
            std::transform(ins->inputs().begin(),
                           ins->inputs().end(),
                           std::back_inserter(args),
                           [&](auto arg) { return self(arg); });
            auto normal_op = ins->normalized_operator();
            auto s = normal_op.compute_shape(to_shapes(args));
            return normal_op.compute(s, args);
        }
        return {};
    })(this);

    auto convert = make_op("convert", {{"target_type", to_value(this->get_shape().type())}});
    auto s = convert.compute_shape({r.get_shape()});
    return convert.compute(s, {r});

#else

Paul's avatar
Paul committed
392
393
394
395
    if(op.name() == "@literal")
    {
        return this->get_literal().get_argument();
    }
Paul's avatar
Paul committed
396
    if(is_context_free(op))
Paul's avatar
Paul committed
397
    {
Paul's avatar
Paul committed
398
        if(check_eval and not this->can_eval())
Paul's avatar
Paul committed
399
            return {};
Paul's avatar
Paul committed
400
        std::vector<argument> args;
Paul's avatar
Paul committed
401
402
403
        std::transform(this->inputs().begin(),
                       this->inputs().end(),
                       std::back_inserter(args),
Paul's avatar
Paul committed
404
                       [](auto arg) { return arg->eval(false); });
405
        return normalized_operator().compute(result, args);
Paul's avatar
Paul committed
406
407
    }
    return {};
Paul's avatar
Paul committed
408
#endif
Paul's avatar
Paul committed
409
410
}

Paul's avatar
Paul committed
411
412
void instruction::finalize(context& ctx)
{
Paul's avatar
Paul committed
413
    if(has_finalize(this->op))
Paul's avatar
Paul committed
414
415
416
        this->op.finalize(ctx, this->get_shape(), to_shapes(this->inputs()));
}

417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
void instruction::print(std::ostream& os,
                        instruction_ref ins,
                        const std::unordered_map<instruction_ref, std::string>& names)
{
    os << names.at(ins) << " = ";

    os << ins->get_operator();

    if(ins->name() == "@literal")
    {
        if(ins->get_literal().get_shape().elements() > 10)
            os << "{ ... }";
        else
            os << "{" << ins->get_literal() << "}";
    }

433
    if(not ins->inputs().empty())
434
435
436
437
    {
        char delim = '(';
        for(auto&& arg : ins->inputs())
        {
Shucai Xiao's avatar
Shucai Xiao committed
438
439
            std::string arg_name = contains(names, arg) ? names.at(arg) : "?";
            os << delim << arg_name;
440
441
442
443
444
            delim = ',';
        }
        os << ")";
    }

Shucai Xiao's avatar
Shucai Xiao committed
445
    // print module inputs
446
    if(not ins->module_inputs().empty())
Shucai Xiao's avatar
Shucai Xiao committed
447
448
    {
        std::string delim = ", [";
449
        for(const const_module_ref& mod_arg : ins->module_inputs())
Shucai Xiao's avatar
Shucai Xiao committed
450
451
452
453
454
455
456
        {
            os << delim << mod_arg->name();
            delim = ", ";
        }
        os << "]";
    }

457
458
459
    // skip return instruction shape
    if(ins->name() != "@return")
        os << " -> " << ins->get_shape();
460
461
462
    // print tid

    os << ", target_id=" << ins->target_id;
463
464
}

Paul Fultz II's avatar
Paul Fultz II committed
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
static void debug_name(std::ostream& os, const instruction& ins)
{
    if(ins.name() == "@literal")
    {
        os << "@literal";
        if(ins.get_literal().get_shape().elements() > 10)
            os << "{ ... }";
        else
            os << "{" << ins.get_literal() << "}";
    }
    else
    {
        os << ins.get_operator();
    }
}

void instruction::debug_print() const
{
    debug_name(std::cout, *this);
    std::string delim = "(";
    for(auto arg : this->inputs())
    {
        std::cout << delim;
        debug_name(std::cout, *arg);
        delim = ", ";
    }
    if(not this->inputs().empty())
        std::cout << ")";
    std::cout << " -> " << this->get_shape() << std::endl;
}

Paul's avatar
Paul committed
496
instruction_ref instruction::get_output_alias(instruction_ref ins, bool shallow)
Paul's avatar
Paul committed
497
{
Paul's avatar
Paul committed
498
    auto i = ins->get_operator().output_alias(to_shapes(ins->inputs()));
Paul's avatar
Paul committed
499
500
    if(i < 0)
        return ins;
Paul's avatar
Paul committed
501
    if(shallow)
Paul's avatar
Paul committed
502
        return ins->inputs().at(i);
Paul's avatar
Paul committed
503
504
505
    return get_output_alias(ins->inputs().at(i));
}

506
507
508
509
510
511
512
513
514
515
516
517
518
519
void instruction::set_normalized(bool value) { normalized = value; }

bool instruction::is_normalized() const { return normalized; }

bool instruction::need_normalization() const
{
    return this->get_operator().need_normalization() and not normalized;
}

operation instruction::normalized_operator() const
{
    operation o = this->get_operator();
    if(this->need_normalization())
    {
520
        auto s = this->inputs().front()->get_shape();
521
        if(not normalize_attributes(o, s))
522
523
524
525
            return this->get_operator();
    }
    return o;
}
526
std::size_t instruction::get_target_id() const { return target_id; }
527

528
void instruction::set_target_id(std::size_t tid) { this->target_id = tid; }
529

Paul's avatar
Paul committed
530
531
532
533
534
535
536
537
std::vector<shape> to_shapes(const std::vector<instruction_ref>& args)
{
    std::vector<shape> shapes(args.size());
    std::transform(
        args.begin(), args.end(), shapes.begin(), [](instruction_ref i) { return i->get_shape(); });
    return shapes;
}

Paul's avatar
Paul committed
538
539
shape compute_shape(const operation& op, const std::vector<instruction_ref>& args)
{
Paul's avatar
Paul committed
540
    return op.compute_shape(to_shapes(args));
Paul's avatar
Paul committed
541
542
}

Shucai Xiao's avatar
Shucai Xiao committed
543
544
545
546
547
548
549
550
551
552
553
554
555
shape compute_shape(const operation& op,
                    const std::vector<instruction_ref>& args,
                    const std::vector<module_ref>& mods)
{
    if(mods.empty())
    {
        return op.compute_shape(to_shapes(args));
    }
    else
    {
        return op.compute_shape(to_shapes(args), mods);
    }
}
556
557
558
559
560
561
562
563
564
565
566
567
568
569

std::vector<shape> try_compute_shape(const operation& op, const std::vector<shape>& inputs)
{
    shape new_shape;
    try
    {
        new_shape = op.compute_shape(inputs);
    }
    catch(...)
    {
        return {};
    }
    return {new_shape};
}
570
571
572
573
574
575

migraphx::instruction* as_address(const instruction_ref& ins) noexcept
{
    return std::addressof(*ins);
}

Paul's avatar
Paul committed
576
} // namespace MIGRAPHX_INLINE_NS
Paul's avatar
Paul committed
577
} // namespace migraphx