program.cpp 13.6 KB
Newer Older
Paul's avatar
Paul committed
1
2
3
#include <migraph/program.hpp>
#include <migraph/stringutils.hpp>
#include <migraph/instruction.hpp>
Paul's avatar
Paul committed
4
#include <migraph/env.hpp>
Paul's avatar
Paul committed
5
#include <migraph/time.hpp>
6
#include <migraph/iterator_for.hpp>
Paul's avatar
Paul committed
7
#include <iostream>
Paul's avatar
Paul committed
8
#include <sstream>
Paul's avatar
Paul committed
9
#include <algorithm>
Paul's avatar
Paul committed
10
#include <utility>
Paul's avatar
Paul committed
11

Paul's avatar
Paul committed
12
namespace migraph {
Paul's avatar
Paul committed
13

Paul's avatar
Paul committed
14
15
MIGRAPH_DECLARE_ENV_VAR(MIGRAPH_TRACE_COMPILE)

Paul's avatar
Paul committed
16
17
18
19
struct program_impl
{
    // A list is used to keep references to an instruction stable
    std::list<instruction> instructions;
Paul's avatar
Paul committed
20
    context ctx;
Paul's avatar
Paul committed
21
22
};

Paul's avatar
Paul committed
23
const operation& get_operation(instruction_ref ins) { return ins->op; }
Paul's avatar
Paul committed
24

Paul's avatar
Paul committed
25
template <class F>
Paul's avatar
Paul committed
26
27
static void print_program(std::ostream& os, const program& p, F annonate)
{
28
    std::unordered_map<instruction_ref, std::string> names;
Paul's avatar
Paul committed
29
30
    int count = 0;

31
    for(auto ins : iterator_for(p))
Paul's avatar
Paul committed
32
33
    {
        std::string var_name = "@" + std::to_string(count);
34
        if(ins->op.name() == "@param")
Paul's avatar
Paul committed
35
        {
36
            var_name = any_cast<builtin::param>(ins->op).parameter;
Paul's avatar
Paul committed
37
38
39
40
        }

        os << var_name << " = ";

41
        os << ins->op;
Paul's avatar
Paul committed
42

43
        if(ins->op.name() == "@literal")
Paul's avatar
Paul committed
44
        {
45
            if(ins->lit.get_shape().elements() > 10)
Paul's avatar
Paul committed
46
47
                os << "{ ... }";
            else
48
                os << "{" << ins->lit << "}";
Paul's avatar
Paul committed
49
50
        }

51
        if(!ins->arguments.empty())
Paul's avatar
Paul committed
52
53
        {
            char delim = '(';
54
            for(auto&& arg : ins->arguments)
Paul's avatar
Paul committed
55
56
            {
                assert(p.has_instruction(arg) && "Instruction not found");
57
                os << delim << names.at(arg);
Paul's avatar
Paul committed
58
59
60
61
62
                delim = ',';
            }
            os << ")";
        }

63
        os << " -> " << ins->result;
Paul's avatar
Paul committed
64

Paul's avatar
Paul committed
65
        annonate(ins, names);
Paul's avatar
Paul committed
66
67
68

        os << std::endl;

69
        names.emplace(ins, var_name);
Paul's avatar
Paul committed
70
71
72
73
        count++;
    }
}

Paul's avatar
Paul committed
74
program::program() : impl(std::make_unique<program_impl>()) {}
Paul's avatar
Paul committed
75

Paul's avatar
Paul committed
76
program::program(program&&) noexcept = default;
Paul's avatar
Paul committed
77
78
program& program::operator=(program&&) noexcept = default;
program::~program() noexcept                    = default;
Paul's avatar
Paul committed
79

Paul's avatar
Paul committed
80
instruction_ref program::add_instruction(const operation& op, std::vector<instruction_ref> args)
Paul's avatar
Paul committed
81
{
Paul's avatar
Paul committed
82
    return insert_instruction(impl->instructions.end(), op, std::move(args));
Paul's avatar
Paul committed
83
}
Paul's avatar
Paul committed
84
85
86
instruction_ref program::insert_instruction(instruction_ref ins,
                                            const operation& op,
                                            std::vector<instruction_ref> args)
Paul's avatar
Paul committed
87
{
Paul's avatar
Paul committed
88
89
90
    assert(std::all_of(
               args.begin(), args.end(), [&](instruction_ref x) { return has_instruction(x); }) &&
           "Argument is not an exisiting instruction");
Paul's avatar
Paul committed
91
    assert(not starts_with(op.name(), "@"));
Paul's avatar
Paul committed
92
93
    // TODO: Use move
    shape r     = compute_shape(op, args);
Paul's avatar
Paul committed
94
    auto result = impl->instructions.insert(ins, {op, r, std::move(args)});
Paul's avatar
Paul committed
95
    backreference(result);
Paul's avatar
Paul committed
96
    // assert(result->arguments == args);
Paul's avatar
Paul committed
97
    assert(result->valid(begin()));
Paul's avatar
Paul committed
98
    return result;
Paul's avatar
Paul committed
99
100
}

Paul's avatar
Paul committed
101
102
103
instruction_ref program::replace_instruction(instruction_ref ins,
                                             const operation& op,
                                             std::vector<instruction_ref> args)
Paul's avatar
Paul committed
104
105
106
107
{
    assert(std::all_of(
               args.begin(), args.end(), [&](instruction_ref x) { return has_instruction(x); }) &&
           "Argument is not an exisiting instruction");
Paul's avatar
Paul committed
108
    assert(not starts_with(op.name(), "@"));
Paul's avatar
Paul committed
109

Paul's avatar
Paul committed
110
    shape r = compute_shape(op, args);
Paul's avatar
Paul committed
111
    ins->replace(op, r, std::move(args));
Paul's avatar
Paul committed
112
    backreference(ins);
Paul's avatar
Paul committed
113
    assert(ins->valid(begin()));
Paul's avatar
Paul committed
114
115
116
    return ins;
}

Paul's avatar
Paul committed
117
instruction_ref program::replace_instruction(instruction_ref ins, instruction_ref rep)
Paul's avatar
Paul committed
118
{
Paul's avatar
Paul committed
119
120
121
122
    assert(has_instruction(ins));
    assert(has_instruction(rep));
    assert(ins != rep);
    // TODO: Should it be an error if the output is empty?
Paul's avatar
Paul committed
123
    if(ins->output.empty())
Paul's avatar
Paul committed
124
125
126
    {
        return rep;
    }
Paul's avatar
Paul committed
127
    for(auto&& out : ins->output)
Paul's avatar
Paul committed
128
    {
Paul's avatar
Paul committed
129
130
        // TODO: Check for possible cycles
        if(out != rep)
Paul's avatar
Paul committed
131
        {
Paul's avatar
Paul committed
132
            replace_argument(out, ins, rep);
Paul's avatar
Paul committed
133
        }
Paul's avatar
Paul committed
134
        assert(out->valid(begin()));
Paul's avatar
Paul committed
135
    }
Paul's avatar
Paul committed
136
137
    // Replacement should not be dead code unless its the last instruction
    assert(!rep->output.empty() or rep == std::prev(end()));
Paul's avatar
Paul committed
138
    assert(ins->valid(begin()));
Paul's avatar
Paul committed
139
    assert(rep->valid(begin()));
Paul's avatar
Paul committed
140
141
142
    return rep;
}

Paul's avatar
Paul committed
143
instruction_ref program::remove_instruction(instruction_ref ins)
Paul's avatar
Paul committed
144
145
146
147
148
149
150
{
    assert(has_instruction(ins));
    assert(ins->output.empty());
    ins->clear_arguments();
    return impl->instructions.erase(ins);
}

151
152
instruction_ref program::remove_instructions(instruction_ref first, instruction_ref last)
{
Paul's avatar
Paul committed
153
154
    if(first == last)
        return first;
Paul's avatar
Paul committed
155
    // TODO: Check every element
156
    assert(has_instruction(first));
Paul's avatar
Paul committed
157
158
    std::for_each(first, last, [&](instruction& ins) { ins.clear_arguments(); });
    assert(std::all_of(first, last, [&](instruction& ins) { return ins.output.empty(); }));
159
160
161
162
163
164
165
166
167
    return impl->instructions.erase(first, last);
}

instruction_ref program::move_instruction(instruction_ref src, instruction_ref dst)
{
    impl->instructions.splice(dst, impl->instructions, src);
    return src;
}

Paul's avatar
Paul committed
168
instruction_ref program::add_literal(literal l)
Paul's avatar
Paul committed
169
{
Paul's avatar
Paul committed
170
171
172
173
    impl->instructions.emplace_front(std::move(l));
    return impl->instructions.begin();
}

Paul's avatar
Paul committed
174
instruction_ref program::add_outline(const shape& s)
Paul's avatar
Paul committed
175
176
177
{
    impl->instructions.push_front({builtin::outline{s}, s, {}});
    return impl->instructions.begin();
Paul's avatar
Paul committed
178
179
}

Paul's avatar
Paul committed
180
instruction_ref program::add_parameter(std::string name, shape s)
Paul's avatar
Paul committed
181
{
182
    assert(get_parameter_shape(name) == shape{});
Paul's avatar
Paul committed
183
    impl->instructions.push_front({builtin::param{std::move(name)}, std::move(s), {}});
Paul's avatar
Paul committed
184
185
186
    return impl->instructions.begin();
}

Paul's avatar
Paul committed
187
shape program::get_parameter_shape(std::string name) const
Paul's avatar
Paul committed
188
189
{
    auto ins = std::find_if(
Paul's avatar
Paul committed
190
191
192
193
194
195
196
197
198
199
200
201
202
203
        impl->instructions.begin(), impl->instructions.end(), [&](const instruction& x) {
            if(x.op.name() == "@param")
            {
                return any_cast<builtin::param>(x.op).parameter == name;
            }
            else
            {
                return false;
            }
        });
    if(ins != this->end())
        return ins->result;
    else
        return {};
Paul's avatar
Paul committed
204
205
}

Paul's avatar
Paul committed
206
207
208
std::unordered_map<std::string, shape> program::get_parameter_shapes() const
{
    std::unordered_map<std::string, shape> result;
Paul's avatar
Paul committed
209
    for(auto&& ins : impl->instructions)
Paul's avatar
Paul committed
210
211
212
    {
        if(ins.op.name() == "@param")
        {
Paul's avatar
Paul committed
213
            auto&& name  = any_cast<builtin::param>(ins.op).parameter;
Paul's avatar
Paul committed
214
215
216
217
218
219
            result[name] = ins.result;
        }
    }
    return result;
}

Paul's avatar
Paul committed
220
bool program::has_instruction(instruction_ref ins) const
Paul's avatar
Paul committed
221
{
Paul's avatar
Paul committed
222
223
224
225
    return std::find_if(
               impl->instructions.begin(), impl->instructions.end(), [&](const instruction& x) {
                   return std::addressof(*ins) == std::addressof(x);
               }) != impl->instructions.end();
Paul's avatar
Paul committed
226
227
}

Paul's avatar
Paul committed
228
std::size_t program::size() const { return impl->instructions.size(); }
Paul's avatar
Paul committed
229
230
instruction_ref program::begin() const { return impl->instructions.begin(); }
instruction_ref program::end() const { return impl->instructions.end(); }
231

Paul's avatar
Paul committed
232
shape program::get_shape() const { return impl->instructions.back().result; }
Paul's avatar
Paul committed
233

Paul's avatar
Paul committed
234
235
instruction_ref program::validate() const
{
Paul's avatar
Paul committed
236
237
    return std::find_if(impl->instructions.begin(),
                        impl->instructions.end(),
Paul's avatar
Paul committed
238
                        [&](const instruction& i) { return !i.valid(impl->instructions.begin()); });
Paul's avatar
Paul committed
239
240
}

Paul's avatar
Paul committed
241
void program::compile(const target& t, tracer trace)
Paul's avatar
Paul committed
242
{
Paul's avatar
Paul committed
243
    assert(this->validate() == impl->instructions.end());
Paul's avatar
Paul committed
244
    this->impl->ctx = t.get_context();
Paul's avatar
Paul committed
245
246
247
248
    if(not trace.enabled() and enabled(MIGRAPH_TRACE_COMPILE{}))
        trace = tracer{std::cout};
    trace(*this);
    trace();
Paul's avatar
Paul committed
249
    for(auto&& p : t.get_passes(this->impl->ctx))
Paul's avatar
Paul committed
250
    {
Paul's avatar
Paul committed
251
        trace("Pass: ", p.name());
Paul's avatar
Paul committed
252
        p.apply(*this);
Paul's avatar
Paul committed
253
        trace(*this);
Paul's avatar
Paul committed
254
#ifndef NDEBUG
Paul's avatar
Paul committed
255
        trace("Validate ...");
Paul's avatar
Paul committed
256
        auto invalid = this->validate();
Paul's avatar
Paul committed
257
258
        if(invalid != impl->instructions.end())
        {
Paul's avatar
Paul committed
259
            auto index = std::distance(impl->instructions.begin(), invalid);
Paul's avatar
Paul committed
260
            MIGRAPH_THROW(p.name() + " pass produces invalid program at instruction " +
Paul's avatar
Paul committed
261
                          std::to_string(index) + ": " + invalid->op.name());
Paul's avatar
Paul committed
262
        }
Paul's avatar
Paul committed
263
        trace();
Paul's avatar
Paul committed
264
265
#endif
    }
Paul's avatar
Paul committed
266
    auto invalid = this->validate();
Paul's avatar
Paul committed
267
268
    if(invalid != impl->instructions.end())
    {
Paul's avatar
Paul committed
269
270
271
        auto index = std::distance(impl->instructions.begin(), invalid);
        MIGRAPH_THROW("Invalid program from compilation at instruction " + std::to_string(index));
    }
Paul's avatar
Paul committed
272
273
}

Paul's avatar
Paul committed
274
275
276
277
278
template <class F>
argument generic_eval(const program& p,
                      context& ctx,
                      std::unordered_map<std::string, argument> params,
                      F trace)
Paul's avatar
Paul committed
279
{
Paul's avatar
Paul committed
280
    assert(p.validate() == p.end());
281
    std::unordered_map<instruction_ref, argument> results;
Paul's avatar
Paul committed
282
    results.reserve(p.size() * 2);
Paul's avatar
Paul committed
283
284
    std::vector<argument> values;
    values.reserve(16);
285
    for(auto ins : iterator_for(p))
Paul's avatar
Paul committed
286
    {
287
        if(ins->op.name() == "@literal")
Paul's avatar
Paul committed
288
        {
289
            results.emplace(ins, trace(ins, [&] { return ins->lit.get_argument(); }));
Paul's avatar
Paul committed
290
        }
291
        else if(ins->op.name() == "@param")
Paul's avatar
Paul committed
292
        {
Paul's avatar
Paul committed
293
294
295
            results.emplace(ins, trace(ins, [&] {
                                return params.at(any_cast<builtin::param>(ins->op).parameter);
                            }));
Paul's avatar
Paul committed
296
        }
297
        else if(ins->op.name() == "@outline")
Paul's avatar
Paul committed
298
        {
299
            results.emplace(ins, trace(ins, [&] { return argument{ins->result, nullptr}; }));
Paul's avatar
Paul committed
300
        }
Paul's avatar
Paul committed
301
302
        else
        {
303
304
305
            values.resize(ins->arguments.size());
            std::transform(ins->arguments.begin(),
                           ins->arguments.end(),
Paul's avatar
Paul committed
306
                           values.begin(),
307
                           [&](instruction_ref i) {
Paul's avatar
Paul committed
308
309
310
311
312
                               assert(results.find(i) != results.end());
                               return results[i];
                           });
            results.emplace(ins,
                            trace(ins, [&] { return ins->op.compute(ctx, ins->result, values); }));
Paul's avatar
Paul committed
313
        }
314
        assert(results.find(ins) != results.end());
Paul's avatar
Paul committed
315
    }
316
    return results.at(std::prev(p.end()));
Paul's avatar
Paul committed
317
318
}

Paul's avatar
Paul committed
319
320
argument program::eval(std::unordered_map<std::string, argument> params) const
{
Paul's avatar
Paul committed
321
322
    return generic_eval(
        *this, this->impl->ctx, std::move(params), [](auto&, auto f) { return f(); });
Paul's avatar
Paul committed
323
324
}

Paul's avatar
Paul committed
325
326
327
double common_average(const std::vector<double>& v)
{
    std::size_t n = v.size() / 4;
Paul's avatar
Paul committed
328
329
    double total  = std::accumulate(v.begin() + n, v.end() - n, 0.0);
    return total / std::distance(v.begin() + n, v.end() - n);
Paul's avatar
Paul committed
330
331
}

Paul's avatar
Paul committed
332
333
334
void program::perf_report(std::ostream& os, std::size_t n, parameter_map params) const
{
    using milliseconds = std::chrono::duration<double, std::milli>;
Paul's avatar
Paul committed
335
    auto& ctx          = this->impl->ctx;
Paul's avatar
Paul committed
336
337
    // Run once by itself
    eval(params);
Paul's avatar
Paul committed
338
    ctx.finish();
Paul's avatar
Paul committed
339
    // Run and time entire program
Paul's avatar
Paul committed
340
341
    std::vector<double> total_vec;
    total_vec.reserve(n);
Paul's avatar
Paul committed
342
    for(std::size_t i = 0; i < n; i++)
Paul's avatar
Paul committed
343
    {
Paul's avatar
Paul committed
344
345
346
347
        total_vec.push_back(time<milliseconds>([&] {
            eval(params);
            ctx.finish();
        }));
Paul's avatar
Paul committed
348
    }
Paul's avatar
Paul committed
349
350
    std::sort(total_vec.begin(), total_vec.end());
    std::unordered_map<instruction_ref, std::vector<double>> ins_vec;
Paul's avatar
Paul committed
351
    // Fill the map
Paul's avatar
Paul committed
352
    generic_eval(*this, ctx, params, [&](auto ins, auto) {
Paul's avatar
Paul committed
353
        ins_vec[ins].reserve(n);
Paul's avatar
Paul committed
354
355
        return argument{};
    });
Paul's avatar
Paul committed
356
    // Run and time each instruction
Paul's avatar
Paul committed
357
    for(std::size_t i = 0; i < n; i++)
Paul's avatar
Paul committed
358
    {
Paul's avatar
Paul committed
359
        generic_eval(*this, ctx, params, [&](auto ins, auto f) {
360
            argument result;
Paul's avatar
Paul committed
361
362
363
364
            ins_vec[ins].push_back(time<milliseconds>([&] {
                result = f();
                ctx.finish();
            }));
365
            return result;
Paul's avatar
Paul committed
366
367
        });
    }
Paul's avatar
Paul committed
368
369
    for(auto&& p : ins_vec)
        std::sort(p.second.begin(), p.second.end());
Paul's avatar
Paul committed
370
    // Run and time implicit overhead
Paul's avatar
Paul committed
371
372
    std::vector<double> overhead_vec;
    overhead_vec.reserve(n);
Paul's avatar
Paul committed
373
    for(std::size_t i = 0; i < n; i++)
Paul's avatar
Paul committed
374
    {
Paul's avatar
Paul committed
375
376
        overhead_vec.push_back(time<milliseconds>(
            [&] { generic_eval(*this, ctx, params, [](auto...) { return argument{}; }); }));
Paul's avatar
Paul committed
377
378
    }

Paul's avatar
Paul committed
379
    double total_time             = common_average(total_vec);
Paul's avatar
Paul committed
380
    double rate                   = std::ceil(1000.0 / total_time);
Paul's avatar
Paul committed
381
    double overhead_time          = common_average(overhead_vec);
Paul's avatar
Paul committed
382
    double overhead_percent       = overhead_time * 100.0 / total_time;
Paul's avatar
Paul committed
383
    double total_instruction_time = 0.0;
Paul's avatar
Paul committed
384
    std::unordered_map<std::string, double> op_times;
Paul's avatar
Paul committed
385
    for(auto&& p : ins_vec)
Paul's avatar
Paul committed
386
387
388
389
390
    {
        double avg = common_average(p.second);
        op_times[p.first->op.name()] += avg;
        total_instruction_time += avg;
    }
Paul's avatar
Paul committed
391
392
    double calculate_overhead_time    = total_time - total_instruction_time;
    double calculate_overhead_percent = calculate_overhead_time * 100.0 / total_time;
Paul's avatar
Paul committed
393

Paul's avatar
Paul committed
394
395
396
397
398
    print_program(os, *this, [&](auto ins, auto&&) {
        double avg     = common_average(ins_vec[ins]);
        double percent = std::ceil(100.0 * avg / total_instruction_time);
        os << ": " << avg << "ms, " << percent << "%";
    });
Paul's avatar
Paul committed
399
400
401

    os << std::endl;
    os << "Summary:" << std::endl;
Paul's avatar
Paul committed
402
    for(auto&& p : op_times)
Paul's avatar
Paul committed
403
    {
Paul's avatar
Paul committed
404
405
        auto&& name    = p.first;
        double avg     = p.second;
Paul's avatar
Paul committed
406
407
408
409
410
        double percent = std::ceil(100.0 * avg / total_instruction_time);
        os << name << ": " << avg << "ms, " << percent << "%" << std::endl;
    }

    os << std::endl;
Paul's avatar
Paul committed
411

Paul's avatar
Paul committed
412
    os << "Rate: " << rate << "/sec" << std::endl;
Paul's avatar
Paul committed
413
414
    os << "Total time: " << total_time << "ms" << std::endl;
    os << "Total instructions time: " << total_instruction_time << "ms" << std::endl;
Paul's avatar
Paul committed
415
416
417
418
    os << "Overhead time: " << overhead_time << "ms"
       << ", " << calculate_overhead_time << "ms" << std::endl;
    os << "Overhead: " << std::round(overhead_percent) << "%"
       << ", " << std::round(calculate_overhead_percent) << "%" << std::endl;
Paul's avatar
Paul committed
419
420
}

Paul's avatar
Paul committed
421
bool operator==(const program& x, const program& y) { return to_string(x) == to_string(y); }
Paul's avatar
Paul committed
422

Paul's avatar
Paul committed
423
std::ostream& operator<<(std::ostream& os, const program& p)
Paul's avatar
Paul committed
424
{
Paul's avatar
Paul committed
425
    print_program(os, p, [](auto&&...) {});
Paul's avatar
Paul committed
426
    return os;
Paul's avatar
Paul committed
427
}
Paul's avatar
Paul committed
428
} // namespace migraph