"git@developer.sourcefind.cn:change/sglang.git" did not exist on "33f0de337d978b37c63b98575b4962c6e6479e8c"
scheduler.py 29.4 KB
Newer Older
1
2
3
4
5
"""For different schedulers"""
from __future__ import absolute_import

from .. import utils
from .._ffi.function import _init_api
Minjie Wang's avatar
Minjie Wang committed
6
from ..base import DGLError
7
8
9
10
11
12
from .. import backend as F
from ..frame import frame_like, FrameRef
from ..function.base import BuiltinFunction, BundledFunction
from ..udf import EdgeBatch, NodeBatch

from . import ir
Minjie Wang's avatar
Minjie Wang committed
13
from .ir import var
14
15
16
17
from . import degree_bucketing as db
from . import spmv

__all__ = [
Minjie Wang's avatar
Minjie Wang committed
18
19
20
21
22
23
    "schedule_send",
    "schedule_recv",
    "schedule_update_all",
    "schedule_snr",
    "schedule_apply_nodes",
    "schedule_apply_edges",
24
    "schedule_group_apply_edge",
Minjie Wang's avatar
Minjie Wang committed
25
26
27
    "schedule_push",
    "schedule_pull"
]
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44

def schedule_send(graph, u, v, eid, message_func):
    """get send schedule

    Parameters
    ----------
    graph: DGLGraph
        The DGLGraph to use
    u : utils.Index
        Source nodes
    v : utils.Index
        Destination nodes
    eid : utils.Index
        Ids of sending edges
    message_func: callable or list of callable
        The message function
    """
45
    message_func = _standardize_func_usage(message_func, 'message')
46
47
48
    mfunc_is_list = utils.is_iterable(message_func)
    if mfunc_is_list:
        message_func = BundledFunction(message_func)
49
    # vars
50
51
52
53
54
55
    var_nf = var.FEAT_DICT(graph._node_frame)
    var_ef = var.FEAT_DICT(graph._edge_frame)
    var_mf = var.FEAT_DICT(graph._msg_frame)
    var_u = var.IDX(u)
    var_v = var.IDX(v)
    var_eid = var.IDX(eid)
Da Zheng's avatar
Da Zheng committed
56
    msg = _gen_send(graph, var_nf, var_nf, var_ef, var_u, var_v, var_eid, message_func)
57
58
    ir.WRITE_ROW_(var_mf, var_eid, msg)
    # set message indicator to 1
59
    graph._set_msg_index(graph._get_msg_index().set_items(eid, 1))
60

Lingfan Yu's avatar
Lingfan Yu committed
61
62
63
64
65
def schedule_recv(graph,
                  recv_nodes,
                  reduce_func,
                  apply_func,
                  inplace):
66
67
68
69
70
71
    """Schedule recv.

    Parameters
    ----------
    graph: DGLGraph
        The DGLGraph to use
Lingfan Yu's avatar
Lingfan Yu committed
72
    recv_nodes: utils.Index
73
74
75
76
77
        Nodes to recv.
    reduce_func: callable or list of callable
        The reduce function
    apply_func: callable
        The apply node function
Lingfan Yu's avatar
Lingfan Yu committed
78
79
    inplace: bool
        If True, the update will be done in place
80
    """
81
82
    src, dst, eid = graph._graph.in_edges(recv_nodes)
    if len(eid) > 0:
83
        nonzero_idx = graph._get_msg_index().get_items(eid).nonzero()
84
85
86
87
88
89
90
        eid = eid.get_items(nonzero_idx)
        src = src.get_items(nonzero_idx)
        dst = dst.get_items(nonzero_idx)
    if len(eid) == 0:
        # Downgrade to apply nodes if
        #   1) all recv nodes are 0-degree nodes
        #   2) no send has been called
91
        if apply_func is not None:
Lingfan Yu's avatar
Lingfan Yu committed
92
            schedule_apply_nodes(graph, recv_nodes, apply_func, inplace)
93
    else:
94
95
96
97
98
99
        var_nf = var.FEAT_DICT(graph._node_frame, name='nf')
        # sort and unique the argument
        recv_nodes, _ = F.sort_1d(F.unique(recv_nodes.tousertensor()))
        recv_nodes = utils.toindex(recv_nodes)
        var_recv_nodes = var.IDX(recv_nodes, name='recv_nodes')
        # reduce
100
101
        reduced_feat = _gen_reduce(graph, reduce_func, (src, dst, eid),
                                   recv_nodes)
102
        # apply
103
104
        final_feat = _apply_with_accum(graph, var_recv_nodes, var_nf,
                                       reduced_feat, apply_func)
Lingfan Yu's avatar
Lingfan Yu committed
105
106
107
108
        if inplace:
            ir.WRITE_ROW_INPLACE_(var_nf, var_recv_nodes, final_feat)
        else:
            ir.WRITE_ROW_(var_nf, var_recv_nodes, final_feat)
