compile_ops.cpp 10.2 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.
 */
24
25
26
27
28
#include <migraphx/gpu/compile_ops.hpp>
#include <migraphx/gpu/context.hpp>
#include <migraphx/module.hpp>
#include <migraphx/iterator_for.hpp>
#include <migraphx/instruction.hpp>
Paul Fultz II's avatar
Paul Fultz II committed
29
#include <migraphx/par_for.hpp>
30
31
#include <migraphx/register_op.hpp>
#include <migraphx/op/identity.hpp>
32
#include <migraphx/gpu/compiler.hpp>
33
#include <migraphx/gpu/time_op.hpp>
34

Paul's avatar
Paul committed
35
36
#include <mutex>

37
38
39
40
namespace migraphx {
inline namespace MIGRAPHX_INLINE_NS {
namespace gpu {

41
42
MIGRAPHX_DECLARE_ENV_VAR(MIGRAPHX_GPU_COMPILE_PARALLEL);

43
44
struct precompile_op
{
45
46
47
    operation op                = op::identity{};
    std::size_t additional_args = 1;
    bool ignore_modules         = false;
48
49
50
51

    template <class Self, class F>
    static auto reflect(Self& self, F f)
    {
52
53
54
        return pack(f(self.op, "op"),
                    f(self.additional_args, "additional_args"),
                    f(self.ignore_modules, "ignore_modules"));
55
56
57
58
59
60
    }

    std::string name() const { return "gpu::precompile_op"; }

    shape compute_shape(std::vector<shape> inputs, const std::vector<module_ref>& mods) const
    {
61
62
63
64
        // Pop off additional args
        inputs.resize(inputs.size() - additional_args);
        if(ignore_modules)
            return op.compute_shape(inputs);
65
66
67
68
69
70
71
72
73
74
75
        return op.compute_shape(inputs, mods);
    }

    std::ptrdiff_t output_alias(const std::vector<shape>& shapes) const
    {
        return shapes.size() - 1;
    }
};

MIGRAPHX_REGISTER_OP(precompile_op);

Paul Fultz II's avatar
Paul Fultz II committed
76
77
struct compiled_result
{
78
    compiler_replace replace;
Paul Fultz II's avatar
Paul Fultz II committed
79
80
81
    instruction_ref ins;
};

82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
struct problem_cache
{
    bool has(const std::string& name, const value& problem) const
    {
        return contains(cache, create_key(name, problem));
    }
    void insert(const std::string& name, const value& problem, const value& solution)
    {
        assert(not solution.is_null());
        cache[create_key(name, problem)] = solution;
    }
    void mark(const std::string& name, const value& problem)
    {
        cache.insert(std::make_pair(create_key(name, problem), value{}));
    }
    optional<value> get(const std::string& name, const value& problem) const
    {
        auto it = cache.find(create_key(name, problem));
        if(it == cache.end())
            return nullopt;
        return it->second;
    }
    static value create_key(const std::string& name, const value& problem)
    {
        return {{"name", name}, {"problem", problem}};
    }
    std::unordered_map<value, value> cache;
};

struct compile_plan
{
    context* ctx;
    operation preop;
    instruction_ref ins;
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
    optional<tuning_config> config                 = nullopt;
    std::vector<optional<compiled_result>> results = {};
    void update_config(bool exhaustive)
    {
        config = get_tuning_config(*ctx, ins, preop, exhaustive);
    }
    template <class Vector>
    void insert_compiles(Vector& compiles, const value& solution, std::size_t i)
    {
        compiles.emplace_back([=] {
            try
            {
                results[i] = compiled_result{compile(*ctx, ins, preop, solution), ins};
            }
            catch(...)
            {
                results[i] = nullopt;
            }
        });
    }

137
138
139
140
141
142
143
144
145
146
147
148
149
    template <class Vector>
    void add_compiles(Vector& compiles, problem_cache& pc)
    {
        if(config.has_value())
        {
            const auto& problem = config->problem;
            if(auto sol = pc.get(preop.name(), problem))
            {
                auto solution = sol.value();
                // No solution yet until benchmarked so skip for now
                if(solution.is_null())
                    return;
                results.resize(1);
150
                insert_compiles(compiles, solution, 0);
151
152
153
154
155
156
157
158
159
            }
            else
            {
                pc.mark(preop.name(), problem);
                const auto& solutions = config->solutions;
                results.resize(solutions.size());
                for(auto i : range(solutions.size()))
                {
                    auto solution = solutions[i];
160
                    insert_compiles(compiles, solution, i);
161
162
163
164
165
166
                }
            }
        }
        else
        {
            results.resize(1);
167
            insert_compiles(compiles, value{}, 0);
168
169
170
171
172
173
174
        }
    }
    const compiled_result& benchmark(problem_cache& pc) const
    {
        if(results.empty())
            MIGRAPHX_THROW("No configs to tune");
        if(results.size() == 1)
175
176
177
178
179
        {
            if(not results.front().has_value())
                MIGRAPHX_THROW("No configs to tune");
            return *results.front();
        }
180
181
182
183
        if(not config)
            MIGRAPHX_THROW("Multiple kernels without config");
        std::cout << "Benchmarking " << preop.name() << ": " << results.size() << " configs"
                  << std::endl;
Paul's avatar
Paul committed
184
        std::cout << "Problem: " << config->problem << std::endl;
185
186
187
188
        std::vector<double> times;
        times.reserve(results.size());
        std::transform(
            results.begin(), results.end(), std::back_inserter(times), [&](const auto& cr) {
189
190
191
192
                if(not cr.has_value())
                    return std::numeric_limits<double>::max();
                return time_op(*ctx, cr->replace.code_object, to_shapes(cr->ins->inputs()), 20)
                    .first;
193
194
            });
        auto i = std::distance(times.begin(), std::min_element(times.begin(), times.end()));
Paul's avatar
Paul committed
195
        auto j = std::distance(times.begin(), std::max_element(times.begin(), times.end()));
196
        std::cout << "Fastest solution: " << config->solutions.at(i) << std::endl;
Paul's avatar
Paul committed
197
        std::cout << "Slowest solution: " << config->solutions.at(j) << std::endl;
Paul's avatar
Paul committed
198
199
        std::cout << "Fastest time: " << *std::min_element(times.begin(), times.end()) << std::endl;
        std::cout << "Slowest time: " << *std::max_element(times.begin(), times.end()) << std::endl;
200
        pc.insert(preop.name(), config->problem, config->solutions.at(i));
201
202
203
        if(not results[i].has_value())
            MIGRAPHX_THROW("No valid tuned compilation.");
        return *results[i];
204
205
206
207
208
209
210
211
    }
    void replace(module& m, problem_cache& pc) const
    {
        const auto& cr = benchmark(pc);
        cr.replace.replace(m, cr.ins);
    }
};

Paul's avatar
Paul committed
212
213
struct parallel_work
{
Paul's avatar
Format  
Paul committed
214
215
    std::size_t start             = 0;
    std::size_t stop              = 0;
Paul's avatar
Paul committed
216
217
    std::shared_ptr<std::mutex> m = std::make_shared<std::mutex>();

Paul's avatar
Paul committed
218
219
220
221
222
    bool empty() const
    {
        std::lock_guard<std::mutex> guard(*m);
        return start >= stop;
    }
Paul's avatar
Format  
Paul committed
223
224
    optional<std::size_t> pop()
    {
Paul's avatar
Paul committed
225
        std::lock_guard<std::mutex> guard(*m);
Paul's avatar
Paul committed
226
        if(start >= stop)
Paul's avatar
Paul committed
227
228
229
230
231
            return nullopt;
        return start++;
    }
};

232
233
234
235
236
template <class F>
void par_compile(std::size_t n, F f)
{
    if(n == 0)
        return;
Paul's avatar
Paul committed
237
    std::cout << "Compile: " << n << std::endl;
Paul's avatar
Format  
Paul committed
238
239
    auto d =
        std::min(n, value_of(MIGRAPHX_GPU_COMPILE_PARALLEL{}, std::thread::hardware_concurrency()));
Paul's avatar
Paul committed
240
241
242
243
    std::size_t grainsize = std::ceil(static_cast<double>(n) / d);
    std::vector<parallel_work> pw(d);
    std::size_t work = 0;
    std::generate(pw.begin(), pw.end(), [&] {
Paul's avatar
Paul committed
244
        parallel_work p{work, std::min(n, work + grainsize)};
Paul's avatar
Format  
Paul committed
245
246
247
        work += grainsize;
        return p;
    });
Paul's avatar
Paul committed
248
249
250
251
252
253
    if(work < n)
        MIGRAPHX_THROW("Work missing");
    par_for(d, 1, [&](auto i) {
        while(auto w = pw[i].pop())
            f(*w);
        while(any_of(range(d), [&](auto j) {
Paul's avatar
Format  
Paul committed
254
255
256
257
258
259
260
261
262
            auto k = (j + i + 1) % d;
            if(k == i)
                return false;
            auto w = pw[k].pop();
            if(w.has_value())
                f(*w);
            return w.has_value();
        }))
            ;
Paul's avatar
Paul committed
263
    });
264
265
}

266
struct compile_manager
267
{
268
269
270
    problem_cache pc;
    std::vector<compile_plan> cps;
    bool exhaustive = false;
Paul Fultz II's avatar
Paul Fultz II committed
271

272
273
274
275
276
277
278
279
    template <class... Ts>
    void add_plan(Ts&&... xs)
    {
        cps.push_back({std::forward<Ts>(xs)...});
    }

    void update_configs()
    {
280
        par_compile(cps.size(), [&](auto i) { cps[i].update_config(exhaustive); });
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
    }

    void compile(module& m)
    {
        std::vector<std::function<void()>> compiles;
        for(auto& cp : cps)
        {
            cp.add_compiles(compiles, pc);
        }
        par_compile(compiles.size(), [&](auto i) { compiles[i](); });

        // Replace and/or benchmark
        for(const auto& cp : cps)
        {
            if(cp.results.empty())
                continue;
            cp.replace(m, pc);
        }

        // Remove compile_plan already executed
        cps.erase(std::remove_if(cps.begin(),
                                 cps.end(),
                                 [](const auto& cp) { return not cp.results.empty(); }),
                  cps.end());
    }
};

void compile_ops::apply(module& m) const
{
    compile_manager cm;
    cm.exhaustive = exhaustive_tune;
    // Find all precompile opes
313
314
315
316
317
    for(auto ins : iterator_for(m))
    {
        if(ins->name() != "gpu::precompile_op")
            continue;
        operation preop = any_cast<precompile_op>(ins->get_operator()).op;
318
        cm.add_plan(ctx, preop, ins);
319
    }
320
321
322
323
324
    cm.update_configs();
    cm.compile(m);
    // Compile already tuned configs
    cm.compile(m);
    assert(cm.cps.empty());
325
326
327
328
329
330
}

} // namespace gpu

} // namespace MIGRAPHX_INLINE_NS
} // namespace migraphx