main.cpp 17.3 KB
Newer Older
Paul's avatar
Paul committed
1
2
#include "argument_parser.hpp"
#include "command.hpp"
Paul's avatar
Paul committed
3
#include "verify.hpp"
Paul's avatar
Paul committed
4
#include "perf.hpp"
5
#include "models.hpp"
6
#include "marker_roctx.hpp"
Paul's avatar
Paul committed
7

Paul's avatar
Paul committed
8
9
10
#include <migraphx/tf.hpp>
#include <migraphx/onnx.hpp>
#include <migraphx/stringutils.hpp>
11
12
#include <migraphx/load_save.hpp>
#include <migraphx/json.hpp>
13
#include <migraphx/version.h>
Paul's avatar
Paul committed
14

15
16
17
#include <migraphx/dead_code_elimination.hpp>
#include <migraphx/eliminate_identity.hpp>
#include <migraphx/eliminate_pad.hpp>
18
19
#include <migraphx/generate.hpp>
#include <migraphx/pass_manager.hpp>
20
#include <migraphx/propagate_constant.hpp>
21
#include <migraphx/quantization.hpp>
22
#include <migraphx/register_op.hpp>
23
#include <migraphx/rewrite_batchnorm.hpp>
24
25
#include <migraphx/simplify_algebra.hpp>
#include <migraphx/simplify_reshapes.hpp>
26
#include <migraphx/register_target.hpp>
27

28
29
#include <fstream>

