pre_scheduling_impl.cpp 10.2 KB
Newer Older
mei-ye's avatar
mei-ye committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
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
186
187
188
189
190
191
192
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
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
244
245
246
247
248
249
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
#include "pre_scheduling_impl.hpp"
#include <migraphx/iterator_for.hpp>
#include <migraphx/pass_config.hpp>
#include <stack>
namespace migraphx {

// Compute accumulated weights for each node in the DAG. Collect exit nodes
// and sort them according to accumulated weights.
//
void pre_scheduling_impl::compute_weights()
{
    int ndx = 0;
    std::unordered_map<dag_node*, bool> visited;
    for(auto ins : iterator_for(*p_program))
    {
        dag_node& node             = nodes[ndx];
        std::pair<int, int> weight = weight_func(ins->get_operator());
        node.weight                = weight.first;
        node.run_on_cpu            = weight.second;
        node.weight_sum += node.weight;
        visited.clear();

        for(auto&& arg : ins->inputs())
        {
            assert(instr2_node.find(arg) != instr2_node.end());
            dag_node* def_node = instr2_node[arg];
            if(visited.find(def_node) == visited.end())
            {
                node.weight_sum += def_node->weight_sum;
                visited[def_node] = true;
            }
        }
        if(ins->outputs().empty())
        {
            exit_nodes.push_back(&node);
        }
        node.ins         = ins;
        node.ins_ndx     = ndx++;
        instr2_node[ins] = &node;
    }
    int size = exit_nodes.size();
    if(size > 1)
    {
        std::sort(exit_nodes.begin(), exit_nodes.end(), compare_exit_nodes);
    }
}

// Do topology sort according to accumulated weight.  Identify critial paths.
// Schedule nodes into streams.  Reorder instructions according to topological
// order and annoate streams and events in the instructions.
//
void pre_scheduling_impl::reorder()
{
    std::list<dag_node*> sorted_nodes;
    std::stack<dag_node*> stack;
    std::priority_queue<dag_node*, std::vector<dag_node*>, weighted_topology_ordering> child_queue;
    std::unordered_map<dag_node*, bool> visited;
    std::unordered_map<dag_node*, bool> dequeued;

    for(auto&& node : exit_nodes)
    {
        stack.push(node);
        node->partition = partition_info.create_partition();
        partition_info.add_weight(node);
        while(!stack.empty())
        {
            auto cur = stack.top();
            if(dequeued.find(cur) != dequeued.end())
            {
                stack.pop();
                continue;
            }
            else if((visited.find(cur) != visited.end()) || cur->ins->inputs().empty())
            {
                stack.pop();
                sorted_nodes.push_back(cur);
                dequeued[cur] = true;
                continue;
            }
            // sort child nodes.
            for(auto&& arg : cur->ins->inputs())
            {
                dag_node* child_node = instr2_node[arg];
                if(dequeued.find(child_node) == dequeued.end())
                {
                    child_queue.push(child_node);
                }
            }

            // Last item in queue is on critical path.
            while(!child_queue.empty())
            {
                dag_node* child = child_queue.top();
                stack.push(child);
                child_queue.pop();
                if(child->weight_sum < min_partition_threshold)
                    child->partition = cur->partition;
                else if(!child_queue.empty())
                    child->partition = partition_info.create_partition();
                else
                {
                    cur->first_child = child;
                    child->partition = cur->partition;
                }
                partition_info.add_weight(child);
            }
            visited[cur] = true;
        }
    }

#ifdef MIGRAPHX_DEBUG_OPT
    MIGRAPHX_DEBUG(dump("---After weighted topology sort---"));
    MIGRAPHX_DEBUG(dump(sorted_nodes));
#endif
    schedule(sorted_nodes);
    splice(sorted_nodes);
    annotate(sorted_nodes);

    if(enable_verify)
        verify();
}

// Assign stream to nodes according to load balance.
//
int pre_scheduling_impl::get_stream(stream_info& info, dag_node* node)
{
    int max_cycle = info.max_cycle;
    if(max_cycle == 0)
        return 0;
    int partition_load   = partition_info.weight_sum[node->partition];
    int earliest_cycle   = node->earliest_cycle;
    int min_cycle        = -1;
    int min_cycle_stream = -1;
    for(auto stream = 0; stream < num_of_streams; ++stream)
    {
        int cycle = std::max(info.next_cycles[stream], earliest_cycle);
        if((cycle < max_cycle) && ((max_cycle - cycle) > partition_load))
            return stream;
        if((min_cycle_stream == -1) || (cycle < min_cycle))
        {
            min_cycle        = cycle;
            min_cycle_stream = stream;
        }
    }
    return min_cycle_stream;
}

//  Record the stream-assignment.
//
void pre_scheduling_impl::record(stream_info& info, dag_node* node)
{
    int stream               = node->stream;
    int next_cycle           = info.next_cycles[stream];
    node->sched_cycle        = std::max(node->earliest_cycle, next_cycle);
    next_cycle               = node->sched_cycle + node->weight;
    info.next_cycles[stream] = next_cycle;
    info.max_cycle           = std::max(info.max_cycle, next_cycle);
    for(auto&& arg : node->ins->outputs())
    {
        assert(instr2_node.find(arg) != instr2_node.end());
        dag_node* use_node       = instr2_node[arg];
        use_node->earliest_cycle = std::max(use_node->earliest_cycle, next_cycle);
    }
    if(node->can_use_stream())
        instr2_stream[node->ins] = stream;
}

//  Assign nodes to streams.
//
void pre_scheduling_impl::schedule(std::list<dag_node*>& sorted_nodes)
{
    if(num_of_streams == 0)
        return;
    stream_info info(num_of_streams);
    std::unordered_map<int, int> partition2_stream;
    partition2_stream.clear();

    for(auto&& node : sorted_nodes)
    {
        int cur_partition = node->partition;
        assert(cur_partition >= 0);
        if(partition2_stream.find(cur_partition) != partition2_stream.end())
        {
            node->stream = partition2_stream[cur_partition];
        }
        else
        {
            node->stream = get_stream(info, node);
        }
        assert(node->stream >= 0);
        record(info, node);
        partition2_stream[cur_partition] = node->stream;
    }

#ifdef MIGRAPHX_DEBUG_OPT
    MIGRAPHX_DEBUG(dump("---After assigning stream---"));
    MIGRAPHX_DEBUG(dump(sorted_nodes));
#endif
}

// Reorder the instructions ino topological order.
//
void pre_scheduling_impl::splice(std::list<dag_node*>& sorted_nodes)
{
    if(sorted_nodes.size() <= 1)
        return;
    auto begin                    = sorted_nodes.begin();
    auto iter                     = sorted_nodes.end();
    instruction_ref insert_before = (*(--iter))->ins;
    do
    {
        iter--;
        insert_before = p_program->move_instruction((*iter)->ins, insert_before);
    } while(iter != begin);

#ifdef MIGRAPHX_DEBUG_OPT
    MIGRAPHX_DEBUG(dump("---After splice in pre-scheduling---"));
    MIGRAPHX_DEBUG(dump_program());
#endif
}

//  Annotate streams and events in the instruction.  Insert set_stream
//  instructions.
//
void pre_scheduling_impl::annotate(std::list<dag_node*>& sorted_nodes)
{
    int event                  = 0;
    int last_stream            = -1;
    bool enable_event_as_instr = enabled(MIGRAPHX_ENABLE_EVENT_AS_INSTRUCTION{});
    for(auto&& node : sorted_nodes)
    {
        instruction_ref ins = node->ins;
        if(instr2_stream.find(ins) == instr2_stream.end())
            continue;
        int stream = instr2_stream[ins];
        ins->set_stream(stream);
        if(last_stream != stream)
        {
            insert_instr.insert_stream(p_program, ins, stream);
            last_stream = stream;
        }
        std::vector<int> events;
        for(auto&& arg : ins->inputs())
        {
            if(instr2_stream.find(arg) == instr2_stream.end())
                continue;
            int arg_s = instr2_stream[arg];
            if(arg_s == stream)
                continue;
            if(!has_mask(arg, record_event))
            {
                events.push_back(event);
                arg->set_event(event);
                arg->add_mask(record_event);
                if(enable_event_as_instr)
                    insert_instr.insert_record_event(p_program, std::next(arg), event);
                event++;
            }

            ins->add_mask(wait_event);
            add_mask(arg, record_event);
            add_mask(ins, wait_event);
        }
        if(enable_event_as_instr)
        {
            for(auto&& i : events)
                insert_instr.insert_wait_event(p_program, ins, i);
        }
    }
}

void pre_scheduling_impl::run()
{
    std::size_t num_of_instrs = p_program->size();
    if(num_of_instrs == 0)
        return;
    MIGRAPHX_DEBUG(dump("---Before pre-scheduling---"));
    MIGRAPHX_DEBUG(dump_program());
    nodes.resize(num_of_instrs);
    compute_weights();
    reorder();
}

void pre_scheduling_impl::verify()
{
    std::unordered_map<instruction_ref, bool> visited;
    for(auto ins : iterator_for(*p_program))
    {
        for(auto&& arg : ins->inputs())
        {
            if(visited.find(arg) == visited.end())
                MIGRAPHX_THROW("Input not visited");
        }
        visited[ins] = true;
    }
}

#ifdef MIGRAPHX_DEBUG_OPT
void pre_scheduling_impl::dump(const std::string& str) { std::cout << str << std::endl; }

void pre_scheduling_impl::dump_program() { std::cout << *p_program << std::endl; }

void pre_scheduling_impl::dump(std::list<dag_node*>& sorted_nodes)
{
    for(auto&& node : sorted_nodes)
    {
        node->dump();
        if(!node->ins->inputs().empty())
        {
            std::cout << " inputs: ";
            for(auto&& arg : node->ins->inputs())
            {
                dag_node* def_node = instr2_node[arg];
                std::cout << " @" << def_node->ins_ndx;
            }
            std::cout << std::endl;
        }
    }
}

void dag_node::dump()
{
    std::cout << " @" << ins_ndx;
    std::cout << " name: " << ins->name();
    std::cout << " weight: " << weight;
    std::cout << " weight_sum: " << weight_sum;
    if(can_use_stream())
        std::cout << " stream: " << stream;
    std::cout << " partition: " << partition;
    std::cout << " sched_cycle: " << sched_cycle;
    std::cout << std::endl;
}
#endif
} // namespace migraphx