109
        # set message indicator to 0
110
111
        graph._set_msg_index(graph._get_msg_index().set_items(eid, 0))
        if not graph._get_msg_index().has_nonzero():
112
            ir.CLEAR_FRAME_(var.FEAT_DICT(graph._msg_frame, name='mf'))
113
114
115
116
117

def schedule_snr(graph,
                 edge_tuples,
                 message_func,
                 reduce_func,
Lingfan Yu's avatar
Lingfan Yu committed
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
                 apply_func,
                 inplace):
    """Schedule send_and_recv.

    Parameters
    ----------
    graph: DGLGraph
        The DGLGraph to use
    edge_tuple: tuple
        A tuple of (src ids, dst ids, edge ids) representing edges to perform
        send_and_recv
    message_func: callable or list of callable
        The message function
    reduce_func: callable or list of callable
        The reduce function
    apply_func: callable
        The apply node function
    inplace: bool
        If True, the update will be done in place
    """
138
139
140
141
142
143
144
145
146
147
    u, v, eid = edge_tuples
    recv_nodes, _ = F.sort_1d(F.unique(v.tousertensor()))
    recv_nodes = utils.toindex(recv_nodes)
    # create vars
    var_nf = var.FEAT_DICT(graph._node_frame, name='nf')
    var_u = var.IDX(u)
    var_v = var.IDX(v)
    var_eid = var.IDX(eid)
    var_recv_nodes = var.IDX(recv_nodes, name='recv_nodes')
    # generate send and reduce schedule
Minjie Wang's avatar
Minjie Wang committed
148
    uv_getter = lambda: (var_u, var_v)
Da Zheng's avatar
Da Zheng committed
149
    adj_creator = lambda: spmv.build_adj_matrix_uv((u, v), recv_nodes, graph.number_of_nodes())
Minjie Wang's avatar
Minjie Wang committed
150
    inc_creator = lambda: spmv.build_inc_matrix_dst(v, recv_nodes)
Da Zheng's avatar
Da Zheng committed
151
152
    reduced_feat = _gen_send_reduce(graph, graph._node_frame, graph._node_frame,
                                    graph._edge_frame, message_func, reduce_func,
Minjie Wang's avatar
Minjie Wang committed
153
154
                                    var_eid, var_recv_nodes,
                                    uv_getter, adj_creator, inc_creator)
155
    # generate apply schedule
156
    final_feat = _apply_with_accum(graph, var_recv_nodes, var_nf, reduced_feat, apply_func)
Lingfan Yu's avatar
Lingfan Yu committed
157
158
159
160
    if inplace:
        ir.WRITE_ROW_INPLACE_(var_nf, var_recv_nodes, final_feat)
    else:
        ir.WRITE_ROW_(var_nf, var_recv_nodes, final_feat)
161

Lingfan Yu's avatar
Lingfan Yu committed
162
163
164
165
def schedule_update_all(graph,
                        message_func,
                        reduce_func,
                        apply_func):
166
167
168
169
170
171
172
173
174
175
176
177
178
    """get send and recv schedule

    Parameters
    ----------
    graph: DGLGraph
        The DGLGraph to use
    message_func: callable or list of callable
        The message function
    reduce_func: callable or list of callable
        The reduce function
    apply_func: callable
        The apply node function
    """
179
180
181
182
    if graph.number_of_edges() == 0:
        # All the nodes are zero degree; downgrade to apply nodes
        if apply_func is not None:
            nodes = utils.toindex(slice(0, graph.number_of_nodes()))
Lingfan Yu's avatar
Lingfan Yu committed
183
            schedule_apply_nodes(graph, nodes, apply_func, inplace=False)
184
    else:
185
        # TODO is the eid here correct?
186
187
188
189
190
191
192
        eid = utils.toindex(slice(0, graph.number_of_edges()))  # shortcut for ALL
        recv_nodes = utils.toindex(slice(0, graph.number_of_nodes()))  # shortcut for ALL
        # create vars
        var_nf = var.FEAT_DICT(graph._node_frame, name='nf')
        var_recv_nodes = var.IDX(recv_nodes, name='recv_nodes')
        var_eid = var.IDX(eid)
        # generate send + reduce
193
        def uv_getter():
194
            src, dst, _ = graph._graph.edges('eid')
195
            return var.IDX(src), var.IDX(dst)
Minjie Wang's avatar
Minjie Wang committed
196
197
        adj_creator = lambda: spmv.build_adj_matrix_graph(graph)
        inc_creator = lambda: spmv.build_inc_matrix_graph(graph)
