schedule.cpp 10.7 KB
Newer Older
Paul's avatar
Paul committed
1
2
3
#include <migraphx/schedule.hpp>
#include <migraphx/program.hpp>
#include <migraphx/instruction.hpp>
Paul's avatar
Paul committed
4
#include <migraphx/operators.hpp>
Paul's avatar
Paul committed
5
#include <migraphx/iterator_for.hpp>
Paul's avatar
Paul committed
6
#include <migraphx/dfor.hpp>
Paul's avatar
Paul committed
7
8
9
#include <migraphx/functional.hpp>
#include <migraphx/ranges.hpp>
#include <unordered_map>
Paul's avatar
Paul committed
10
#include <unordered_set>
11
#include <set>
Paul's avatar
Paul committed
12
#include <deque>
Paul's avatar
Paul committed
13
14
15
16

namespace migraphx {
inline namespace MIGRAPHX_INLINE_NS {

Paul's avatar
Paul committed
17
18
19
20
21
22
23
24
25
26
auto get_inputs()
{
    return [](auto i) { return i->inputs(); };
}

auto get_outputs()
{
    return [](auto i) { return i->outputs(); };
}

27
28
29
struct stream_info
{
    std::unordered_map<instruction_ref, std::size_t> ins2stream;
Paul's avatar
Paul committed
30
    std::unordered_map<instruction_ref, std::size_t> weights;
31
    std::unordered_map<instruction_ref, std::size_t> iweights;
Paul's avatar
Paul committed
32
33
34
35
36
37

    void accumulate_weights(instruction_ref last, const schedule_model& model)
    {
        fix<std::size_t>([&](auto self, auto ins) -> std::size_t {
            if(weights.count(ins) == 0)
            {
Paul's avatar
Paul committed
38
                std::size_t weight = 0;
Paul's avatar
Paul committed
39
                auto&& op          = ins->get_operator();
Paul's avatar
Paul committed
40
41
                if(not is_context_free(op) and op.name()[0] != '@')
                    weight = model.weight(op);
42
                iweights[ins] = weight;
Paul's avatar
Paul committed
43
44
45
                weights[ins] =
                    std::accumulate(ins->inputs().begin(),
                                    ins->inputs().end(),
Paul's avatar
Paul committed
46
                                    weight,
Paul's avatar
Paul committed
47
48
49
50
51
52
                                    [&](std::size_t w, instruction_ref i) { return w + self(i); });
            }
            return weights[ins];
        })(last);
    }

Paul's avatar
Paul committed
53
    struct partition
Paul's avatar
Paul committed
54
    {
Paul's avatar
Paul committed
55
56
57
58
        std::size_t weight = 0;
        std::vector<instruction_ref> instructions{};

        void add(instruction_ref ins, std::size_t w)
Paul's avatar
Paul committed
59
        {
Paul's avatar
Paul committed
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
            weight += w;
            instructions.push_back(ins);
        }
    };

    void assign_streams(program& p, std::size_t n)
    {
        const std::size_t min_partition_threshold = 2;
        partition critical;
        std::unordered_map<instruction_ref, std::deque<partition>> partitions;
        fix([&](auto self, auto ins, auto& part) {
            // If weight is zero then stop
            if(this->weights[ins] == 0)
                return;
            part.add(ins, this->iweights[ins]);

            auto max_it = std::max_element(ins->inputs().begin(), ins->inputs().end(), by(std::less<>{}, index_of(this->weights)));
            for(auto i : ins->inputs())
            {
                const auto weight = this->weights[i];
                if (i == *max_it or weight <= min_partition_threshold) 
Paul's avatar
Paul committed
81
                {
Paul's avatar
Paul committed
82
                    self(i, part);
Paul's avatar
Paul committed
83
                }
Paul's avatar
Paul committed
84
85
86
87
88
89
90
91
92
93
94
95
96
                else
                {
                    partitions[ins].emplace_back();
                    self(i, partitions[ins].back());
                }
            }
        })(std::prev(p.end()), critical);

        // Set the critical partition to stream 0
        set_stream(critical, 0);
        std::vector<std::size_t> streams(n-1);
        // Assign streams for the other partitions
        for(auto&& ins_part:partitions)
Paul's avatar
Paul committed
97
        {
Paul's avatar
Paul committed
98
99
100
101
102
103
104
            std::sort(ins_part.second.begin(), ins_part.second.end(), by(std::greater<>{}, [](auto&& x) { return std::make_tuple(x.weight, x.instructions.size()); }));
            for(auto&& part:ins_part.second)
            {
                auto stream = std::min_element(streams.begin(), streams.end()) - streams.begin();
                set_stream(part, stream+1);
                streams[stream] += part.weight;
            }
Paul's avatar
Paul committed
105
106
        }
    }
107

Paul's avatar
Paul committed
108
109
110
111
112
113
114
    void set_stream(const partition& p, std::size_t n)
    {
        for(auto ins:p.instructions)
            if (iweights[ins] > 0)
                set_stream(ins, n);
    }

Paul's avatar
Paul committed
115
    void set_stream(instruction_ref ins, std::size_t n)
116
    {
Paul's avatar
Paul committed
117
118
        assert(iweights[ins] > 0);
        ins2stream[ins] = n;
119
    }
120

Paul's avatar
Paul committed
121
    std::size_t get_stream(instruction_ref ins) const { return ins2stream.at(ins); }
122

Paul's avatar
Paul committed
123
    bool has_stream(instruction_ref ins) const { return ins2stream.count(ins) > 0; }
124

Paul's avatar
Paul committed
125
    bool different(const std::vector<std::size_t>& v) const
126
    {
Paul's avatar
Paul committed
127
        if(v.size() < 2)
128
            return false;
Paul's avatar
Paul committed
129
        return not std::all_of(v.begin(), v.end(), [&](std::size_t x) { return x == v.front(); });
130
131
    }

Paul's avatar
Paul committed
132
    template <class F>
Paul's avatar
Paul committed
133
    bool different(F f, std::size_t stream) const
Paul's avatar
Paul committed
134
    {
Paul's avatar
Paul committed
135
        bool result = false;
Paul's avatar
Paul committed
136
        f([&](auto s) {
Paul's avatar
Paul committed
137
            if(s != stream)
Paul's avatar
Paul committed
138
            {
Paul's avatar
Paul committed
139
140
                result = true;
                return false;
Paul's avatar
Paul committed
141
            }
Paul's avatar
Paul committed
142
143
144
            stream = s;
            return true;
        });
Paul's avatar
Paul committed
145
146
        return result;
    }
147

Paul's avatar
Paul committed
148
149
150
151
152
153
154
155
156
157
158
    template <class F>
    bool different(F f) const
    {
        bool result = false;
        f([&](auto s) {
            result = different(f, s);
            return false;
        });
        return result;
    }

Paul's avatar
Paul committed
159
160
161
162
163
164
165
    template <class Selector>
    auto get_streams(instruction_ref start, Selector select) const
    {
        return [=](auto f) {
            return fix<bool>([&](auto self, auto ins) {
                for(auto i : select(ins))
                {
166
                    if(iweights.at(i) == 0)
Paul's avatar
Paul committed
167
                    {
Paul's avatar
Paul committed
168
                        if(not self(i))
Paul's avatar
Paul committed
169
170
171
172
                            return false;
                    }
                    else
                    {
Paul's avatar
Paul committed
173
                        if(not f(get_stream(i)))
Paul's avatar
Paul committed
174
175
176
177
178
179
180
181
                            return false;
                    }
                }
                return true;
            })(start);
        };
    }

Paul's avatar
Paul committed
182
183
184
185
186
    template <class... Ts>
    bool is_merge_point(instruction_ref ins, Ts... xs) const
    {
        return different(get_streams(ins, get_inputs()), xs...);
    }
Paul's avatar
Paul committed
187

Paul's avatar
Paul committed
188
189
190
191
192
    template <class... Ts>
    bool is_split_point(instruction_ref ins, Ts... xs) const
    {
        return different(get_streams(ins, get_outputs()), xs...);
    }
193
194
195

    std::vector<std::size_t> wait_for(instruction_ref ins) const
    {
Paul's avatar
Paul committed
196
        std::vector<std::size_t> result;
Paul's avatar
Paul committed
197
        get_streams(ins, get_inputs())([&](auto s) {
Paul's avatar
Paul committed
198
199
200
201
            result.push_back(s);
            return true;
        });
        // Remove duplicates
Paul's avatar
Paul committed
202
203
        std::sort(result.begin(), result.end());
        result.erase(std::unique(result.begin(), result.end()), result.end());
Paul's avatar
Paul committed
204
        // Remove the merged stream
Paul's avatar
Paul committed
205
        auto it = std::find(result.begin(), result.end(), get_stream(ins));
Paul's avatar
Paul committed
206
        if(it != result.end())
Paul's avatar
Paul committed
207
            result.erase(it);
Paul's avatar
Paul committed
208
        return result;
209
    }
Paul's avatar
Paul committed
210

Paul's avatar
Paul committed
211
212
    std::unordered_map<instruction_ref, std::vector<std::vector<instruction_ref>>>
    find_concurrent_instructions(program& p)
Paul's avatar
Paul committed
213
    {
Paul's avatar
Paul committed
214
        std::unordered_map<instruction_ref, std::vector<std::vector<instruction_ref>>> result;
Paul's avatar
Paul committed
215
216
217
        std::unordered_map<instruction_ref, std::unordered_set<instruction_ref>> split_from;
        for(auto ins : iterator_for(p))
        {
218
            if(iweights[ins] == 0)
Paul's avatar
Paul committed
219
220
221
                continue;
            for(auto&& arg : ins->inputs())
            {
Paul's avatar
Paul committed
222
                if(is_split_point(arg))
Paul's avatar
Paul committed
223
224
225
226
                    split_from[ins].insert(arg);
                split_from[ins].insert(split_from[arg].begin(), split_from[arg].end());
            }

Paul's avatar
Paul committed
227
            auto stream = get_stream(ins);
Paul's avatar
Paul committed
228
229
230
231
232
233
234
235
236
237
            // if (is_merge_point(ins))
            // {
            //     // post-dominator kills split point.
            //     for(auto& split : split_from[ins])
            //     {
            //         if(strictly_post_dominates(ins, split))
            //             split_from[ins].erase(split);
            //     }
            // }

Paul's avatar
Paul committed
238
239
240
            // Collect concur instructions for each split point.
            for(auto& split : split_from[ins])
            {
Paul's avatar
Paul committed
241
242
                if(result[split].size() <= stream)
                    result[split].resize(stream + 1);
Paul's avatar
Paul committed
243
                result[split][stream].push_back(ins);
Paul's avatar
Paul committed
244
245
            }
        }
Paul's avatar
Paul committed
246
        return result;
Paul's avatar
Paul committed
247
    }
248
249
};

Paul's avatar
Paul committed
250
251
void schedule::apply(program& p) const
{
252
    stream_info si;
Paul's avatar
Paul committed
253
254
255
    auto last = std::prev(p.end());
    si.accumulate_weights(last, model);
    si.assign_streams(p, model.concurrency());
256

Paul's avatar
Paul committed
257
258
    // Topo sort
    fix([&](auto self, auto ins) {
Paul's avatar
Paul committed
259
        auto args = ins->inputs();
Paul's avatar
Paul committed
260
261
262
        std::sort(args.begin(), args.end(), by(std::less<>{}, [&](auto x) {
            return std::make_tuple(si.weights[x], x->inputs().size());
        }));
Paul's avatar
Paul committed
263
        for(auto i : args)
264
        {
Paul's avatar
Paul committed
265
266
            p.move_instruction(i, p.begin());
            self(i);
267
        }
Paul's avatar
Paul committed
268
    })(last);
Paul's avatar
Paul committed
269

Paul's avatar
Paul committed
270
271
272
273
274
    if(enabled(MIGRAPHX_TRACE_COMPILE{}))
    {
        p.annotate(std::cout, [&](auto ins) {
            std::cout << ":";
            std::cout << " weight=" << si.weights.at(ins);
Paul's avatar
Paul committed
275
276
277
278
279
280
            std::cout << " input={";
            si.get_streams(ins, get_inputs())([&](auto s) {
                std::cout << s << ",";
                return true;
            });
            std::cout << "}";
Paul's avatar
Paul committed
281
            if(si.has_stream(ins))
Paul's avatar
Paul committed
282
283
284
285
286
                std::cout << " stream=" << si.get_stream(ins);
        });
        std::cout << std::endl;
    }

287
    // Schedule instructions
Paul's avatar
Paul committed
288
289
    std::set<std::size_t> waited_for;
    std::size_t waited_on = model.concurrency();
Paul's avatar
Paul committed
290
    for(auto ins : iterator_for(p))
291
    {
Paul's avatar
Paul committed
292
        // Only schedule instructions that have a stream
Paul's avatar
Paul committed
293
        if(not si.has_stream(ins))
Paul's avatar
Paul committed
294
            continue;
295
        assert(si.weights[ins] > 0);
Paul's avatar
Paul committed
296
        // Schedule instruction on the stream
Paul's avatar
Paul committed
297
        auto stream = si.get_stream(ins);
Paul's avatar
Paul committed
298
        assert(stream < model.concurrency());
Paul's avatar
Paul committed
299
        model.schedule_instruction(p, ins, stream);
Paul's avatar
Paul committed
300
        // Clear waits when switching streams
Paul's avatar
Paul committed
301
        if(stream != waited_on)
Paul's avatar
Paul committed
302
303
            waited_for.clear();
        // Schedule wait instruction
Paul's avatar
Paul committed
304
        if(si.is_merge_point(ins, stream))
Paul's avatar
Paul committed
305
306
307
        {
            auto wait_for = si.wait_for(ins);
            // Dont wait for streams that have already been waited for
Paul's avatar
Paul committed
308
309
310
311
312
            wait_for.erase(std::remove_if(wait_for.begin(),
                                          wait_for.end(),
                                          [&](auto x) { return waited_for.count(x) > 0; }),
                           wait_for.end());
            if(not wait_for.empty())
Paul's avatar
Paul committed
313
314
315
316
                model.wait(p, ins, stream, wait_for);
            waited_for.insert(wait_for.begin(), wait_for.end());
            waited_on = stream;
        }
317
    }
Paul's avatar
Paul committed
318

Paul's avatar
Paul committed
319
320
    // Add memory conflicts
    auto concur_ins = si.find_concurrent_instructions(p);
Paul's avatar
Paul committed
321
    for(auto&& split : concur_ins)
Paul's avatar
Paul committed
322
323
    {
        dfor(split.second.size(), split.second.size())([&](auto i, auto j) {
Paul's avatar
Paul committed
324
            if(i == j)
Paul's avatar
Paul committed
325
                return;
Paul's avatar
Paul committed
326
327
            for(auto ins1 : split.second[i])
            {
Paul's avatar
Paul committed
328
                auto args = split.second[j];
Paul's avatar
Paul committed
329
                args.insert(args.begin(), ins1);
Paul's avatar
Paul committed
330
331
332
333
334

                auto point = std::max_element(args.begin(), args.end(), [&](auto x, auto y) {
                    return std::distance(split.first, x) < std::distance(split.first, y);
                });
                p.insert_instruction(std::next(*point), op::identity{}, args);
Paul's avatar
Paul committed
335
336
337
            }
        });
    }
Paul's avatar
Paul committed
338
339
340
341
}

} // namespace MIGRAPHX_INLINE_NS
} // namespace migraphx