Paul's avatar
Paul committed
30
31
32
33
34
35
namespace migraphx {
namespace driver {
inline namespace MIGRAPHX_INLINE_NS {

struct loader
{
36
    std::string model;
Paul's avatar
Paul committed
37
    std::string file;
Paul's avatar
Paul committed
38
    std::string file_type;
39
40
41
42
43
    unsigned batch              = 1;
    bool is_nhwc                = true;
    unsigned trim               = 0;
    bool optimize               = false;
    bool skip_unknown_operators = false;
44
45
46
    bool brief                  = false;
    std::string output_type;
    std::string output;
Shucai Xiao's avatar
Shucai Xiao committed
47
    std::vector<std::string> param_dims;
kahmed10's avatar
kahmed10 committed
48
    std::vector<std::string> output_names;
Paul's avatar
Paul committed
49
50
51

    void parse(argument_parser& ap)
    {
Paul's avatar
Paul committed
52
        ap(file, {}, ap.metavar("<input file>"));
53
        ap(model, {"--model"}, ap.help("Load model"), ap.type("resnet50|inceptionv3|alexnet"));
Paul's avatar
Paul committed
54
55
        ap(file_type, {"--onnx"}, ap.help("Load as onnx"), ap.set_value("onnx"));
        ap(file_type, {"--tf"}, ap.help("Load as tensorflow"), ap.set_value("tf"));
56
57
        ap(file_type, {"--migraphx"}, ap.help("Load as MIGraphX"), ap.set_value("migraphx"));
        ap(file_type, {"--migraphx-json"}, ap.help("Load as MIGraphX JSON"), ap.set_value("json"));
58
        ap(batch, {"--batch"}, ap.help("Set batch size for model"));
Paul's avatar
Paul committed
59
        ap(is_nhwc, {"--nhwc"}, ap.help("Treat tensorflow format as nhwc"), ap.set_value(true));
60
61
62
63
        ap(skip_unknown_operators,
           {"--skip-unknown-operators"},
           ap.help("Skip unknown operators when parsing and continue to parse."),
           ap.set_value(true));
Paul's avatar
Paul committed
64
        ap(is_nhwc, {"--nchw"}, ap.help("Treat tensorflow format as nchw"), ap.set_value(false));
Paul's avatar
Paul committed
65
        ap(trim, {"--trim", "-t"}, ap.help("Trim instructions from the end"));
Shucai Xiao's avatar
Shucai Xiao committed
66
67
68
69
70
        ap(param_dims,
           {"--input-dim"},
           ap.help("Dim of a parameter (format: \"@name d1 d2 dn\")"),
           ap.append(),
           ap.nargs(2));
kahmed10's avatar
kahmed10 committed
71
72
73
74
75
76

        ap(output_names,
           {"--output-names"},
           ap.help("Names of node output (format: \"name_1 name_2 name_n\")"),
           ap.append(),
           ap.nargs(2));
77
        ap(optimize, {"--optimize", "-O"}, ap.help("Optimize when reading"), ap.set_value(true));
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
        ap(output_type,
           {"--graphviz", "-g"},
           ap.help("Print out a graphviz representation."),
           ap.set_value("graphviz"));
        ap(brief, {"--brief"}, ap.help("Make the output brief."), ap.set_value(true));
        ap(output_type,
           {"--cpp"},
           ap.help("Print out the program as cpp program."),
           ap.set_value("cpp"));
        ap(output_type, {"--json"}, ap.help("Print out program as json."), ap.set_value("json"));
        ap(output_type,
           {"--text"},
           ap.help("Print out program in text format."),
           ap.set_value("text"));
        ap(output_type,
           {"--binary"},
           ap.help("Print out program in binary format."),
           ap.set_value("binary"));
        ap(output, {"--output", "-o"}, ap.help("Output to file."));
Paul's avatar
Paul committed
97
98
    }

Shucai Xiao's avatar
Shucai Xiao committed
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
    static auto parse_param_dims(const std::vector<std::string>& param_dims_info)
    {
        std::unordered_map<std::string, std::vector<std::size_t>> map_input_dims;
        std::string name = "";
        for(auto&& x : param_dims_info)
        {
            if(x[0] == '@')
            {
                name = x.substr(1);
            }
            else
            {
                map_input_dims[name].push_back(value_parser<std::size_t>::apply(x));
            }
        }

        return map_input_dims;
    }

kahmed10's avatar
kahmed10 committed
118
119
120
121
122
123
124
125
126
127
128
    static auto parse_output_names(const std::vector<std::string>& output_names_info)
    {
        std::vector<std::string> output_node_names;
        std::transform(output_names_info.begin(),
                       output_names_info.end(),
                       std::back_inserter(output_node_names),
                       [&](auto x) { return value_parser<std::string>::apply(x); });

        return output_node_names;
    }

Paul's avatar
Paul committed
129
    program load()
Paul's avatar
Paul committed
130
131
    {
        program p;
132
        if(model.empty())
Paul's avatar
Paul committed
133
        {
kahmed10's avatar
kahmed10 committed
134
135
            auto map_input_dims    = parse_param_dims(param_dims);
            auto output_node_names = parse_output_names(output_names);
136
137
138
139
140
141
            if(file_type.empty())
            {
                if(ends_with(file, ".onnx"))
                    file_type = "onnx";
                else if(ends_with(file, ".pb"))
                    file_type = "tf";
142
143
144
145
                else if(ends_with(file, ".json"))
                    file_type = "json";
                else
                    file_type = "migraphx";
146
147
148
            }
            std::cout << "Reading: " << file << std::endl;
            if(file_type == "onnx")
149
150
151
152
153
            {
                onnx_options options;
                options.default_dim_value      = batch;
                options.skip_unknown_operators = skip_unknown_operators;
                options.print_program_on_error = true;
Shucai Xiao's avatar
Shucai Xiao committed
154
                options.map_input_dims         = map_input_dims;
155
156
                p                              = parse_onnx(file, options);
            }
157
            else if(file_type == "tf")
158
            {
kahmed10's avatar
kahmed10 committed
159
                p = parse_tf(file, tf_options{is_nhwc, batch, map_input_dims, output_node_names});
160
            }
161
162
163
164
165
166
167
168
169
170
            else if(file_type == "json")
            {
                file_options options;
                options.format = "json";
                p              = migraphx::load(file, options);
            }
            else if(file_type == "migraphx")
            {
                p = migraphx::load(file);
            }
171
172
173
174
175
176
177
178
179
180
181
        }
        else
        {
            if(model == "resnet50")
                p = resnet50(batch);
            else if(model == "inceptionv3")
                p = inceptionv3(batch);
            else if(model == "alexnet")
                p = alexnet(batch);
            else
                MIGRAPHX_THROW("Unknown model: " + model);
Paul's avatar
Paul committed
182
        }
Paul's avatar
Paul committed
183
        if(trim > 0)
Paul's avatar
Paul committed
184
        {
185
            auto* mm  = p.get_main_module();
Shucai Xiao's avatar
Shucai Xiao committed
186
187
            auto last = std::prev(mm->end(), trim);
            mm->remove_instructions(last, mm->end());
Paul's avatar
Paul committed
188
        }
Paul's avatar
Paul committed
189
        if(optimize)
190
191
        {
            migraphx::run_passes(*p.get_main_module(),
Paul's avatar
Paul committed
192
                                 {
193
                                     migraphx::rewrite_batchnorm{},
Paul's avatar
Paul committed
194
195
196
197
198
199
200
201
202
203
204
                                     migraphx::eliminate_identity{},
                                     migraphx::dead_code_elimination{},
                                     migraphx::simplify_algebra{},
                                     migraphx::dead_code_elimination{},
                                     migraphx::simplify_reshapes{},
                                     migraphx::dead_code_elimination{},
                                     migraphx::propagate_constant{},
                                     migraphx::dead_code_elimination{},
                                     migraphx::eliminate_pad{},
                                     migraphx::dead_code_elimination{},
                                 });
205
        }
Paul's avatar
Paul committed
206
207
        return p;
    }
208
209
210
211
212
213

    static void write(std::ostream& os, const std::vector<char>& buffer)
    {
        os.write(buffer.data(), buffer.size());
    }

214
    void save(const program& p) const
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
    {
        auto* os = &std::cout;
        std::ofstream fs;
        if(not output.empty())
        {
            fs.open(output);
            os = &fs;
        }

        std::string type = output_type;
        if(type.empty())
        {
            if(output.empty())
                type = "text";
            else
                type = "binary";
        }

        if(type == "cpp")
            p.print_cpp(*os);
        else if(type == "graphviz")
            p.print_graph(*os, brief);
        else if(type == "text")
            *os << p << std::endl;
        else if(type == "json")
            *os << to_json_string(p.to_value()) << std::endl;
        else if(type == "binary")
            write(*os, save_buffer(p));
    }
Paul's avatar
Paul committed
244
245
};

246
247
248
249
250
251
struct program_params
{
    std::vector<std::string> fill0{};
    std::vector<std::string> fill1{};
    void parse(argument_parser& ap)
    {
Shucai Xiao's avatar
Shucai Xiao committed
252
253
        ap(fill0, {"--fill0"}, ap.help("Fill parameter with 0s"), ap.append(), ap.nargs(2));
        ap(fill1, {"--fill1"}, ap.help("Fill parameter with 1s"), ap.append(), ap.nargs(2));
254
255
    }

256
    auto generate(const program& p, const target& t, bool offload)
257
    {
258
        parameter_map m;
259
260
261
262
        for(auto&& s : fill0)
            m[s] = fill_argument(p.get_parameter_shape(s), 0);
        for(auto&& s : fill1)
            m[s] = fill_argument(p.get_parameter_shape(s), 1);
263
        fill_param_map(m, p, t, offload);
264
265
266
267
        return m;
    }
};

268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
struct compiler_target
{
#ifdef HAVE_GPU
    std::string target_name = "gpu";
#else
    std::string target_name = "cpu";
#endif

    void parse(argument_parser& ap)
    {
        ap(target_name, {"--gpu"}, ap.help("Compile on the gpu"), ap.set_value("gpu"));
        ap(target_name, {"--cpu"}, ap.help("Compile on the cpu"), ap.set_value("cpu"));
        ap(target_name,
           {"--ref"},
           ap.help("Compile on the reference implementation"),
           ap.set_value("ref"));
    }

    target get_target() const { return make_target(target_name); }
};

Paul's avatar
Paul committed
289
290
struct compiler
{
291
292
    static const int q_fp16 = 1;
    static const int q_int8 = 2;
Paul's avatar
Paul committed
293
    loader l;
294
    program_params parameters;
295
    compiler_target ct;
296
    bool offload_copy = false;
kahmed10's avatar
kahmed10 committed
297
    bool fast_math    = true;
298
    int quantize      = 0;
299

kahmed10's avatar
kahmed10 committed
300
    std::vector<std::string> fill0;
Paul's avatar
Paul committed
301
    std::vector<std::string> fill1;
Paul's avatar
Paul committed
302
303
    void parse(argument_parser& ap)
    {
Paul's avatar
Paul committed
304
        l.parse(ap);
305
        parameters.parse(ap);
306
        ct.parse(ap);
307
308
309
        ap(offload_copy,
           {"--enable-offload-copy"},
           ap.help("Enable implicit offload copying"),
310
           ap.set_value(true));
kahmed10's avatar
kahmed10 committed
311
312
313
314
        ap(fast_math,
           {"--disable-fast-math"},
           ap.help("Disable fast math optimization"),
           ap.set_value(false));
315
316
        ap(quantize, {"--fp16"}, ap.help("Quantize for fp16"), ap.set_value(q_fp16));
        ap(quantize, {"--int8"}, ap.help("Quantize for int8"), ap.set_value(q_int8));
Paul's avatar
Paul committed
317
318
    }

319
    auto params(const program& p) { return parameters.generate(p, ct.get_target(), offload_copy); }
320
321
322
323

    program compile()
    {
        auto p = l.load();
324
325
326
        // Dont compile if its already been compiled
        if(p.is_compiled())
            return p;
327
        auto t = ct.get_target();
328
329
330
331
332
333
        if(quantize == q_fp16)
        {
            quantize_fp16(p);
        }
        else if(quantize == q_int8)
        {
334
            quantize_int8(p, t, {params(p)});
335
        }
336
337
        compile_options options;
        options.offload_copy = offload_copy;
kahmed10's avatar
kahmed10 committed
338
        options.fast_math    = fast_math;
339
        p.compile(t, options);
340
        l.save(p);
341
342
        return p;
    }
Paul's avatar
Paul committed
343
344
};

Paul's avatar
Paul committed
345
346
347
struct read : command<read>
{
    loader l;
348
    void parse(argument_parser& ap) { l.parse(ap); }
Paul's avatar
Paul committed
349
350
351
352

    void run()
    {
        auto p = l.load();
353
        l.save(p);
Paul's avatar
Paul committed
354
355
356
    }
};

Paul's avatar
Paul committed
357
358
359
360
361
362
363
364
struct params : command<params>
{
    loader l;
    void parse(argument_parser& ap) { l.parse(ap); }

    void run()
    {
        auto p = l.load();
Paul's avatar
Paul committed
365
        for(auto&& param : p.get_parameter_shapes())
Paul's avatar
Paul committed
366
367
368
369
            std::cout << param.first << ": " << param.second << std::endl;
    }
};

Paul's avatar
Paul committed
370
371
372
struct verify : command<verify>
{
    loader l;
373
    program_params parameters;
374
    compiler_target ct;
Paul's avatar
Paul committed
375
    double tolerance     = 80;
Paul's avatar
Paul committed
376
    bool per_instruction = false;
Paul's avatar
Paul committed
377
    bool reduce          = false;
378
    bool offload_copy    = false;
kahmed10's avatar
kahmed10 committed
379
    bool fast_math       = true;
Paul's avatar
Paul committed
380
381
    void parse(argument_parser& ap)
    {
Paul's avatar
Paul committed
382
        l.parse(ap);
383
        parameters.parse(ap);
384
        ct.parse(ap);
385
386
387
388
        ap(offload_copy,
           {"--enable-offload-copy"},
           ap.help("Enable implicit offload copying"),
           ap.set_value(true));
kahmed10's avatar
kahmed10 committed
389
390
391
392
        ap(fast_math,
           {"--disable-fast-math"},
           ap.help("Disable fast math optimization"),
           ap.set_value(false));
Paul's avatar
Paul committed
393
394
        ap(tolerance, {"--tolerance"}, ap.help("Tolerance for errors"));
        ap(per_instruction,
Paul's avatar
Paul committed
395
396
397
398
           {"-i", "--per-instruction"},
           ap.help("Verify each instruction"),
           ap.set_value(true));
        ap(reduce, {"-r", "--reduce"}, ap.help("Reduce program and verify"), ap.set_value(true));
Paul's avatar
Paul committed
399
400
401
402
403
    }

    void run()
    {
        auto p = l.load();
404
        l.save(p);
Paul's avatar
Paul committed
405
406
        std::cout << p << std::endl;

407
408
        compile_options options;
        options.offload_copy = offload_copy;
kahmed10's avatar
kahmed10 committed
409
        options.fast_math    = fast_math;
410
411
        auto t               = ct.get_target();
        auto m               = parameters.generate(p, t, true);
412

Paul's avatar
Paul committed
413
414
        if(per_instruction)
        {
415
            verify_instructions(p, t, options, tolerance);
Paul's avatar
Paul committed
416
417
418
        }
        else if(reduce)
        {
419
            verify_reduced_program(p, t, options, m, tolerance);
Paul's avatar
Paul committed
420
421
422
        }
        else
        {
423
            verify_program(l.file, p, t, options, m, tolerance);
Paul's avatar
Paul committed
424
425
426
427
        }
    }
};

428
429
430
431
432
433
434
435
436
437
struct version : command<version>
{
    void parse(const argument_parser&) {}
    void run() const
    {
        std::cout << "MIGraphX Version: " << MIGRAPHX_VERSION_MAJOR << "." << MIGRAPHX_VERSION_MINOR
                  << std::endl;
    }
};

Paul's avatar
Paul committed
438
439
440
struct compile : command<compile>
{
    compiler c;
Paul's avatar
Paul committed
441
    void parse(argument_parser& ap) { c.parse(ap); }
Paul's avatar
Paul committed
442
443
444
445

    void run()
    {
        std::cout << "Compiling ... " << std::endl;
446
        c.compile();
Paul's avatar
Paul committed
447
448
449
450
451
452
    }
};

struct run_cmd : command<run_cmd>
{
    compiler c;
Paul's avatar
Paul committed
453
    void parse(argument_parser& ap) { c.parse(ap); }
Paul's avatar
Paul committed
454
455
456
457
458
459
460

    void run()
    {
        std::cout << "Compiling ... " << std::endl;
        auto p = c.compile();
        std::cout << "Allocating params ... " << std::endl;
        auto m = c.params(p);
Paul's avatar
Paul committed
461
        p.eval(m);
Paul's avatar
Paul committed
462
463
464
465
        std::cout << p << std::endl;
    }
};

Paul's avatar
Paul committed
466
467
468
469
struct perf : command<perf>
{
    compiler c;
    unsigned n = 100;
Paul's avatar
Paul committed
470
471
    void parse(argument_parser& ap)
    {
Paul's avatar
Paul committed
472
473
474
475
476
477
478
479
480
481
482
483
484
        c.parse(ap);
        ap(n, {"--iterations", "-n"}, ap.help("Number of iterations to run for perf report"));
    }

    void run()
    {
        std::cout << "Compiling ... " << std::endl;
        auto p = c.compile();
        std::cout << "Allocating params ... " << std::endl;
        auto m = c.params(p);
        std::cout << "Running performance report ... " << std::endl;
        p.perf_report(std::cout, n, m);
    }
485
486
};

487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
struct roctx : command<roctx>
{
    compiler c;
    void parse(argument_parser& ap) { c.parse(ap); }

    void run()
    {
        std::cout << "Compiling ... " << std::endl;
        auto p = c.compile();
        std::cout << "Allocating params ... " << std::endl;
        auto m = c.params(p);
        std::cout << "rocTX:\tLoading rocTX library..." << std::endl;
        auto rtx = create_marker_roctx();
        p.mark(m, std::move(rtx));
    }
};

504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
struct op : command<op>
{
    bool show_ops = false;
    void parse(argument_parser& ap)
    {
        ap(show_ops,
           {"--list", "-l"},
           ap.help("List all the operators of MIGraphX"),
           ap.set_value(true));
    }
    void run() const
    {
        if(show_ops)
        {
            for(const auto& name : get_operators())
                std::cout << name << std::endl;
        }
    }
Paul's avatar
Paul committed
522
523
};

524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
struct onnx : command<onnx>
{
    bool show_ops = false;
    void parse(argument_parser& ap)
    {
        ap(show_ops,
           {"--list", "-l"},
           ap.help("List all onnx operators supported by MIGraphX"),
           ap.set_value(true));
    }
    void run() const
    {
        if(show_ops)
        {
            for(const auto& name : get_onnx_operators())
                std::cout << name << std::endl;
        }
    }
};

Paul's avatar
Paul committed
544
545
546
547
548
struct main_command
{
    static std::string get_command_help()
    {
        std::string result = "Commands:\n";
Paul's avatar
Paul committed
549
550
551
552
        return std::accumulate(get_commands().begin(),
                               get_commands().end(),
                               result,
                               [](auto r, auto&& p) { return r + "    " + p.first + "\n"; });
Paul's avatar
Paul committed
553
    }
Paul's avatar
Paul committed
554
    void parse(argument_parser& ap)
Paul's avatar
Paul committed
555
    {
556
557
        std::string version_str = "MIGraphX Version: " + std::to_string(MIGRAPHX_VERSION_MAJOR) +
                                  "." + std::to_string(MIGRAPHX_VERSION_MINOR);
Paul's avatar
Paul committed
558
        ap(nullptr, {"-h", "--help"}, ap.help("Show help"), ap.show_help(get_command_help()));
559
560
561
562
        ap(nullptr,
           {"-v", "--version"},
           ap.help("Show MIGraphX version"),
           ap.show_help(version_str));
Paul's avatar
Paul committed
563
564
565
566
567
    }

    void run() {}
};

Paul's avatar
Paul committed
568
569
570
571
} // namespace MIGRAPHX_INLINE_NS
} // namespace driver
} // namespace migraphx