Da Zheng's avatar
Da Zheng committed
198
199
        reduced_feat = _gen_send_reduce(graph, graph._node_frame, graph._node_frame,
                                        graph._edge_frame, message_func, reduce_func,
Minjie Wang's avatar
Minjie Wang committed
200
201
                                        var_eid, var_recv_nodes,
                                        uv_getter, adj_creator, inc_creator)
202
203
204
        # generate optional apply
        final_feat = _apply_with_accum(graph, var_recv_nodes, var_nf, reduced_feat, apply_func)
        ir.WRITE_DICT_(var_nf, final_feat)
205

Lingfan Yu's avatar
Lingfan Yu committed
206
207
208
209
def schedule_apply_nodes(graph,
                         v,
                         apply_func,
                         inplace):
210
211
212
213
214
215
216
217
218
219
    """get apply nodes schedule

    Parameters
    ----------
    graph: DGLGraph
        The DGLGraph to use
    v : utils.Index
        Nodes to apply
    apply_func: callable
        The apply node function
Lingfan Yu's avatar
Lingfan Yu committed
220
221
    inplace: bool
        If True, the update will be done in place
222
223
224
225
226
227
228
229
230

    Returns
    -------
    A list of executors for DGL Runtime
    """
    var_nf = var.FEAT_DICT(graph._node_frame, name='nf')
    var_v = var.IDX(v)
    v_nf = ir.READ_ROW(var_nf, var_v)
    def _afunc_wrapper(node_data):
Minjie Wang's avatar
Minjie Wang committed
231
232
        nbatch = NodeBatch(graph, v, node_data)
        return apply_func(nbatch)
233
234
    afunc = var.FUNC(_afunc_wrapper)
    applied_feat = ir.NODE_UDF(afunc, v_nf)
Lingfan Yu's avatar
Lingfan Yu committed
235
236
237
238
    if inplace:
        ir.WRITE_ROW_INPLACE_(var_nf, var_v, applied_feat)
    else:
        ir.WRITE_ROW_(var_nf, var_v, applied_feat)
239

Da Zheng's avatar
Da Zheng committed
240
241
242
243
244
245
246
247
248
def schedule_nodeflow_apply_nodes(graph,
                                  layer_id,
                                  v,
                                  apply_func,
                                  inplace):
    """get apply nodes schedule in NodeFlow.

    Parameters
    ----------
249
250
    graph: NodeFlow
        The NodeFlow to use
Da Zheng's avatar
Da Zheng committed
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
    layer_id : int
        The layer where we apply node update function.
    v : utils.Index
        Nodes to apply
    apply_func: callable
        The apply node function
    inplace: bool
        If True, the update will be done in place

    Returns
    -------
    A list of executors for DGL Runtime
    """
    var_nf = var.FEAT_DICT(graph._get_node_frame(layer_id), name='nf')
    var_v = var.IDX(v)
    v_nf = ir.READ_ROW(var_nf, var_v)
    def _afunc_wrapper(node_data):
        nbatch = NodeBatch(graph, v, node_data)
        return apply_func(nbatch)
    afunc = var.FUNC(_afunc_wrapper)
    applied_feat = ir.NODE_UDF(afunc, v_nf)
272
    # TODO we need to avoid index_copy here.
Da Zheng's avatar
Da Zheng committed
273
274
275
276
277
    if inplace:
        ir.WRITE_ROW_INPLACE_(var_nf, var_v, applied_feat)
    else:
        ir.WRITE_ROW_(var_nf, var_v, applied_feat)

Lingfan Yu's avatar
Lingfan Yu committed
278
279
280
281
def schedule_apply_edges(graph,
                         u, v, eid,
                         apply_func,
                         inplace):
282
283
284
285
286
287
288
289
290
291
292
293
294
295
    """get apply edges schedule

    Parameters
    ----------
    graph: DGLGraph
        The DGLGraph to use
    u : utils.Index
        Source nodes of edges to apply
    v : utils.Index
        Destination nodes of edges to apply
    eid : utils.Index
        Ids of sending edges
    apply_func: callable
        The apply edge function
Lingfan Yu's avatar
Lingfan Yu committed
296
297
    inplace: bool
        If True, the update will be done in place
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313

    Returns
    -------
    A list of executors for DGL Runtime
    """
    # vars
    var_nf = var.FEAT_DICT(graph._node_frame, name='nf')
    var_ef = var.FEAT_DICT(graph._edge_frame, name='ef')
    var_u = var.IDX(u)
    var_v = var.IDX(v)
    var_eid = var.IDX(eid)
    # schedule apply edges
    fdsrc = ir.READ_ROW(var_nf, var_u)
    fddst = ir.READ_ROW(var_nf, var_v)
    fdedge = ir.READ_ROW(var_ef, var_eid)
    def _efunc_wrapper(src_data, edge_data, dst_data):
