"tests/vscode:/vscode.git/clone" did not exist on "686f5e321096f3a843a23a89fa4a3f28e586c26f"
mlir.cpp 33.8 KB
Newer Older
Paul Fultz II's avatar
Paul Fultz II committed
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.
 */
24
#include "migraphx/make_op.hpp"
25
#include <migraphx/stringutils.hpp>
Paul Fultz II's avatar
Paul Fultz II committed
26
27
28
29
30
31
32
33
#include <migraphx/gpu/mlir.hpp>

#ifdef MIGRAPHX_MLIR
#include <mlir-c/IR.h>
#include <mlir-c/BuiltinAttributes.h>
#include <mlir-c/BuiltinTypes.h>
#include <mlir-c/Diagnostics.h>
#include <mlir-c/Dialect/MIGraphX.h>
34
#include <mlir-c/Dialect/Rock.h>
Paul Fultz II's avatar
Paul Fultz II committed
35
36
#include <mlir-c/IntegerSet.h>
#include <mlir-c/Pass.h>
37
38
39
#include <mutex>
#if !defined(MLIR_MIGRAPHX_DIALECT_API_VERSION) || MLIR_MIGRAPHX_DIALECT_API_VERSION != 3
#warning "Incompatible version of rocMLIR library used, disabling"
40
41
// Only undefine when not using cppcheck
#ifndef CPPCHECK
42
#undef MIGRAPHX_MLIR
43
#endif
44
45
46
#else
#include <mlir-c/RegisterRocMLIR.h>
#endif
Paul Fultz II's avatar
Paul Fultz II committed
47
48
49
50
51
52
53
54
55
56
#endif

#include <migraphx/env.hpp>
#include <migraphx/manage_ptr.hpp>
#include <migraphx/module.hpp>
#include <migraphx/instruction.hpp>
#include <migraphx/config.hpp>
#include <migraphx/ranges.hpp>
#include <migraphx/gpu/code_object_op.hpp>
#include <migraphx/gpu/context.hpp>
57
#include <migraphx/gpu/compile_gen.hpp>
Paul Fultz II's avatar
Paul Fultz II committed
58
#include <migraphx/gpu/device_name.hpp>
59
#include <migraphx/gpu/perfdb.hpp>
Paul Fultz II's avatar
Paul Fultz II committed
60
#include <migraphx/gpu/tuning_config.hpp>
61
62
#include <migraphx/iterator_for.hpp>
#include <migraphx/permutation.hpp>
Paul Fultz II's avatar
Paul Fultz II committed
63
64
#include <deque>
#include <variant>
65
66
#include <fstream>
#include <sstream>
Paul Fultz II's avatar
Paul Fultz II committed
67
68
69
70
71
72

