propagate_constant.cpp 1.96 KB
Newer Older
Paul's avatar
Paul committed
1
#include <migraphx/propagate_constant.hpp>
Paul's avatar
Paul committed
2
3
4
#include <migraphx/program.hpp>
#include <migraphx/matcher.hpp>
#include <migraphx/literal.hpp>
Paul's avatar
Paul committed
5
#include <migraphx/functional.hpp>
6
#include <migraphx/par_for.hpp>
7
#include <unordered_set>
Paul's avatar
Paul committed
8

Paul's avatar
Paul committed
9
namespace migraphx {
Paul's avatar
Paul committed
10
inline namespace MIGRAPHX_INLINE_NS {
Paul's avatar
Paul committed
11

Paul's avatar
Paul committed
12
bool skip_propogate(instruction_ref ins)
Paul's avatar
Paul committed
13
{
Paul's avatar
Paul committed
14
    if(ins->name() == "contiguous")
Paul's avatar
Paul committed
15
        return skip_propogate(ins->inputs().front());
Paul's avatar
Paul committed
16
17
    auto&& s = ins->get_shape();
    if(s.broadcasted() and not s.scalar())
Paul's avatar
Paul committed
18
        return true;
Paul's avatar
Paul committed
19
    if(s.scalar() and s.elements() != 1)
Paul's avatar
Paul committed
20
21
22
        return true;
    return false;
}
Paul's avatar
Paul committed
23

24
25
bool is_const(instruction_ref ins) { return ins->can_eval() and not skip_propogate(ins); }

26
void propagate_constant::apply(module& m) const
Paul's avatar
Paul committed
27
{
28
29
30
31
    std::unordered_set<instruction_ref> const_instrs;
    auto last = std::prev(m.end());

    // Find instructions that can be evaluated to a literal
32
    for(auto i : iterator_for(m))
33
    {
34
        if(is_const(i) and i != last)
35
            continue;
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59

        std::copy_if(
            i->inputs().begin(),
            i->inputs().end(),
            std::inserter(const_instrs, const_instrs.begin()),
            [&](const instruction_ref ins) { return is_const(ins) and ins->name() != "@literal"; });
    }

    // Compute literals in parallel
    std::vector<instruction_ref> const_instrs_vec{const_instrs.begin(), const_instrs.end()};
    std::vector<argument> literals(const_instrs_vec.size());
    par_for(const_instrs_vec.size(), 1, [&](const auto i) {
        literals[i] = const_instrs_vec[i]->eval();
    });

    // Replace instructions in m
    for(size_t i = 0; i < const_instrs_vec.size(); i++)
    {
        if(not literals[i].empty())
        {
            assert(literals[i].get_shape() == const_instrs_vec[i]->get_shape());
            auto l = m.add_literal(literals[i].get_shape(), literals[i].data());
            m.replace_instruction(const_instrs_vec[i], l);
        }
60
    }
Paul's avatar
Paul committed
61
}
Paul's avatar
Paul committed
62

Paul's avatar
Paul committed
63
} // namespace MIGRAPHX_INLINE_NS
Paul's avatar
Paul committed
64
} // namespace migraphx