Minjie Wang's avatar
Minjie Wang committed
314
315
        ebatch = EdgeBatch(graph, (u, v, eid), src_data, edge_data, dst_data)
        return apply_func(ebatch)
316
317
    _efunc = var.FUNC(_efunc_wrapper)
    new_fdedge = ir.EDGE_UDF(_efunc, fdsrc, fdedge, fddst)
Lingfan Yu's avatar
Lingfan Yu committed
318
319
320
321
322
    if inplace:
        ir.WRITE_ROW_INPLACE_(var_ef, var_eid, new_fdedge)
    else:
        ir.WRITE_ROW_(var_ef, var_eid, new_fdedge)

Da Zheng's avatar
Da Zheng committed
323
324
325
326
327
328
329
330
def schedule_nodeflow_apply_edges(graph, block_id,
                                  u, v, eid,
                                  apply_func,
                                  inplace):
    """get apply edges schedule in NodeFlow.

    Parameters
    ----------
331
332
    graph: NodeFlow
        The NodeFlow to use
Da Zheng's avatar
Da Zheng committed
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
    block_id : int
        The block whose edges we apply edge update function.
    u : utils.Index
        Source nodes of edges to apply
    v : utils.Index
        Destination nodes of edges to apply
    eid : utils.Index
        Ids of sending edges
    apply_func: callable
        The apply edge function
    inplace: bool
        If True, the update will be done in place

    Returns
    -------
    A list of executors for DGL Runtime
    """
    # vars
    in_var_nf = var.FEAT_DICT(graph._get_node_frame(block_id), name='in_nf')
    out_var_nf = var.FEAT_DICT(graph._get_node_frame(block_id + 1), name='out_nf')
    var_ef = var.FEAT_DICT(graph._get_edge_frame(block_id), name='ef')
    var_u = var.IDX(u)
    var_v = var.IDX(v)
    var_eid = var.IDX(eid)
    # schedule apply edges
    fdsrc = ir.READ_ROW(in_var_nf, var_u)
    fddst = ir.READ_ROW(out_var_nf, var_v)
    fdedge = ir.READ_ROW(var_ef, var_eid)
    def _efunc_wrapper(src_data, edge_data, dst_data):
        ebatch = EdgeBatch(graph, (u, v, eid), src_data, edge_data, dst_data)
        return apply_func(ebatch)
    _efunc = var.FUNC(_efunc_wrapper)
    new_fdedge = ir.EDGE_UDF(_efunc, fdsrc, fdedge, fddst)
366
    # TODO we need to avoid index_copy here.
Da Zheng's avatar
Da Zheng committed
367
368
369
370
371
    if inplace:
        ir.WRITE_ROW_INPLACE_(var_ef, var_eid, new_fdedge)
    else:
        ir.WRITE_ROW_(var_ef, var_eid, new_fdedge)

Lingfan Yu's avatar
Lingfan Yu committed
372
373
374
375
376
377
def schedule_push(graph,
                  u,
                  message_func,
                  reduce_func,
                  apply_func,
                  inplace):
378
379
380
381
382
383
384
385
386
387
388
389
390
391
    """get push schedule

    Parameters
    ----------
    graph: DGLGraph
        The DGLGraph to use
    u : utils.Index
        Source nodes for push
    message_func: callable or list of callable
        The message function
    reduce_func: callable or list of callable
        The reduce function
    apply_func: callable
        The apply node function
Lingfan Yu's avatar
Lingfan Yu committed
392
393
    inplace: bool
        If True, the update will be done in place
394
395
396
    """
    u, v, eid = graph._graph.out_edges(u)
    if len(eid) == 0:
397
398
        # All the pushing nodes have no out edges. No computation is scheduled.
        return
Lingfan Yu's avatar
Lingfan Yu committed
399
400
401
402
403
404
405
406
407
    schedule_snr(graph, (u, v, eid),
                 message_func, reduce_func, apply_func, inplace)

def schedule_pull(graph,
                  pull_nodes,
                  message_func,
                  reduce_func,
                  apply_func,
                  inplace):
408
409
410
411
412
413
    """get pull schedule

    Parameters
    ----------
    graph: DGLGraph
        The DGLGraph to use
414
    pull_nodes : utils.Index
415
416
417
418
419
420
421
        Destination nodes for pull
    message_func: callable or list of callable
        The message function
    reduce_func: callable or list of callable
        The reduce function
    apply_func: callable
        The apply node function
Lingfan Yu's avatar
Lingfan Yu committed
422
423
    inplace: bool
        If True, the update will be done in place
424
    """
425
426
    # TODO(minjie): `in_edges` can be omitted if message and reduce func pairs
    #   can be specialized to SPMV. This needs support for creating adjmat
427
    #   directly from pull node frontier.
428
    u, v, eid = graph._graph.in_edges(pull_nodes)