namespace migraphx {
inline namespace MIGRAPHX_INLINE_NS {
namespace gpu {

MIGRAPHX_DECLARE_ENV_VAR(MIGRAPHX_TRACE_MLIR);
73
MIGRAPHX_DECLARE_ENV_VAR(MIGRAPHX_MLIR_TUNE_EXHAUSTIVE);
74
75
MIGRAPHX_DECLARE_ENV_VAR(MIGRAPHX_MLIR_TUNING_DB);
MIGRAPHX_DECLARE_ENV_VAR(MIGRAPHX_MLIR_TUNING_CFG);
Paul Fultz II's avatar
Paul Fultz II committed
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96

#ifdef MIGRAPHX_MLIR
template <class T, class F, F f> // NOLINT
struct mlir_handle
{
    struct ptr
    {
        ptr() = default;
        ptr(std::nullptr_t) {}
        ptr(T x) : obj(x) {}

        std::intptr_t get_value() const
        {
            static_assert(sizeof(T) == sizeof(std::intptr_t), "MLIR Handle different size");
            return reinterpret_cast<const std::intptr_t&>(obj);
        }

        T get() const { return obj; }

        friend bool operator==(ptr x, ptr y) { return x.get_value() == y.get_value(); }

97
        friend bool operator!=(ptr x, ptr y) { return not(x == y); }
98
99

        explicit operator bool() const noexcept { return obj != ptr(); }
Paul Fultz II's avatar
Paul Fultz II committed
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
        T obj{};
    };

    struct deleter
    {
        using pointer = ptr;

        void operator()(pointer x) const
        {
            if(x != nullptr)
            {
                (void)f(x.obj);
            }
        }
    };

    mlir_handle() : handle(nullptr) {}

    mlir_handle(T p) : handle(ptr{p}) {}

120
121
122
123
    T get() const
    {
        return handle.get().get(); // NOLINT(readability-redundant-smartptr-get)
    }
Paul Fultz II's avatar
Paul Fultz II committed
124
125
126
127
128
129
130
131
132

    T release() { return handle.release().get(); }

    private:
    std::unique_ptr<ptr, deleter> handle;
};

#define MIGRAPHX_MANAGE_MLIR_HANDLE(T, F) migraphx::gpu::mlir_handle<T, decltype(&F), &F> // NOLINT

Umang Yadav's avatar
Umang Yadav committed
133
using mlir_context     = MIGRAPHX_MANAGE_MLIR_HANDLE(MlirContext, mlirContextDestroy);
134
135
136
using mlir_thread_pool = MIGRAPHX_MANAGE_MLIR_HANDLE(MlirLlvmThreadPool, mlirLlvmThreadPoolDestroy);
using mlir_dialect_registry  = MIGRAPHX_MANAGE_MLIR_HANDLE(MlirDialectRegistry,
                                                          mlirDialectRegistryDestroy);
Paul Fultz II's avatar
Paul Fultz II committed
137
138
139
140
141
142
143
using mlir_module            = MIGRAPHX_MANAGE_MLIR_HANDLE(MlirModule, mlirModuleDestroy);
using mlir_operation         = MIGRAPHX_MANAGE_MLIR_HANDLE(MlirOperation, mlirOperationDestroy);
using mlir_op_printing_flags = MIGRAPHX_MANAGE_MLIR_HANDLE(MlirOpPrintingFlags,
                                                           mlirOpPrintingFlagsDestroy);
using mlir_region            = MIGRAPHX_MANAGE_MLIR_HANDLE(MlirRegion, mlirRegionDestroy);
using mlir_block             = MIGRAPHX_MANAGE_MLIR_HANDLE(MlirBlock, mlirBlockDestroy);
using mlir_pass_manager      = MIGRAPHX_MANAGE_MLIR_HANDLE(MlirPassManager, mlirPassManagerDestroy);
144
145
using mlir_tuning_table      = MIGRAPHX_MANAGE_MLIR_HANDLE(MlirRockTuningTable,
                                                      mlirRockTuningTableDestroy);
Paul Fultz II's avatar
Paul Fultz II committed
146
147
148
149
using mlir_tuning_space      = MIGRAPHX_MANAGE_MLIR_HANDLE(MlirRockTuningSpace,
                                                      mlirRockTuningSpaceDestroy);
using mlir_tuning_param      = MIGRAPHX_MANAGE_MLIR_HANDLE(MlirRockTuningParam,
                                                      mlirRockTuningParamDestroy);
Paul Fultz II's avatar
Paul Fultz II committed
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185

std::string_view to_string_view(MlirStringRef s) { return {s.data, s.length}; }

MlirStringRef make_mlir_string_ref(const std::string_view& s)
{
    return mlirStringRefCreate(s.data(), s.size());
}

template <class F, class T, class Printer>
void mlir_print(F f, T x, Printer printer)
{
    f(
        x,
        +[](MlirStringRef s, void* data) {
            (*reinterpret_cast<Printer*>(data))(to_string_view(s));
        },
        &printer);
}

template <class F, class T>
void mlir_print(F f, T x, std::ostream& os)
{
    mlir_print(f, x, [&](auto s) { os << s; });
}

template <class F, class T>
std::string mlir_print(F f, T x)
{
    std::stringstream ss;
    mlir_print(f, x, [&](auto s) { ss << s; });
    return ss.str();
}

struct mlir_program
{
    mlir_program()
186
187
        : ctx(mlirContextCreateWithRegistry(get_dialect_registry().get(),
                                            /*threadingEnable=*/false)),
Paul Fultz II's avatar
Paul Fultz II committed
188
189
190
          location(mlirLocationUnknownGet(ctx.get())),
          mmodule(mlirModuleCreateEmpty(location))
    {
191
        mlirContextSetThreadPool(ctx.get(), get_thread_pool().get());
192
        mlirContextLoadAllAvailableDialects(ctx.get());
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
    }

    static mlir_dialect_registry& get_dialect_registry()
    {
        static std::once_flag init_guard;
        static mlir_dialect_registry the_registry;
        // The MLIR registration functions (for dialects and passes) are not
        // necessarily thread-safe and need to be executed exactly once
        // (especially since they eventually call non-thread-safe LLVM
        // initilizations).
        std::call_once(init_guard, [&]() {
            the_registry = mlirDialectRegistryCreate();
            mlirRegisterRocMLIRDialects(the_registry.get());
            mlirRegisterRocMLIRPasses();
        });
        return the_registry;
    }

    static mlir_thread_pool& get_thread_pool()
    {
        // To save on overhead, we create one LLVM thread pool and reuse it
        // across all MLIR contexts as recommended by MLIR upstream.
        // Note that this is thread-safe as of C++11.
        static mlir_thread_pool the_pool = mlirLlvmThreadPoolCreate();
        return the_pool;
Paul Fultz II's avatar
Paul Fultz II committed
218
219
220
221
222
223
224
225
226
227
228
229
230
231
    }

    MlirType make_type(shape::type_t t) const
    {
        MlirType result;
        shape::visit(t, [&](auto as) {
            if(as.type_enum() == shape::float_type)
                result = mlirF32TypeGet(ctx.get());
            else if(as.type_enum() == shape::half_type)
                result = mlirF16TypeGet(ctx.get());
            else if(as.type_enum() == shape::double_type)
                result = mlirF64TypeGet(ctx.get());
            else if(as.is_integral())
            {
232
233
234
235
236
237
238
239
                // Note: rocMLIR use signless integer type for tensors types. This
                // will translate to signed implementation for current supported
                // operations.
                if(as.is_unsigned())
                {
                    MIGRAPHX_THROW("Unsupported type: " + std::to_string(as.type_enum()));
                }
                result = mlirIntegerTypeGet(ctx.get(), as.size() * 8);
Paul Fultz II's avatar
Paul Fultz II committed
240
241
242
243
244
245
246
247
248
            }
            else
                MIGRAPHX_THROW("Unsupported type: " + std::to_string(as.type_enum()));
        });
        return result;
    }

    MlirType make_tensor(const shape& s) const
    {
249
        assert(s.standard());
Paul Fultz II's avatar
Paul Fultz II committed
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
        std::vector<int64_t> lens(s.lens().begin(), s.lens().end());
        return mlirRankedTensorTypeGet(
            lens.size(), lens.data(), make_type(s.type()), mlirAttributeGetNull());
    }

    template <class Range>
    std::vector<MlirType> make_tensors(const Range& r)
    {
        std::vector<MlirType> result;
        std::transform(r.begin(), r.end(), std::back_inserter(result), [&](const auto& s) {
            return make_tensor(s);
        });
        return result;
    }

    MlirType make_function_type(const std::vector<shape>& inputs, const std::vector<shape>& outputs)
    {
        auto in  = make_tensors(inputs);
        auto out = make_tensors(outputs);
        return mlirFunctionTypeGet(ctx.get(), in.size(), in.data(), out.size(), out.data());
    }

    MlirIdentifier id(const std::string_view& s) const
    {
        return mlirIdentifierGet(ctx.get(), make_mlir_string_ref(s));
    }

    MlirAttribute attribute(std::int64_t i) const
    {
        return mlirIntegerAttrGet(mlirIntegerTypeGet(ctx.get(), 64), i);
    }
    MlirAttribute attribute(std::uint64_t i) const
    {
        if(i > (std::numeric_limits<std::uint64_t>::max() / 2))
            MIGRAPHX_THROW("MLIR cant handle large integer values since they are ambiguous");
        return mlirIntegerAttrGet(mlirIntegerTypeGet(ctx.get(), 64), i);
    }
    MlirAttribute attribute(unsigned char i) const { return attribute(std::uint64_t(i)); }
    MlirAttribute attribute(bool b) const { return mlirBoolAttrGet(ctx.get(), b ? 1 : 0); }
    MlirAttribute attribute(double d) const
    {
        return mlirFloatAttrDoubleGet(ctx.get(), mlirF64TypeGet(ctx.get()), d);
    }
    MlirAttribute attribute(const std::string& s) const
    {
        return mlirStringAttrGet(ctx.get(), make_mlir_string_ref(s));
    }
    MlirAttribute attribute(std::nullptr_t) const { return {}; }
    template <class T>
    MlirAttribute attribute(const std::vector<T>& v) const
    {
        std::vector<MlirAttribute> attributes;
        attributes.reserve(v.size());
        std::transform(v.begin(), v.end(), std::back_inserter(attributes), [&](auto&& x) {
            return attribute(x);
        });
        return mlirArrayAttrGet(ctx.get(), attributes.size(), attributes.data());
    }
    MlirAttribute attribute(const value& v) const
    {
        MlirAttribute attr;
        v.visit_value([&](auto&& x) { attr = attribute(x); });
        return attr;
    }
    MlirAttribute attribute(const std::vector<value>& v) const
    {
        if(v.empty())
        {
            return mlirArrayAttrGet(ctx.get(), 0, nullptr);
        }
        if(not v.front().get_key().empty())
        {
            std::vector<MlirNamedAttribute> attributes = name_attributes(v);
            return mlirDictionaryAttrGet(ctx.get(), attributes.size(), attributes.data());
        }
        else
        {
            std::vector<MlirAttribute> attributes;
            attributes.reserve(v.size());
            std::transform(v.begin(), v.end(), std::back_inserter(attributes), [&](auto&& x) {
                return attribute(x);
            });
            return mlirArrayAttrGet(ctx.get(), attributes.size(), attributes.data());
        }
    }

    MlirAttribute attribute(MlirType t) const { return mlirTypeAttrGet(t); }

    MlirAttribute attribute(MlirAttribute a) const { return a; }

    template <class T>
    MlirNamedAttribute name_attribute(const std::string_view& key, const T& x) const
    {
        MlirNamedAttribute attr;
        attr.name      = id(key);
        attr.attribute = attribute(x);
        return attr;
    }

    using attribute_t       = std::variant<std::nullptr_t,
                                     std::uint64_t,
                                     unsigned char,
                                     bool,
                                     double,
                                     std::string,
                                     value,
                                     std::vector<value>,
357
358
                                     MlirType,
                                     MlirAttribute>;
Paul Fultz II's avatar
Paul Fultz II committed
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
392
393
394
395
396
397
398
    using named_attribute_t = std::pair<std::string_view, attribute_t>;

    MlirNamedAttribute name_attribute(const named_attribute_t& na) const
    {
        return name_attribute(na.first,
                              std::visit([&](const auto& x) { return attribute(x); }, na.second));
    }

    std::vector<MlirNamedAttribute>
    name_attributes(const std::vector<named_attribute_t>& named_attrs) const
    {
        std::vector<MlirNamedAttribute> attributes;
        attributes.reserve(named_attrs.size());
        std::transform(named_attrs.begin(),
                       named_attrs.end(),
                       std::back_inserter(attributes),
                       [&](const named_attribute_t& a) { return name_attribute(a); });
        return attributes;
    }

    std::vector<MlirNamedAttribute> name_attributes(const value& v) const
    {
        std::vector<MlirNamedAttribute> attributes;
        attributes.reserve(v.size());
        std::transform(v.begin(), v.end(), std::back_inserter(attributes), [&](const value& x) {
            return name_attribute(x.get_key(), x.without_key());
        });
        return attributes;
    }

    struct mlir_operation_state
    {
        mlir_operation_state(mlir_program& p, const std::string_view& name)
            : prog(&p), op_state(mlirOperationStateGet(make_mlir_string_ref(name), p.location))
        {
        }

        mlir_operation_state& add_attributes(const std::vector<named_attribute_t>& named_attrs)
        {
            auto attributes = prog->name_attributes(named_attrs);
399
400
401
402
            if(not attributes.empty())
            {
                mlirOperationStateAddAttributes(&op_state, attributes.size(), attributes.data());
            }
Paul Fultz II's avatar
Paul Fultz II committed
403
404
405
406
407
408
            return *this;
        }

        mlir_operation_state& add_attribute_value(const value& v)
        {
            auto attributes = prog->name_attributes(v);
409
410
411
412
            if(not attributes.empty())
            {
                mlirOperationStateAddAttributes(&op_state, attributes.size(), attributes.data());
            }
Paul Fultz II's avatar
Paul Fultz II committed
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
            return *this;
        }

        mlir_operation_state& add_regions(std::vector<mlir_region> rs)
        {
            regions = std::move(rs);
            return *this;
        }

        mlir_operation_state& add_region(mlir_region r)
        {
            regions.emplace_back(std::move(r));
            return *this;
        }

        mlir_operation_state& add_results(const std::vector<shape>& outputs)
        {
430
431
432
433
434
            std::vector<shape> reshaped(outputs.size());
            std::transform(outputs.begin(), outputs.end(), reshaped.begin(), [](const shape& r) {
                return shape{r.type(), r.lens()};
            });
            auto x = prog->make_tensors(reshaped);
435
436
437
438
            if(not x.empty())
            {
                mlirOperationStateAddResults(&op_state, x.size(), x.data());
            }
Paul Fultz II's avatar
Paul Fultz II committed
439
440
441
442
443
            return *this;
        }

        mlir_operation_state& add_operands(const std::vector<MlirValue>& inputs)
        {
444
445
446
447
            if(not inputs.empty())
            {
                mlirOperationStateAddOperands(&op_state, inputs.size(), inputs.data());
            }
Paul Fultz II's avatar
Paul Fultz II committed
448
449
450
451
452
453
454
455
456
            return *this;
        }

        mlir_operation create_operation()
        {
            std::vector<MlirRegion> mregions(regions.size());
            std::transform(regions.begin(), regions.end(), mregions.begin(), [](const auto& r) {
                return r.get();
            });
457
458
459
460
            if(not mregions.empty())
            {
                mlirOperationStateAddOwnedRegions(&op_state, mregions.size(), mregions.data());
            }
Paul Fultz II's avatar
Paul Fultz II committed
461
462
463
464
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
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
            mlir_operation op(mlirOperationCreate(&op_state));
            // Release memory since mlir_operation owns it
            for(auto& r : regions)
                r.release();
            regions.clear();
            return op;
        }

        mlir_program* prog;
        MlirOperationState op_state;
        std::vector<mlir_region> regions = {};
    };

    mlir_operation_state create_operation_state(const std::string_view& name)
    {
        return {*this, name};
    }

    std::vector<MlirValue> insert(MlirBlock body, mlir_operation_state ops)
    {
        std::vector<MlirValue> result;
        mlir_operation op = ops.create_operation();
        auto weak_op      = op.get();
        mlirBlockAppendOwnedOperation(body, op.release());

        auto n = mlirOperationGetNumResults(weak_op);
        result.reserve(n);
        transform(range(n), std::back_inserter(result), [&](auto i) {
            return mlirOperationGetResult(weak_op, i);
        });
        return result;
    }

    MlirBlock
    insert(MlirBlock body, const module& m, std::unordered_map<instruction_ref, MlirValue>& ins_map)
    {
        auto names = m.get_parameter_names();
        std::sort(names.begin(), names.end());
        std::vector<shape> inputs;
        std::transform(names.begin(),
                       names.end(),
                       std::back_inserter(inputs),
                       [&](const std::string& name) { return m.get_parameter_shape(name); });
        std::vector<shape> outputs = m.get_output_shapes();

        std::vector<MlirLocation> arg_locs(inputs.size(), location);
        auto body_inputs   = make_tensors(inputs);
        mlir_region region = mlirRegionCreate();
        mlir_block fbody = mlirBlockCreate(body_inputs.size(), body_inputs.data(), arg_locs.data());
        MlirBlock result = fbody.get();
        mlirRegionAppendOwnedBlock(region.get(), fbody.release());

        auto ops = create_operation_state("func.func");
        ops.add_attributes({{"function_type", make_function_type(inputs, outputs)},
515
                            {"sym_name", sym_name},
516
                            {"kernel", std::string("mixr")},
517
518
                            {"arch", target_arch},
                            {"num_cu", num_cu}});
Paul Fultz II's avatar
Paul Fultz II committed
519
520
521
522
523
524
525
526
527
528
529
530
        ops.add_region(std::move(region));
        insert(body, std::move(ops));

        for(auto i : range(names.size()))
            ins_map[m.get_parameter(names[i])] = mlirBlockGetArgument(result, i);
        return result;
    }

    static std::string get_name(instruction_ref ins)
    {
        if(ins->name() == "@return")
            return "func.return";
531
532
533
534
        if(ins->name() == "@literal")
        {
            return "tosa.const";
        }
Paul Fultz II's avatar
Paul Fultz II committed
535
536
537
538
539
540
        return "migraphx." + ins->name();
    }

    static value get_operator_value(const operation& op)
    {
        auto v = op.to_value();
541
        if(op.name() == "convolution" or op.name() == "quant_convolution")
Paul Fultz II's avatar
Paul Fultz II committed
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
        {
            // Adjust symetrical padding
            if(v.at("padding").size() == v.at("stride").size())
            {
                auto padding = v.at("padding");
                std::copy(padding.begin(), padding.end(), std::back_inserter(v.at("padding")));
            }
        }
        return v;
    }

    static shape get_shape(instruction_ref ins)
    {
        if(ins->name() == "@return")
        {
            assert(ins->inputs().size() == 1);
            return ins->inputs().front()->get_shape();
        }
        return ins->get_shape();
    }

563
564
    static std::string get_symbol_name(const module& m)
    {
565
        return "mlir_" + gen::generate_name_from_ops(m);
566
567
    }

Paul Fultz II's avatar
Paul Fultz II committed
568
569
    void parse(const module& m)
    {
570
        sym_name   = get_symbol_name(m);
Paul Fultz II's avatar
Paul Fultz II committed
571
572
573
        auto mbody = mlirModuleGetBody(mmodule.get());
        std::unordered_map<instruction_ref, MlirValue> ins_map;
        auto fbody = insert(mbody, m, ins_map);
574

Paul Fultz II's avatar
Paul Fultz II committed
575
576
577
578
        for(auto ins : iterator_for(m))
        {
            if(ins->name() == "@param")
                continue;
579
580
581
582
583
            if(ins->name() == "contiguous")
            {
                ins_map[ins] = ins_map[ins->inputs().at(0)];
                continue;
            }
Paul Fultz II's avatar
Paul Fultz II committed
584
585
586
587
588
            auto name = get_name(ins);
            auto ops  = create_operation_state(name);
            ops.add_attribute_value(get_operator_value(ins->get_operator()));
            if(ins->name() != "@return")
                ops.add_results({get_shape(ins)});
589
590
591
592
593
594
595
596
            if(ins->name() == "@literal")
            {
                literal r            = ins->get_literal();
                MlirType tensor_type = make_tensor(ins->get_shape());
                MlirAttribute mlir_value_attr =
                    mlirDenseElementsAttrRawBufferGet(tensor_type, r.get_shape().bytes(), r.data());
                ops.add_attributes({{"value", mlir_value_attr}});
            }
597
            if(ins->name() == "convolution" or ins->name() == "dot")
598
599
600
601
            {
                pp =
                    problem_params{ins->get_operator(), to_shapes(ins->inputs()), ins->get_shape()};
            }
Paul Fultz II's avatar
Paul Fultz II committed
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616

            std::vector<MlirValue> inputs;
            transform(
                ins->inputs(), std::back_inserter(inputs), [&](auto i) { return ins_map.at(i); });
            ops.add_operands(inputs);

            auto outputs = insert(fbody, std::move(ops));
            if(ins->name() != "@return")
            {
                assert(outputs.size() == 1);
                ins_map[ins] = outputs.front();
            }
        }
    }

Paul Fultz II's avatar
Paul Fultz II committed
617
    void run_high_level_pipeline() MIGRAPHX_TIDY_CONST
Paul Fultz II's avatar
Paul Fultz II committed
618
    {
619
620
        mlir_pass_manager pm_front{mlirPassManagerCreate(ctx.get())};
        mlirMIGraphXAddHighLevelPipeline(pm_front.get());
621
        mlirPassManagerRunOnOp(pm_front.get(), mlirModuleGetOperation(mmodule.get()));
Paul Fultz II's avatar
Paul Fultz II committed
622
    }
623

Paul Fultz II's avatar
Paul Fultz II committed
624
625
626
    void run_backend_pipeline() MIGRAPHX_TIDY_CONST
    {
        mlir_pass_manager pm_back{mlirPassManagerCreate(ctx.get())};
627
        mlirMIGraphXAddBackendPipeline(pm_back.get(), target_arch.c_str());
628
        mlirPassManagerRunOnOp(pm_back.get(), mlirModuleGetOperation(mmodule.get()));
Paul Fultz II's avatar
Paul Fultz II committed
629
630
631
632
633
634
635
636
637
638
639
640
    }

    code_object_op compile(const value& solution) MIGRAPHX_TIDY_CONST
    {
        // 1st pipeline to call
        run_high_level_pipeline();
        if(solution.is_null())
            get_module_tuned();
        else
            set_tuning(solution);
        // 2nd pipeline to call
        run_backend_pipeline();
Paul Fultz II's avatar
Paul Fultz II committed
641
642

        code_object_op op{};
643
        op.symbol_name                = sym_name;
Paul Fultz II's avatar
Paul Fultz II committed
644
645
646
647
648
        op.code_object                = get_binary();
        std::tie(op.global, op.local) = get_launch_params();
        return op;
    }

649
650
    void set_gpu_properties(const context& migraphx_ctx)
    {
651
        const auto& device = migraphx_ctx.get_current_device();
652
653
        target_arch        = device.get_device_name();
        num_cu             = device.get_cu_count();
654
    }
655

Paul Fultz II's avatar
Paul Fultz II committed
656
657
658
659
660
661
662
663
664
665
666
667
    std::pair<std::size_t, std::size_t> get_launch_params() const
    {
        uint32_t attrs[2];
        // returns block and grid sizes
        mlirGetKernelAttrs(mmodule.get(), attrs);
        std::size_t local  = attrs[0];
        std::size_t global = local * attrs[1];
        return {global, local};
    }

    value::binary get_binary() const
    {
668
        size_t size = 0;
Paul Fultz II's avatar
Paul Fultz II committed
669
670
671
672
673
674
675
        mlirGetBinary(mmodule.get(), &size, nullptr);
        value::binary result(size);
        if(mlirGetBinary(mmodule.get(), &size, reinterpret_cast<char*>(result.data())))
            return result;
        MIGRAPHX_THROW("Failed to compile mlir program");
    }

676
    void set_tuning(const value& v) MIGRAPHX_TIDY_CONST
Paul Fultz II's avatar
Paul Fultz II committed
677
    {
678
679
        const auto* str = v.if_string();
        if(str == nullptr)
680
681
682
            MIGRAPHX_THROW("mlir tuning solutions must be strings");
        if(not mlirRockTuningSetFromStr(mmodule.get(), make_mlir_string_ref(*str)))
            MIGRAPHX_THROW("Failed setting tuning key: " + *str);
Paul Fultz II's avatar
Paul Fultz II committed
683
684
685
686
687
688
    }

    tuning_config get_tuning_config() MIGRAPHX_TIDY_CONST
    {
        tuning_config tc;
        run_high_level_pipeline();
689
690
691
692
        auto tuning_mode = RocmlirTuningParamSetKindFull;
        if(enabled(MIGRAPHX_MLIR_TUNE_EXHAUSTIVE{}))
            tuning_mode = RocmlirTuningParamSetKindExhaustive;
        mlir_tuning_space params{mlirRockTuningSpaceCreate(mmodule.get(), tuning_mode)};
693
        for(auto i : range(mlirRockTuningGetNumParams(params.get())))
Paul Fultz II's avatar
Paul Fultz II committed
694
695
696
697
        {
            mlir_tuning_param param{mlirRockTuningParamCreate()};
            if(not mlirRockTuningParamGet(params.get(), i, param.get()))
                MIGRAPHX_THROW("Incorrect mlir tuning parameter: " + std::to_string(i));
698
699
700
701
702
703
704
            std::array<char, ROCMLIR_TUNING_KEY_BUFSZ> perf_key;
            size_t perf_key_bytes =
                mlirRockTuningParamToString(param.get(), perf_key.data(), perf_key.size());
            if(perf_key_bytes > perf_key.size())
                MIGRAPHX_THROW("Tuning perf key was " + std::to_string(perf_key_bytes) +
                               " bytes and thus too long");
            tc.solutions.emplace_back(perf_key.begin(), perf_key.begin() + perf_key_bytes);
Paul Fultz II's avatar
Paul Fultz II committed
705
        }
706
707
708
709
710
711
712
        std::array<char, ROCMLIR_TUNING_KEY_BUFSZ> tuning_key;
        size_t tuning_key_bytes =
            mlirRockTuningGetKey(mmodule.get(), tuning_key.data(), tuning_key.size());
        if(tuning_key_bytes > tuning_key.size())
            MIGRAPHX_THROW("Tuning table key was " + std::to_string(tuning_key_bytes) +
                           " bytes and thus too long");
        tc.problem = std::string(tuning_key.begin(), tuning_key.begin() + tuning_key_bytes);
Paul Fultz II's avatar
Paul Fultz II committed
713
714
715
        return tc;
    }

716
717
718
719
    std::string get_tune_params(bool xdlops) const { return get_mlir_perf_for_conv(pp, xdlops); }

    // This function appends to tuning cfg file that could be
    // used with rocMLIR tuning scripts.
720
    void dump_tuning_cfg(const std::string& prob_config) const
721
722
    {
        std::string tuning_cfg_path = string_value_of(MIGRAPHX_MLIR_TUNING_CFG{});
723
        if(not tuning_cfg_path.empty())
724
725
        {
            std::vector<std::string> tokens = split_string(prob_config, '\t');
726
727
            std::string prob                = tokens[2];

728
729
730
731
732
733
734
735
736
            if(starts_with(prob, "conv"))
            {
                tuning_cfg_path += ".conv";
            }
            else
            {
                tuning_cfg_path += ".gemm";
            }
            std::ofstream tuning_cfg(tuning_cfg_path, std::ios::app);
737
738
            prob =
                trim(prob, [](unsigned char c) { return (c == '\0') or (std::isspace(c) != 0); });
739
740
741
742
            tuning_cfg << prob << std::endl;
        }
    }

743
    static std::pair<mlir_tuning_table, bool> load_tuning_table()
744
745
    {
        mlir_tuning_table tuning_table{mlirRockTuningTableCreate()};
746
        bool found_table           = false;
747
        std::string tuning_db_path = string_value_of(MIGRAPHX_MLIR_TUNING_DB{});
748
        if(not tuning_db_path.empty())
749
750
751
752
        {
            std::ifstream tuning_db_tsv(tuning_db_path);
            if(tuning_db_tsv)
            {
753
                found_table = true;
754
755
756
757
758
                std::string line;
                while(std::getline(tuning_db_tsv, line))
                {
                    std::vector<std::string> tokens = split_string(line, '\t');
                    std::string arch                = tokens[0];
759
                    std::string num_cu              = tokens[1];
760
761
                    std::string prob                = tokens[2];
                    std::string perf                = tokens[3];
762
                    std::string key = arch.append("\t").append(num_cu).append("\t").append(prob);
763
764
765
766
                    mlirRockTuningUpdateTable(tuning_table.get(),
                                              make_mlir_string_ref(key),
                                              make_mlir_string_ref(perf),
                                              1.0);
767
768
769
770
771
                }
            }
        }
        else
        {
772
            found_table = false;
773
774
775
776
777
            std::cerr
                << "WARNING: MLIR tuning db not found. Please set MIGRAPHX_MLIR_TUNING_DB for "
                   "optimal performance."
                << std::endl;
        }
778
        return std::make_pair(std::move(tuning_table), found_table);
779
780
781
782
    }

    bool get_module_tuned() const
    {
783
784
        static std::pair<mlir_tuning_table, bool> tuning_table = load_tuning_table();
        if(not mlirRockTuningSetFromTable(tuning_table.first.get(), mmodule.get()))
785
        {
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
            std::array<char, ROCMLIR_TUNING_KEY_BUFSZ> prob_config;
            size_t prob_config_bytes =
                mlirRockTuningGetKey(mmodule.get(), prob_config.data(), prob_config.size());
            if(prob_config_bytes >= prob_config.size())
            {
                std::cerr << "MLIR tuning key overflowed buffer, needed " << prob_config_bytes
                          << " bytes" << std::endl;
                return false;
            }
            std::string prob_config_str(prob_config.begin(),
                                        prob_config.begin() + prob_config_bytes);
            if(tuning_table.second)
            {
                std::cerr << "NOTE: MLIR tuning table did not include a key for " << prob_config_str
                          << std::endl;
            }
            dump_tuning_cfg(prob_config_str);
803
804
805
806
            return false;
        }
        return true;
    }
807

Paul Fultz II's avatar
Paul Fultz II committed
808
809
810
    mlir_context ctx;
    MlirLocation location;
    mlir_module mmodule;
811
    problem_params pp;
Paul Fultz II's avatar
Paul Fultz II committed
812
    std::deque<std::string> strings{};
813
814
    std::string target_arch = "";
    std::size_t num_cu      = 0;
815
    std::string sym_name;
Paul Fultz II's avatar
Paul Fultz II committed
816
817
818
819
820
821
822
823
824
825
};

std::string dump_mlir(const module& m)
{
    mlir_program mp;
    mp.parse(m);
    auto mod_op = mlirModuleGetOperation(mp.mmodule.get());
    return mlir_print(&mlirOperationPrint, mod_op);
}

Paul Fultz II's avatar
Paul Fultz II committed
826
void adjust_param_shapes(module& m, const std::vector<shape>& inputs)
827
828
829
830
831
832
{
    auto names = m.get_parameter_names();
    std::sort(names.begin(), names.end());
    for(auto i : range(names.size()))
    {
        const auto& name  = names[i];
Paul Fultz II's avatar
Paul Fultz II committed
833
        const auto& input = inputs[i];
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
        auto param        = m.get_parameter(name);
        if(input.standard())
            continue;
        auto lens    = input.lens();
        auto strides = input.strides();
        std::vector<operation> ops;
        if(input.transposed())
        {
            auto perm  = find_permutation(input);
            auto iperm = invert_permutation(perm);
            lens       = reorder_dims(lens, iperm);
            strides    = reorder_dims(strides, iperm);
            ops.push_back(make_op("transpose", {{"permutation", perm}}));
        }
        if(input.broadcasted())
        {
            std::transform(lens.begin(),
                           lens.end(),
                           strides.begin(),
                           lens.begin(),
                           [](auto len, auto stride) -> std::size_t {
                               if(stride == 0)
                                   return 1;
                               return len;
                           });
            ops.push_back(make_op("multibroadcast", {{"out_lens", input.lens()}}));
        }
        auto new_param =
            std::accumulate(ops.begin(),
                            ops.end(),
                            m.add_parameter(name + ".0", shape{input.type(), lens}),
                            [&](auto x, auto op) { return m.insert_instruction(param, op, x); });
        m.replace_instruction(param, new_param);
        m.remove_instruction(param);
    }
}

871
code_object_op compile_mlir(const context& migraphx_ctx,
Paul Fultz II's avatar
Paul Fultz II committed
872
873
874
                            module m,
                            const std::vector<instruction_ref>& inputs,
                            const value& solution)
Paul Fultz II's avatar
Paul Fultz II committed
875
{
Paul Fultz II's avatar
Paul Fultz II committed
876
    adjust_param_shapes(m, to_shapes(inputs));
Paul Fultz II's avatar
Paul Fultz II committed
877
    const bool trace = enabled(MIGRAPHX_TRACE_MLIR{});
878

879
    static std::mutex mutex;
880
    if(trace)
881
882
    {
        const std::lock_guard<std::mutex> lock(mutex);
883
        std::cout << m << std::endl;
884
    }
885

Paul Fultz II's avatar
Paul Fultz II committed
886
    mlir_program mp;
887
    mp.set_gpu_properties(migraphx_ctx);
Paul Fultz II's avatar
Paul Fultz II committed
888
889
890
    mp.parse(m);
    auto mod_op = mlirModuleGetOperation(mp.mmodule.get());
    if(trace)
891
892
    {
        const std::lock_guard<std::mutex> lock(mutex);
Paul Fultz II's avatar
Paul Fultz II committed
893
        std::cout << mlir_print(&mlirOperationPrint, mod_op) << std::endl;
894
    }
Paul Fultz II's avatar
Paul Fultz II committed
895
896
897
    auto co            = mp.compile(solution);
    co.expected_inputs = to_shapes(inputs);
    co.output          = m.get_output_shapes().front();
Paul Fultz II's avatar
Paul Fultz II committed
898
899
900
901
902
903
904
905
    return co;
}

instruction_ref insert_mlir(module& m,
                            instruction_ref ins,
                            code_object_op co,
                            const std::vector<instruction_ref>& inputs)
{
906

Paul Fultz II's avatar
Paul Fultz II committed
907
    std::vector<instruction_ref> refs;
908
909
910
    std::size_t last = 0;
    refs.reserve(inputs.size());
    std::copy(inputs.begin(), inputs.end(), std::back_inserter(refs));
911
    last               = refs.size() - 1;
Paul Fultz II's avatar
Paul Fultz II committed
912
913
914
915
916
    co.expected_inputs = to_shapes(refs);
    co.output_arg      = last;
    return m.insert_instruction(ins, co, refs);
}

917
918
tuning_config
get_tuning_config_mlir(const context& migraphx_ctx, module m, const std::vector<shape>& inputs)
Paul Fultz II's avatar
Paul Fultz II committed
919
920
921
922
{
    adjust_param_shapes(m, inputs);

    mlir_program mp;
923
    mp.set_gpu_properties(migraphx_ctx);
Paul Fultz II's avatar
Paul Fultz II committed
924
925
926
927
    mp.parse(m);
    return mp.get_tuning_config();
}

Paul Fultz II's avatar
Paul Fultz II committed
928
929
930
931
932
933
934
935
936
#else

std::string dump_mlir(const module&) { return {}; }

template <class T>
void use(T&)
{
}

937
938
// Disabling clang-tidy warning on non-real useage.
// NOLINTBEGIN(performance-unnecessary-value-param)
Paul Fultz II's avatar
Paul Fultz II committed
939
940
code_object_op
compile_mlir(const context&, module, const std::vector<instruction_ref>&, const value&)
941
942
943
944
{
    return {};
}

Paul Fultz II's avatar
Paul Fultz II committed
945
946
947
948
949
instruction_ref
// cppcheck-suppress funcArgNamesDifferent
insert_mlir(module& m, instruction_ref, code_object_op co, const std::vector<instruction_ref>&)
{
    use(co);
950
    use(m);
Paul Fultz II's avatar
Paul Fultz II committed
951
952
953
    return m.end();
}

954
955
956
957
tuning_config get_tuning_config_mlir(const context&, module, const std::vector<shape>&)
{
    return {};
}
Paul Fultz II's avatar
Paul Fultz II committed
958
959
// NOLINTEND(performance-unnecessary-value-param)

Paul Fultz II's avatar
Paul Fultz II committed
960
961
962
963
964
#endif

} // namespace gpu
} // namespace MIGRAPHX_INLINE_NS
} // namespace migraphx