Paul's avatar
Paul committed
572
using namespace migraphx::driver; // NOLINT
Paul's avatar
Paul committed
573
574
int main(int argc, const char* argv[])
{
Paul's avatar
Paul committed
575
    std::vector<std::string> args(argv + 1, argv + argc);
Shucai Xiao's avatar
Shucai Xiao committed
576
577

    // no argument, print the help infomration by default
Paul's avatar
Paul committed
578
    if(args.empty())
Shucai Xiao's avatar
Shucai Xiao committed
579
580
581
582
    {
        args.push_back("-h");
    }

Paul's avatar
Paul committed
583
    auto&& m = get_commands();
Paul's avatar
Paul committed
584
    auto cmd = args.front();
Paul's avatar
Paul committed
585
    if(m.count(cmd) > 0)
Paul's avatar
Paul committed
586
    {
Paul's avatar
Paul committed
587
        m.at(cmd)({args.begin() + 1, args.end()});
Paul's avatar
Paul committed
588
    }
Paul's avatar
Paul committed
589
    else
Paul's avatar
Paul committed
590
    {
Paul's avatar
Paul committed
591
        run_command<main_command>(args);
Paul's avatar
Paul committed
592
    }
Shucai Xiao's avatar
Shucai Xiao committed
593

Paul's avatar
Paul committed
594
595
    return 0;
}