429
    if len(eid) == 0:
430
431
        # All the nodes are 0deg; downgrades to apply.
        if apply_func is not None:
Lingfan Yu's avatar
Lingfan Yu committed
432
            schedule_apply_nodes(graph, pull_nodes, apply_func, inplace)
433
434
435
436
437
438
439
440
441
442
    else:
        pull_nodes, _ = F.sort_1d(F.unique(pull_nodes.tousertensor()))
        pull_nodes = utils.toindex(pull_nodes)
        # create vars
        var_nf = var.FEAT_DICT(graph._node_frame, name='nf')
        var_pull_nodes = var.IDX(pull_nodes, name='pull_nodes')
        var_u = var.IDX(u)
        var_v = var.IDX(v)
        var_eid = var.IDX(eid)
        # generate send and reduce schedule
Minjie Wang's avatar
Minjie Wang committed
443
        uv_getter = lambda: (var_u, var_v)
Da Zheng's avatar
Da Zheng committed
444
        adj_creator = lambda: spmv.build_adj_matrix_uv((u, v), pull_nodes, graph.number_of_nodes())
Minjie Wang's avatar
Minjie Wang committed
445
        inc_creator = lambda: spmv.build_inc_matrix_dst(v, pull_nodes)
Da Zheng's avatar
Da Zheng committed
446
447
        reduced_feat = _gen_send_reduce(graph, graph._node_frame, graph._node_frame,
                                        graph._edge_frame, message_func, reduce_func,
Minjie Wang's avatar
Minjie Wang committed
448
449
                                        var_eid, var_pull_nodes,
                                        uv_getter, adj_creator, inc_creator)
450
451
        # generate optional apply
        final_feat = _apply_with_accum(graph, var_pull_nodes, var_nf, reduced_feat, apply_func)
Lingfan Yu's avatar
Lingfan Yu committed
452
453
454
455
        if inplace:
            ir.WRITE_ROW_INPLACE_(var_nf, var_pull_nodes, final_feat)
        else:
            ir.WRITE_ROW_(var_nf, var_pull_nodes, final_feat)
456

457
458
459
460
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
def schedule_group_apply_edge(graph,
                              u, v, eid,
                              apply_func,
                              group_by,
                              inplace):
    """group apply edges schedule

    Parameters
    ----------
    graph: DGLGraph
        The DGLGraph to use
    u : utils.Index
        Source nodes of edges to apply
    v : utils.Index
        Destination nodes of edges to apply
    eid : utils.Index
        Ids of sending edges
    apply_func: callable
        The apply edge function
    group_by : str
        Specify how to group edges. Expected to be either 'src' or 'dst'
    inplace: bool
        If True, the update will be done in place

    Returns
    -------
    A list of executors for DGL Runtime
    """
    # vars
    var_nf = var.FEAT_DICT(graph._node_frame, name='nf')
    var_ef = var.FEAT_DICT(graph._edge_frame, name='ef')
    var_out = var.FEAT_DICT(name='new_ef')
    # TODO (lingfan): check if apply_func is a DGL builtin
    db.gen_group_apply_edge_schedule(graph, apply_func, u, v, eid, group_by,
                                     var_nf, var_ef, var_out)
    var_eid = var.IDX(eid)
    if inplace:
        ir.WRITE_ROW_INPLACE_(var_ef, var_eid, var_out)
    else:
        ir.WRITE_ROW_(var_ef, var_eid, var_out)

498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544

def schedule_nodeflow_update_all(graph,
                                 block_id,
                                 message_func,
                                 reduce_func,
                                 apply_func):
    """get update_all schedule in a block.

    Parameters
    ----------
    graph: NodeFlow
        The NodeFlow to use
    block_id : int
        The block where we perform computation.
    message_func: callable or list of callable
        The message function
    reduce_func: callable or list of callable
        The reduce function
    apply_func: callable
        The apply node function
    """
    # A NodeFlow shouldn't have 0 edges.
    assert graph.block_size(block_id) > 0
    eid = utils.toindex(slice(0, graph.block_size(block_id)))  # shortcut for ALL
    dest_nodes = utils.toindex(slice(0, graph.layer_size(block_id + 1)))  # shortcut for ALL
    # create vars
    var_nf = var.FEAT_DICT(graph._get_node_frame(block_id + 1), name='out_nf')
    var_dest_nodes = var.IDX(dest_nodes, name='dest_nodes')
    var_eid = var.IDX(eid)
    # generate send + reduce
    def uv_getter():
        # TODO get all edges in the block.
        src, dst, _ = graph.block_edges(block_id)
        return var.IDX(utils.toindex(src)), var.IDX(utils.toindex(dst))
    adj_creator = lambda: spmv.build_block_adj_matrix_graph(graph, block_id)
    inc_creator = lambda: spmv.build_block_inc_matrix_graph(graph, block_id)
    reduced_feat = _gen_send_reduce(graph, graph._get_node_frame(block_id),
                                    graph._get_node_frame(block_id + 1),
                                    graph._get_edge_frame(block_id),
                                    message_func, reduce_func,
                                    var_eid, var_dest_nodes,
                                    uv_getter, adj_creator, inc_creator)
    # generate optional apply
    final_feat = _apply_with_accum(graph, var_dest_nodes, var_nf, reduced_feat, apply_func)
    ir.WRITE_DICT_(var_nf, final_feat)


Da Zheng's avatar
Da Zheng committed
545
546
547
548
549
550
551
552
553
554
555
556
def schedule_nodeflow_compute(graph,
                              block_id,
                              u, v, eid,
                              dest_nodes,
                              message_func,
                              reduce_func,
                              apply_func,
                              inplace):
    """get flow compute schedule in NodeFlow

    Parameters
    ----------
557
558
    graph: NodeFlow
        The NodeFlow to use
Da Zheng's avatar
Da Zheng committed
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
    block_id : int
        The block where we perform computation.
    u : utils.Index
        Source nodes of edges to apply
    v : utils.Index
        Destination nodes of edges to apply
    eid : utils.Index
        Ids of sending edges
    message_func: callable or list of callable
        The message function
    reduce_func: callable or list of callable
        The reduce function
    apply_func: callable
        The apply node function
    inplace: bool
        If True, the update will be done in place
    """
    # TODO(minjie): `in_edges` can be omitted if message and reduce func pairs
    #   can be specialized to SPMV. This needs support for creating adjmat
    #   directly from pull node frontier.
    if len(eid) == 0:
        # All the nodes are 0deg; downgrades to apply.
        if apply_func is not None:
582
            schedule_nodeflow_apply_nodes(graph, block_id + 1, dest_nodes, apply_func, inplace)
Da Zheng's avatar
Da Zheng committed
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
    else:
        # create vars
        var_nf = var.FEAT_DICT(graph._get_node_frame(block_id + 1), name='out_nf')
        var_dest_nodes = var.IDX(dest_nodes, name='dest_nodes')
        var_u = var.IDX(u)
        var_v = var.IDX(v)
        var_eid = var.IDX(eid)
        # generate send and reduce schedule
        uv_getter = lambda: (var_u, var_v)
        adj_creator = lambda: spmv.build_adj_matrix_uv((u, v), dest_nodes,
                                                       graph.layer_size(block_id))
        inc_creator = lambda: spmv.build_inc_matrix_dst(v, dest_nodes)
        reduced_feat = _gen_send_reduce(graph, graph._get_node_frame(block_id),
                                        graph._get_node_frame(block_id + 1),
                                        graph._get_edge_frame(block_id),
                                        message_func, reduce_func,
                                        var_eid, var_dest_nodes,
                                        uv_getter, adj_creator, inc_creator)
        # generate optional apply
        final_feat = _apply_with_accum(graph, var_dest_nodes, var_nf, reduced_feat, apply_func)
        if inplace:
            ir.WRITE_ROW_INPLACE_(var_nf, var_dest_nodes, final_feat)
        else:
            ir.WRITE_ROW_(var_nf, var_dest_nodes, final_feat)
607

608
609
610
611
612
613
614
def _check_builtin_func_list(func_list):
    """Check whether func_list only contains builtin functions."""
    for fn in func_list:
        if not isinstance(fn, BuiltinFunction):
            raise DGLError("If specify multiple message/reduce functions, \
                           all of them must be builtin")

615
def _standardize_func_usage(func, func_name):
616
617
618
619
620
621
622
623
624
625
626
627
628
629
    """Standardize usages of message and reduce functions
    Message or reduce funtion can be:
        1. a UDF
        2. a dgl builtin function
        3. a list of dgl builtin function

    This function checks if func meets the requirement, and merges last two cases
    by putting builtin function in case 2 into a list

    Returns:
    One single UDF function or a list of builtin function
    """

    if utils.is_iterable(func):
630
        # func is a list of builtin
631
632
633
634
635
636
        _check_builtin_func_list(func)
        return func
    elif isinstance(func, BuiltinFunction):
        # func is one builtin-in
        return [func]
    else:
637
638
639
640
        # func is one UDF
        if not callable(func):
            raise DGLError('User-defined %s function must be callable.'
                           ' Got: %s' % (func_name, str(func)))
641
642
        return func

643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
def _apply_with_accum(graph, var_nodes, var_nf, var_accum, apply_func):
    """Apply with accumulated features.

    Paramters
    ---------
    var_nodes : var.IDX
        The nodes.
    var_nf : var.FEAT_DICT
        The node features.
    var_accum : var.FEAT_DICT
        The accumulated features.
    apply_func : callable, None
        The apply function.
    """
    if apply_func:
        # To avoid writing reduced features back to node frame and reading
        # it again for apply phase. Instead, we first read the the node
        # features and "merge" it with the reduced features.
        v_nf = ir.READ_ROW(var_nf, var_nodes)
        v_nf = ir.UPDATE_DICT(v_nf, var_accum)
        def _afunc_wrapper(node_data):
Minjie Wang's avatar
Minjie Wang committed
664
665
            nbatch = NodeBatch(graph, var_nodes.data, node_data)
            return apply_func(nbatch)
666
667
668
669
670
671
672
673
674
675
676
677
678
679
        afunc = var.FUNC(_afunc_wrapper)
        applied_feat = ir.NODE_UDF(afunc, v_nf)
        final_feat = ir.UPDATE_DICT(var_accum, applied_feat)
    else:
        final_feat = var_accum
    return final_feat

def _gen_reduce(graph, reduce_func, edge_tuples, recv_nodes):
    """
    graph : DGLGraph
    reduce_func : callable
    edge_tuples : tuple of utils.Index
    recv_nodes : utils.Index
    """
680
    _, dst, eid = edge_tuples
681
682
683
684
685
    rfunc = _standardize_func_usage(reduce_func, 'reduce')
    rfunc_is_list = utils.is_iterable(rfunc)
    # Create a tmp frame to hold the feature data.
    # The frame has the same size and schemes of the
    # node frame.
686
687
    # TODO(minjie): should replace this with an IR call to make the program
    # stateless.
688
689
690
    tmpframe = FrameRef(frame_like(graph._node_frame._frame, len(recv_nodes)))

    # vars
Minjie Wang's avatar
Minjie Wang committed
691
692
693
    var_msg = var.FEAT_DICT(graph._msg_frame, 'msg')
    var_nf = var.FEAT_DICT(graph._node_frame, 'nf')
    var_out = var.FEAT_DICT(data=tmpframe)
694
695
696
697
698

    if rfunc_is_list:
        # UDF message + builtin reducer
        # analyze e2v spmv
        spmv_rfunc, rfunc = spmv.analyze_e2v_spmv(graph, rfunc)
699
700
        inc = spmv.build_inc_matrix_eid(graph._msg_frame.num_rows, eid, dst,
                                        recv_nodes)
Minjie Wang's avatar
Minjie Wang committed
701
        spmv.gen_e2v_spmv_schedule(inc, spmv_rfunc, var_msg, var_out)
702
703
704

        if len(rfunc) == 0:
            # All mfunc and rfunc has been processed.
Minjie Wang's avatar
Minjie Wang committed
705
            return var_out
706
707
708
709
710

        # convert the remaining rfunc to UDFs
        rfunc = BundledFunction(rfunc)

    # gen degree bucketing schedule for UDF recv
711
    db.gen_degree_bucketing_schedule(graph, rfunc, eid, dst,
Minjie Wang's avatar
Minjie Wang committed
712
713
                                     recv_nodes, var_nf, var_msg, var_out)
    return var_out
714
715
716

def _gen_send_reduce(
        graph,
Da Zheng's avatar
Da Zheng committed
717
718
719
        src_node_frame,
        dst_node_frame,
        edge_frame,
720
721
        message_func,
        reduce_func,
722
723
724
725
726
        var_send_edges,
        var_reduce_nodes,
        uv_getter,
        adj_creator,
        inc_creator):
727
728
729
730
731
    """Generate send and reduce schedule.

    This guarantees that the returned reduced features are batched
    in the *unique-ascending* order of the edge destination node ids.

732
733
    Parameters
    ----------
734
    graph : DGLGraph
735
        The graph
Da Zheng's avatar
Da Zheng committed
736
737
738
739
740
741
    src_node_frame : NodeFrame
        The node frame of the source nodes.
    dst_node_frame : NodeFrame
        The node frame of the destination nodes.
    edge_frame : NodeFrame
        The frame for the edges between the source and destination nodes.
742
    message_func : callable, list of builtins
743
        The message func(s).
744
    reduce_func : callable, list of builtins
745
746
747
748
749
750
751
752
        The reduce func(s).
    var_send_edges : var.IDX
        The edges (ids) to perform send.
    var_reduce_nodes : var.IDX
        The nodes to perform reduce. This should include unique(v) + 0deg nodes.
    uv_getter : callable
        A function that returns a pair of var.IDX (u, v) for the triggered edges.
    adj_creator : callable
753
        A function that returns the adjmat and the shuffle index.
754
    inc_creator : callable
755
        A function that returns the incmat and the shuffle index.
756
757
758
759
760

    Returns
    -------
    var.FEAT_DICT
        The reduced feature dict.
761
    """
762
763
764
    # NOTE: currently, this function requires all var.IDX to contain concrete data.
    reduce_nodes = var_reduce_nodes.data

765
    # arg vars
Da Zheng's avatar
Da Zheng committed
766
767
768
    var_src_nf = var.FEAT_DICT(src_node_frame, name='nf')
    var_dst_nf = var.FEAT_DICT(dst_node_frame, name='nf')
    var_ef = var.FEAT_DICT(edge_frame, name='ef')
769
    var_eid = var_send_edges
770
771
772
773
774
775
776
777
778
779
780

    # format the input functions
    mfunc = _standardize_func_usage(message_func, 'message')
    rfunc = _standardize_func_usage(reduce_func, 'reduce')
    mfunc_is_list = utils.is_iterable(mfunc)
    rfunc_is_list = utils.is_iterable(rfunc)

    # Create a tmp frame to hold the feature data.
    # The frame has the same size and schemes of the
    # node frame.
    # TODO(minjie): should replace this with an IR call to make the program stateless.
Da Zheng's avatar
Da Zheng committed
781
    tmpframe = FrameRef(frame_like(dst_node_frame._frame, len(reduce_nodes)))
782
783
784
785
786
787
    var_out = var.FEAT_DICT(data=tmpframe)

    if mfunc_is_list and rfunc_is_list:
        # builtin message + builtin reducer
        # analyze v2v spmv
        spmv_pairs, mfunc, rfunc = spmv.analyze_v2v_spmv(graph, mfunc, rfunc)
788
        adj = adj_creator()
Da Zheng's avatar
Da Zheng committed
789
        spmv.gen_v2v_spmv_schedule(adj, spmv_pairs, var_src_nf, var_ef, var_eid, var_out)
790
791
792
793
794
795
796
797
798
799
800
801

        if len(mfunc) == 0:
            # All mfunc and rfunc have been converted to v2v spmv.
            return var_out

    if mfunc_is_list:
        # Two cases:
        #  - mfunc is builtin while rfunc is UDF.
        #  - mfunc and rfunc are both builtin but some combinations
        #    fall through from the v2v spmv analysis.
        # In both cases, convert the mfunc to UDF.
        mfunc = BundledFunction(mfunc)
Lingfan Yu's avatar
Lingfan Yu committed
802

803
    # generate UDF send schedule
804
    var_u, var_v = uv_getter()
Da Zheng's avatar
Da Zheng committed
805
    var_mf = _gen_send(graph, var_src_nf, var_dst_nf, var_ef, var_u, var_v, var_eid, mfunc)
806
807
808
809
810

    if rfunc_is_list:
        # UDF message + builtin reducer
        # analyze e2v spmv
        spmv_rfunc, rfunc = spmv.analyze_e2v_spmv(graph, rfunc)
811
        inc = inc_creator()
812
813
814
815
816
817
818
819
820
821
822
        spmv.gen_e2v_spmv_schedule(inc, spmv_rfunc, var_mf, var_out)

        if len(rfunc) == 0:
            # All mfunc and rfunc has been processed.
            return var_out

        # convert the remaining rfunc to UDFs
        rfunc = BundledFunction(rfunc)

    # gen degree bucketing schedule for UDF recv
    mid = utils.toindex(slice(0, len(var_v.data)))  # message id is from 0~|dst|
Minjie Wang's avatar
Minjie Wang committed
823
    db.gen_degree_bucketing_schedule(
Da Zheng's avatar
Da Zheng committed
824
        graph, rfunc, mid, var_v.data, reduce_nodes, var_dst_nf, var_mf, var_out)
825
826
    return var_out

Da Zheng's avatar
Da Zheng committed
827
def _gen_send(graph, src_nfr, dst_nfr, efr, u, v, eid, mfunc):
Minjie Wang's avatar
Minjie Wang committed
828
    """Internal function to generate send schedule."""
Da Zheng's avatar
Da Zheng committed
829
830
    fdsrc = ir.READ_ROW(src_nfr, u)
    fddst = ir.READ_ROW(dst_nfr, v)
Minjie Wang's avatar
Minjie Wang committed
831
    fdedge = ir.READ_ROW(efr, eid)
832
    def _mfunc_wrapper(src_data, edge_data, dst_data):
Minjie Wang's avatar
Minjie Wang committed
833
834
835
        ebatch = EdgeBatch(graph, (u.data, v.data, eid.data),
                           src_data, edge_data, dst_data)
        return mfunc(ebatch)
836
837
838
839
    _mfunc_wrapper = var.FUNC(_mfunc_wrapper)
    msg = ir.EDGE_UDF(_mfunc_wrapper, fdsrc, fdedge, fddst)
    return msg

840
_init_api("dgl.runtime.scheduler")