graph.py 34.1 KB
Newer Older
1
2
"""Base graph class specialized for neural networks on graphs.
"""
3
from __future__ import absolute_import
4

5
from collections import MutableMapping
6
7
8
import networkx as nx
from networkx.classes.digraph import DiGraph

Minjie Wang's avatar
Minjie Wang committed
9
from dgl.base import ALL, is_all
10
11
import dgl.backend as F
from dgl.backend import Tensor
12
13
import dgl.builtin as builtin
from dgl.cached_graph import CachedGraph, create_cached_graph
Minjie Wang's avatar
Minjie Wang committed
14
15
import dgl.context as context
from dgl.frame import Frame
16
import dgl.scheduler as scheduler
17
18
import dgl.utils as utils

19
20
__MSG__ = "__MSG__"
__REPR__ = "__REPR__"
Minjie Wang's avatar
Minjie Wang committed
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

class _NodeDict(MutableMapping):
    def __init__(self, cb):
        self._dict = {}
        self._cb = cb
    def __setitem__(self, key, val):
        if isinstance(val, _AdjInnerDict):
            # This node dict is used as adj_outer_list
            val.src = key
        elif key not in self._dict:
            self._cb(key)
        self._dict[key] = val
    def __getitem__(self, key):
        return self._dict[key]
    def __delitem__(self, key):
        del self._dict[key]
    def __len__(self):
        return len(self._dict)
    def __iter__(self):
        return iter(self._dict)

class _AdjInnerDict(MutableMapping):
    def __init__(self, cb):
        self._dict = {}
        self.src = None
        self._cb = cb
    def __setitem__(self, key, val):
        if key not in self._dict:
            self._cb(self.src, key)
        self._dict[key] = val
    def __getitem__(self, key):
        return self._dict[key]
    def __delitem__(self, key):
        del self._dict[key]
    def __len__(self):
        return len(self._dict)
    def __iter__(self):
        return iter(self._dict)
59
60
61
62

class DGLGraph(DiGraph):
    """Base graph class specialized for neural networks on graphs.

63
64
    TODO(minjie): document of batching semantics
    TODO(minjie): document of __REPR__ semantics
65
66
67
68
69
70
71
72
73

    Parameters
    ----------
    data : graph data
        Data to initialize graph. Same as networkx's semantics.
    attr : keyword arguments, optional
        Attributes to add to graph as key=value pairs.
    """
    def __init__(self, graph_data=None, **attr):
Minjie Wang's avatar
Minjie Wang committed
74
75
76
77
78
79
80
81
        # setup dict overlay
        self.node_dict_factory = lambda : _NodeDict(self._add_node_callback)
        # In networkx 2.1, DiGraph is not using this factory. Instead, the outer
        # dict uses the same data structure as the node dict.
        self.adjlist_outer_dict_factory = None
        self.adjlist_inner_dict_factory = lambda : _AdjInnerDict(self._add_edge_callback)
        self.edge_attr_dict_factory = dict
        # cached graph and storage
82
83
84
85
86
87
88
89
90
91
        self._cached_graph = None
        self._node_frame = Frame()
        self._edge_frame = Frame()
        # other class members
        self._msg_graph = None
        self._msg_frame = Frame()
        self._message_func = None
        self._reduce_func = None
        self._update_func = None
        self._edge_func = None
Minjie Wang's avatar
Minjie Wang committed
92
93
94
95
96
        self._edge_cb_state = True
        self._edge_list = []
        self._context = context.cpu()
        # call base class init
        super(DGLGraph, self).__init__(graph_data, **attr)
97
98
99
100
101
102
103
104
105
106
107

    def set_n_repr(self, hu, u=ALL):
        """Set node(s) representation.

        To set multiple node representations at once, pass `u` with a tensor or
        a supported container of node ids. In this case, `hu` must be a tensor
        of shape (B, D1, D2, ...), where B is the number of the nodes and
        (D1, D2, ...) is the shape of the node representation tensor.

        Dictionary type is also supported for `hu`. In this case, each item
        will be treated as separate attribute of the nodes.
108

109
110
        Parameters
        ----------
Minjie Wang's avatar
Minjie Wang committed
111
        hu : tensor or dict of tensor
112
113
114
115
116
117
118
119
          Node representation.
        u : node, container or tensor
          The node(s).
        """
        # sanity check
        if isinstance(u, str) and u == ALL:
            num_nodes = self.number_of_nodes()
        else:
Minjie Wang's avatar
Minjie Wang committed
120
            u = utils.convert_to_id_tensor(u, self.context)
121
122
123
124
125
            num_nodes = len(u)
        if isinstance(hu, dict):
            for key, val in hu.items():
                assert F.shape(val)[0] == num_nodes
        else:
Minjie Wang's avatar
Minjie Wang committed
126
            assert F.shape(hu)[0] == num_nodes
127
128
129
130
131
132
133
134
135
136
        # set
        if isinstance(u, str) and u == ALL:
            if isinstance(hu, dict):
                for key, val in hu.items():
                    self._node_frame[key] = val
            else:
                self._node_frame[__REPR__] = hu
        else:
            if isinstance(hu, dict):
                for key, val in hu.items():
137
                    self._node_frame[key] = F.scatter_row(self._node_frame[key], u, val)
138
            else:
139
                self._node_frame[__REPR__] = F.scatter_row(self._node_frame[__REPR__], u, hu)
140

141
142
    def get_n_repr(self, u=ALL):
        """Get node(s) representation.
143

144
145
146
147
148
149
150
151
152
153
154
        Parameters
        ----------
        u : node, container or tensor
          The node(s).
        """
        if isinstance(u, str) and u == ALL:
            if len(self._node_frame) == 1 and __REPR__ in self._node_frame:
                return self._node_frame[__REPR__]
            else:
                return dict(self._node_frame)
        else:
Minjie Wang's avatar
Minjie Wang committed
155
            u = utils.convert_to_id_tensor(u, self.context)
156
157
158
159
            if len(self._node_frame) == 1 and __REPR__ in self._node_frame:
                return self._node_frame[__REPR__][u]
            else:
                return self._node_frame.select_rows(u)
Minjie Wang's avatar
Minjie Wang committed
160

Minjie Wang's avatar
Minjie Wang committed
161
162
163
164
165
166
167
168
169
170
    def pop_n_repr(self, key=__REPR__):
        """Get and remove the specified node repr.

        Parameters
        ----------
        key : str
          The attribute name.
        """
        return self._node_frame.pop(key)

171
172
    def set_e_repr(self, h_uv, u=ALL, v=ALL):
        """Set edge(s) representation.
Minjie Wang's avatar
Minjie Wang committed
173

174
175
176
177
        To set multiple edge representations at once, pass `u` and `v` with tensors or
        supported containers of node ids. In this case, `h_uv` must be a tensor
        of shape (B, D1, D2, ...), where B is the number of the edges and
        (D1, D2, ...) is the shape of the edge representation tensor.
178

179
180
        Dictionary type is also supported for `h_uv`. In this case, each item
        will be treated as separate attribute of the edges.
181

182
183
        Parameters
        ----------
Minjie Wang's avatar
Minjie Wang committed
184
        h_uv : tensor or dict of tensor
185
186
187
188
189
190
191
192
193
194
195
196
197
          Edge representation.
        u : node, container or tensor
          The source node(s).
        v : node, container or tensor
          The destination node(s).
        """
        # sanity check
        u_is_all = isinstance(u, str) and u == ALL
        v_is_all = isinstance(v, str) and v == ALL
        assert u_is_all == v_is_all
        if u_is_all:
            num_edges = self.number_of_edges()
        else:
Minjie Wang's avatar
Minjie Wang committed
198
199
            u = utils.convert_to_id_tensor(u, self.context)
            v = utils.convert_to_id_tensor(v, self.context)
200
201
202
203
204
            num_edges = max(len(u), len(v))
        if isinstance(h_uv, dict):
            for key, val in h_uv.items():
                assert F.shape(val)[0] == num_edges
        else:
Minjie Wang's avatar
Minjie Wang committed
205
            assert F.shape(h_uv)[0] == num_edges
206
207
208
209
210
211
212
213
214
215
216
        # set
        if u_is_all:
            if isinstance(h_uv, dict):
                for key, val in h_uv.items():
                    self._edge_frame[key] = val
            else:
                self._edge_frame[__REPR__] = h_uv
        else:
            eid = self.cached_graph.get_edge_id(u, v)
            if isinstance(h_uv, dict):
                for key, val in h_uv.items():
217
                    self._edge_frame[key] = F.scatter_row(self._edge_frame[key], eid, val)
218
            else:
219
                self._edge_frame[__REPR__] = F.scatter_row(self._edge_frame[__REPR__], eid, h_uv)
220

Minjie Wang's avatar
Minjie Wang committed
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
    def set_e_repr_by_id(self, h_uv, eid=ALL):
        """Set edge(s) representation by edge id.

        Parameters
        ----------
        h_uv : tensor or dict of tensor
          Edge representation.
        eid : int, container or tensor
          The edge id(s).
        """
        # sanity check
        if isinstance(eid, str) and eid == ALL:
            num_edges = self.number_of_edges()
        else:
            eid = utils.convert_to_id_tensor(eid, self.context)
            num_edges = len(eid)
        if isinstance(h_uv, dict):
            for key, val in h_uv.items():
                assert F.shape(val)[0] == num_edges
        else:
            assert F.shape(h_uv)[0] == num_edges
        # set
        if isinstance(eid, str) and eid == ALL:
            if isinstance(h_uv, dict):
                for key, val in h_uv.items():
                    self._edge_frame[key] = val
            else:
                self._edge_frame[__REPR__] = h_uv
        else:
            if isinstance(h_uv, dict):
                for key, val in h_uv.items():
252
                    self._edge_frame[key] = F.scatter_row(self._edge_frame[key], eid, val)
Minjie Wang's avatar
Minjie Wang committed
253
            else:
254
                self._edge_frame[__REPR__] = F.scatter_row(self._edge_frame[__REPR__], eid, h_uv)
Minjie Wang's avatar
Minjie Wang committed
255

256
257
    def get_e_repr(self, u=ALL, v=ALL):
        """Get node(s) representation.
258

259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
        Parameters
        ----------
        u : node, container or tensor
          The source node(s).
        v : node, container or tensor
          The destination node(s).
        """
        u_is_all = isinstance(u, str) and u == ALL
        v_is_all = isinstance(v, str) and v == ALL
        assert u_is_all == v_is_all
        if u_is_all:
            if len(self._edge_frame) == 1 and __REPR__ in self._edge_frame:
                return self._edge_frame[__REPR__]
            else:
                return dict(self._edge_frame)
        else:
Minjie Wang's avatar
Minjie Wang committed
275
276
            u = utils.convert_to_id_tensor(u, self.context)
            v = utils.convert_to_id_tensor(v, self.context)
277
278
279
280
281
282
            eid = self.cached_graph.get_edge_id(u, v)
            if len(self._edge_frame) == 1 and __REPR__ in self._edge_frame:
                return self._edge_frame[__REPR__][eid]
            else:
                return self._edge_frame.select_rows(eid)

Minjie Wang's avatar
Minjie Wang committed
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
    def pop_e_repr(self, key=__REPR__):
        """Get and remove the specified edge repr.

        Parameters
        ----------
        key : str
          The attribute name.
        """
        return self._edge_frame.pop(key)

    def get_e_repr_by_id(self, eid=ALL):
        """Get edge(s) representation by edge id.

        Parameters
        ----------
        eid : int, container or tensor
          The edge id(s).
        """
        if isinstance(eid, str) and eid == ALL:
            if len(self._edge_frame) == 1 and __REPR__ in self._edge_frame:
                return self._edge_frame[__REPR__]
            else:
                return dict(self._edge_frame)
        else:
            eid = utils.convert_to_id_tensor(eid, self.context)
            if len(self._edge_frame) == 1 and __REPR__ in self._edge_frame:
                return self._edge_frame[__REPR__][eid]
            else:
                return self._edge_frame.select_rows(eid)

    def set_device(self, ctx):
        """Set device context for this graph.

        Parameters
        ----------
        ctx : dgl.context.Context
          The device context.
        """
        self._context = ctx

    @property
    def context(self):
        """Get the device context of this graph."""
        return self._context

328
329
330
331
    def register_message_func(self,
                              message_func,
                              batchable=False):
        """Register global message function.
332
333
334
335
336
337
338
339

        Parameters
        ----------
        message_func : callable
          Message function on the edge.
        batchable : bool
          Whether the provided message function allows batch computing.
        """
340
        self._message_func = (message_func, batchable)
341
342
343

    def register_edge_func(self,
                           edge_func,
Minjie Wang's avatar
Minjie Wang committed
344
                           batchable=False):
345
        """Register global edge update function.
zzhang-cn's avatar
zzhang-cn committed
346
347
348
349
350
351
352
353

        Parameters
        ----------
        edge_func : callable
          Message function on the edge.
        batchable : bool
          Whether the provided message function allows batch computing.
        """
354
        self._edge_func = (edge_func, batchable)
zzhang-cn's avatar
zzhang-cn committed
355

356
357
    def register_reduce_func(self,
                             reduce_func,
Minjie Wang's avatar
Minjie Wang committed
358
                             batchable=False):
359
        """Register global message reduce function.
Lingfan Yu's avatar
Lingfan Yu committed
360
361
362
363
364
365
366
367

        Parameters
        ----------
        reduce_func : str or callable
          Reduce function on incoming edges.
        batchable : bool
          Whether the provided reduce function allows batch computing.
        """
368
        self._reduce_func = (reduce_func, batchable)
Lingfan Yu's avatar
Lingfan Yu committed
369

370
371
    def register_update_func(self,
                             update_func,
Minjie Wang's avatar
Minjie Wang committed
372
                             batchable=False):
373
        """Register global node update function.
374
375
376
377
378
379
380
381

        Parameters
        ----------
        update_func : callable
          Update function on the node.
        batchable : bool
          Whether the provided update function allows batch computing.
        """
382
        self._update_func = (update_func, batchable)
383

384
    def readout(self,
385
386
387
                readout_func,
                nodes=ALL,
                edges=ALL):
388
389
390
391
        """Trigger the readout function on the specified nodes/edges.

        Parameters
        ----------
392
393
        readout_func : callable
          Readout function.
394
395
396
397
398
399
        nodes : str, node, container or tensor
          The nodes to get reprs from.
        edges : str, pair of nodes, pair of containers or pair of tensors
          The edges to get reprs from.
        """
        nodes = self._nodes_or_all(nodes)
Minjie Wang's avatar
Minjie Wang committed
400
        edges = self._edges_or_all(edges)
401
402
        nstates = [self.nodes[n] for n in nodes]
        estates = [self.edges[e] for e in edges]
403
        return readout_func(nstates, estates)
404

405
    def sendto(self, u, v, message_func=None, batchable=False):
406
407
        """Trigger the message function on edge u->v

408
409
410
411
412
413
414
415
416
417
        The message function should be compatible with following signature:

        (node_reprs, edge_reprs) -> message

        It computes the representation of a message using the
        representations of the source node, and the edge u->v.
        All node_reprs and edge_reprs are dictionaries.
        The message function can be any of the pre-defined functions
        ('from_src').

418
419
420
421
422
423
        Parameters
        ----------
        u : node, container or tensor
          The source node(s).
        v : node, container or tensor
          The destination node(s).
424
425
426
427
        message_func : str or callable
          The message function.
        batchable : bool
          Whether the function allows batched computation.
428
        """
429
430
431
432
433
434
435
        if message_func is None:
            message_func, batchable = self._message_func
        assert message_func is not None
        if batchable:
            self._batch_sendto(u, v, message_func)
        else:
            self._nonbatch_sendto(u, v, message_func)
436

437
438
439
440
441
442
443
444
    def _nonbatch_sendto(self, u, v, message_func):
        f_msg = _get_message_func(message_func)
        for uu, vv in utils.edge_iter(u, v):
            ret = f_msg(_get_repr(self.nodes[uu]),
                        _get_repr(self.edges[uu, vv]))
            self.edges[uu, vv][__MSG__] = ret

    def _batch_sendto(self, u, v, message_func):
Minjie Wang's avatar
Minjie Wang committed
445
446
        if is_all(u) and is_all(v):
            u, v = self.cached_graph.edges()
447
448
        u = utils.convert_to_id_tensor(u)
        v = utils.convert_to_id_tensor(v)
Minjie Wang's avatar
Minjie Wang committed
449
        eid = self.cached_graph.get_edge_id(u, v)
450
451
452
        self.msg_graph.add_edges(u, v)
        if len(u) != len(v) and len(u) == 1:
            u = F.broadcast_to(u, v)
Minjie Wang's avatar
Minjie Wang committed
453
454
455
        # call UDF
        src_reprs = self.get_n_repr(u)
        edge_reprs = self.get_e_repr_by_id(eid)
456
457
458
459
460
461
462
        msgs = message_func(src_reprs, edge_reprs)
        if isinstance(msgs, dict):
            self._msg_frame.append(msgs)
        else:
            self._msg_frame.append({__MSG__ : msgs})

    def update_edge(self, u, v, edge_func=None, batchable=False):
zzhang-cn's avatar
zzhang-cn committed
463
464
        """Update representation on edge u->v

465
466
467
468
469
470
471
472
        The edge function should be compatible with following signature:

        (node_reprs, node_reprs, edge_reprs) -> edge_reprs

        It computes the new edge representations using the representations
        of the source node, target node and the edge itself.
        All node_reprs and edge_reprs are dictionaries.

zzhang-cn's avatar
zzhang-cn committed
473
474
475
476
477
478
        Parameters
        ----------
        u : node, container or tensor
          The source node(s).
        v : node, container or tensor
          The destination node(s).
479
480
481
482
        edge_func : str or callable
          The update function.
        batchable : bool
          Whether the function allows batched computation.
zzhang-cn's avatar
zzhang-cn committed
483
        """
484
485
486
487
488
489
490
        if edge_func is None:
            edge_func, batchable = self._edge_func
        assert edge_func is not None
        if batchable:
            self._batch_update_edge(u, v, edge_func)
        else:
            self._nonbatch_update_edge(u, v, edge_func)
zzhang-cn's avatar
zzhang-cn committed
491

492
493
494
495
496
497
498
499
500
501
    def _nonbatch_update_edge(self, u, v, edge_func):
        for uu, vv in utils.edge_iter(u, v):
            ret = edge_func(_get_repr(self.nodes[uu]),
                            _get_repr(self.nodes[vv]),
                            _get_repr(self.edges[uu, vv]))
            _set_repr(self.edges[uu, vv], ret)

    def _batch_update_edge(self, u, v, edge_func):
        u = utils.convert_to_id_tensor(u)
        v = utils.convert_to_id_tensor(v)
Minjie Wang's avatar
Minjie Wang committed
502
        eid = self.cached_graph.get_edge_id(u, v)
503
504
505
506
        if len(u) != len(v) and len(u) == 1:
            u = F.broadcast_to(u, v)
        elif len(u) != len(v) and len(v) == 1:
            v = F.broadcast_to(v, u)
Minjie Wang's avatar
Minjie Wang committed
507
508
509
510
        # call the UDF
        src_reprs = self.get_n_repr(u)
        dst_reprs = self.get_n_repr(v)
        edge_reprs = self.get_e_repr_by_id(eid)
511
        new_edge_reprs = edge_func(src_reprs, dst_reprs, edge_reprs)
Minjie Wang's avatar
Minjie Wang committed
512
        self.set_e_repr_by_id(new_edge_reprs, eid)
513
514
515
516
517
518

    def recv(self,
             u,
             reduce_func=None,
             update_func=None,
             batchable=False):
519
        """Receive in-coming messages and update representation on node u.
520

521
522
523
524
        It computes the new node state using the messages sent from the predecessors
        of node u. If no message is found from the predecessors, reduce function
        will be skipped and a None type will be provided as the reduced messages for
        the update function.
525

526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
        The reduce function should be compatible with following signature:

            (node_reprs, batched_messages) -> reduced_messages

        It computes the reduced edge representations using the representations
        of the in-coming edges (the same concept as messages).
        The reduce function can be any of the pre-defined functions ('sum',
        'max'). If built-in function is used, computation will be performed
        efficiently (using generic-SPMV kernels).

        The update function should be compatible with following signature:

            (node_reprs, reduced_messages) -> node_reprs

        It computes the new node representations using the representations
        of the in-coming edges (the same concept as messages) and the node
        itself. All node_reprs and edge_reprs are dictionaries.

544
545
546
547
        Parameters
        ----------
        u : node, container or tensor
          The node to be updated.
548
549
550
551
552
553
        reduce_func : str or callable
          The reduce function.
        update_func : str or callable
          The update function.
        batchable : bool
          Whether the reduce and update function allows batched computation.
554
        """
555
556
557
558
559
560
561
562
563
564
565
566
567
568
        if reduce_func is None:
            reduce_func, batchable = self._reduce_func
        if update_func is None:
            update_func, batchable = self._update_func
        assert reduce_func is not None
        assert update_func is not None
        if batchable:
            self._batch_recv(u, reduce_func, update_func)
        else:
            self._nonbatch_recv(u, reduce_func, update_func)

    def _nonbatch_recv(self, u, reduce_func, update_func):
        f_reduce = _get_reduce_func(reduce_func)
        f_update = update_func
569
        for i, uu in enumerate(utils.node_iter(u)):
Minjie Wang's avatar
Minjie Wang committed
570
            # reduce phase
571
572
573
574
575
576
577
            msgs_batch = [self.edges[vv, uu].pop(__MSG__)
                          for vv in self.pred[uu] if __MSG__ in self.edges[vv, uu]]
            if len(msgs_batch) == 0:
                msgs_reduced = None
            elif len(msgs_batch) == 1:
                msgs_reduced = msgs_batch[0]
            else:
578
                msgs_reduced = f_reduce(_get_repr(self.nodes[uu]), msgs_batch)
Minjie Wang's avatar
Minjie Wang committed
579
            # update phase
580
581
582
583
            ret = f_update(_get_repr(self.nodes[uu]), msgs_reduced)
            _set_repr(self.nodes[uu], ret)

    def _batch_recv(self, v, reduce_func, update_func):
Minjie Wang's avatar
Minjie Wang committed
584
585
586
        v_is_all = is_all(v)
        if v_is_all:
            v = list(range(self.number_of_nodes()))
587
588
589
590
591
592
593
594
595
596
597
        # sanity checks
        v = utils.convert_to_id_tensor(v)
        f_reduce = _get_reduce_func(reduce_func)
        f_update = update_func
        # degree bucketing
        degrees, v_buckets = scheduler.degree_bucketing(self.msg_graph, v)
        reduced_msgs = []
        for deg, v_bkt in zip(degrees, v_buckets):
            bkt_len = len(v_bkt)
            uu, vv = self.msg_graph.in_edges(v_bkt)
            in_msg_ids = self.msg_graph.get_edge_id(uu, vv)
Minjie Wang's avatar
Minjie Wang committed
598
599
            # TODO(minjie): manually convert ids to context.
            in_msg_ids = F.to_context(in_msg_ids, self.context)
600
601
602
603
604
605
606
607
608
609
610
            in_msgs = self._msg_frame.select_rows(in_msg_ids)
            # Reshape the column tensor to (B, Deg, ...).
            def _reshape_fn(msg):
                msg_shape = F.shape(msg)
                new_shape = (bkt_len, deg) + msg_shape[1:]
                return F.reshape(msg, new_shape)
            if len(in_msgs) == 1 and __MSG__ in in_msgs:
                reshaped_in_msgs = _reshape_fn(in_msgs[__MSG__])
            else:
                reshaped_in_msgs = utils.LazyDict(
                        lambda key: _reshape_fn(in_msgs[key]), self._msg_frame.schemes)
Minjie Wang's avatar
Minjie Wang committed
611
            dst_reprs = self.get_n_repr(v_bkt)
612
613
614
615
616
617
618
            reduced_msgs.append(f_reduce(dst_reprs, reshaped_in_msgs))

        # TODO: clear partial messages
        self.clear_messages()

        # Read the node states in the degree-bucketing order.
        reordered_v = F.pack(v_buckets)
Minjie Wang's avatar
Minjie Wang committed
619
        reordered_ns = self.get_n_repr(reordered_v)
620
        # Pack all reduced msgs together
Minjie Wang's avatar
Minjie Wang committed
621
        if isinstance(reduced_msgs[0], dict):
622
623
624
625
            all_reduced_msgs = {key : F.pack(val) for key, val in reduced_msgs.items()}
        else:
            all_reduced_msgs = F.pack(reduced_msgs)
        new_ns = f_update(reordered_ns, all_reduced_msgs)
Minjie Wang's avatar
Minjie Wang committed
626
627
628
629
630
631
632
633
634
635
636
637
638
        if v_is_all:
            # First do reorder and then replace the whole column.
            _, indices = F.sort(reordered_v)
            # TODO(minjie): manually convert ids to context.
            indices = F.to_context(indices, self.context)
            if isinstance(new_ns, dict):
                for key, val in new_ns.items():
                    self._node_frame[key] = F.gather_row(val, indices)
            else:
                self._node_frame[__REPR__] = F.gather_row(new_ns, indices)
        else:
            # Use setter to do reorder.
            self.set_n_repr(new_ns, reordered_v)
639
640
641
642
643
644
645

    def update_by_edge(self,
                       u, v,
                       message_func=None,
                       reduce_func=None,
                       update_func=None,
                       batchable=False):
646
647
648
649
650
651
652
653
        """Trigger the message function on u->v and update v.

        Parameters
        ----------
        u : node, container or tensor
          The source node(s).
        v : node, container or tensor
          The destination node(s).
654
655
656
657
658
659
660
661
        message_func : str or callable
          The message function.
        reduce_func : str or callable
          The reduce function.
        update_func : str or callable
          The update function.
        batchable : bool
          Whether the reduce and update function allows batched computation.
662
        """
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
        if message_func is None:
            message_func, batchable = self._message_func
        if reduce_func is None:
            reduce_func, batchable = self._reduce_func
        if update_func is None:
            update_func, batchable = self._update_func
        assert message_func is not None
        assert reduce_func is not None
        assert update_func is not None
        if batchable:
            self._batch_update_by_edge(
                    u, v, message_func, reduce_func, update_func)
        else:
            self._nonbatch_update_by_edge(
                    u, v, message_func, reduce_func, update_func)

    def _nonbatch_update_by_edge(
            self,
            u, v,
Minjie Wang's avatar
Minjie Wang committed
682
683
684
            message_func,
            reduce_func,
            update_func):
685
        self._nonbatch_sendto(u, v, message_func)
686
        dst = set()
687
        for uu, vv in utils.edge_iter(u, v):
688
            dst.add(vv)
689
690
691
692
693
        self._nonbatch_recv(list(dst), reduce_func, update_func)

    def _batch_update_by_edge(
            self,
            u, v,
Minjie Wang's avatar
Minjie Wang committed
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
            message_func,
            reduce_func,
            update_func):
        if message_func == 'from_src' and reduce_func == 'sum' \
                and is_all(u) and is_all(v):
            # TODO(minjie): SPMV is only supported for updating all nodes right now.
            adjmat = self.cached_graph.adjmat(self.context)
            reduced_msgs = {}
            for key in self._node_frame.schemes:
                col = self._node_frame[key]
                reduced_msgs[key] = F.spmm(adjmat, col)
            node_repr = self.get_n_repr()
            if len(reduced_msgs) == 1 and __REPR__ in reduced_msgs:
                reduced_msgs = reduced_msgs[__REPR__]
            self.set_n_repr(update_func(node_repr, reduced_msgs))
709
        else:
Minjie Wang's avatar
Minjie Wang committed
710
711
712
713
714
715
716
            if is_all(u) and is_all(v):
                self._batch_sendto(u, v, message_func)
                self._batch_recv(v, reduce_func, update_func)
            else:
                self._batch_sendto(u, v, message_func)
                unique_v = F.unique(v)
                self._batch_recv(unique_v, reduce_func, update_func)
717
718
719
720
721
722
723

    def update_to(self,
                  v,
                  message_func=None,
                  reduce_func=None,
                  update_func=None,
                  batchable=False):
724
725
726
727
        """Pull messages from the node's predecessors and then update it.

        Parameters
        ----------
728
        v : node, container or tensor
729
          The node to be updated.
730
731
732
733
734
735
736
737
        message_func : str or callable
          The message function.
        reduce_func : str or callable
          The reduce function.
        update_func : str or callable
          The update function.
        batchable : bool
          Whether the reduce and update function allows batched computation.
738
        """
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
        if message_func is None:
            message_func, batchable = self._message_func
        if reduce_func is None:
            reduce_func, batchable = self._reduce_func
        if update_func is None:
            update_func, batchable = self._update_func
        assert message_func is not None
        assert reduce_func is not None
        assert update_func is not None
        if batchable:
            uu, vv = self.cached_graph.in_edges(v)
            self.update_by_edge(uu, vv, message_func,
                    reduce_func, update_func, batchable)
        else:
            for vv in utils.node_iter(v):
                assert vv in self.nodes
                uu = list(self.pred[vv])
                self.sendto(uu, vv, message_func, batchable)
                self.recv(vv, reduce_func, update_func, batchable)

    def update_from(self,
                    u,
                    message_func=None,
                    reduce_func=None,
                    update_func=None,
                    batchable=False):
765
766
767
768
769
770
        """Send message from the node to its successors and update them.

        Parameters
        ----------
        u : node, container or tensor
          The node that sends out messages.
771
772
773
774
775
776
777
778
        message_func : str or callable
          The message function.
        reduce_func : str or callable
          The reduce function.
        update_func : str or callable
          The update function.
        batchable : bool
          Whether the reduce and update function allows batched computation.
779
        """
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
        if message_func is None:
            message_func, batchable = self._message_func
        if reduce_func is None:
            reduce_func, batchable = self._reduce_func
        if update_func is None:
            update_func, batchable = self._update_func
        assert message_func is not None
        assert reduce_func is not None
        assert update_func is not None
        if batchable:
            uu, vv = self.cached_graph.out_edges(u)
            self.update_by_edge(uu, vv, message_func,
                    reduce_func, update_func, batchable)
        else:
            for uu in utils.node_iter(u):
                assert uu in self.nodes
                for v in self.succ[uu]:
                    self.update_by_edge(uu, v,
                            message_func, reduce_func, update_func, batchable)

    def update_all(self,
                   message_func=None,
                   reduce_func=None,
                   update_func=None,
                   batchable=False):
805
806
        """Send messages through all the edges and update all nodes.

807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
        Parameters
        ----------
        message_func : str or callable
          The message function.
        reduce_func : str or callable
          The reduce function.
        update_func : str or callable
          The update function.
        batchable : bool
          Whether the reduce and update function allows batched computation.
        """
        if message_func is None:
            message_func, batchable = self._message_func
        if reduce_func is None:
            reduce_func, batchable = self._reduce_func
        if update_func is None:
            update_func, batchable = self._update_func
        assert message_func is not None
        assert reduce_func is not None
        assert update_func is not None
        if batchable:
Minjie Wang's avatar
Minjie Wang committed
828
            self._batch_update_by_edge(ALL, ALL,
829
830
831
832
833
834
835
836
837
838
839
840
841
842
                    message_func, reduce_func, update_func)
        else:
            u = [uu for uu, _ in self.edges]
            v = [vv for _, vv in self.edges]
            self._nonbatch_sendto(u, v, message_func)
            self._nonbatch_recv(list(self.nodes()), reduce_func, update_func)

    def propagate(self,
                  message_func=None,
                  reduce_func=None,
                  update_func=None,
                  batchable=False,
                  iterator='bfs',
                  **kwargs):
843
844
845
846
847
848
849
850
851
852
853
        """Propagate messages and update nodes using iterator.

        A convenient function for passing messages and updating
        nodes according to the iterator. The iterator can be
        any of the pre-defined iterators ('bfs', 'dfs', 'pre-order',
        'mid-order', 'post-order'). The computation will be unrolled
        in the backend efficiently. User can also provide custom
        iterator that generates the edges and nodes.

        Parameters
        ----------
854
855
856
857
858
859
860
861
        message_func : str or callable
          The message function.
        reduce_func : str or callable
          The reduce function.
        update_func : str or callable
          The update function.
        batchable : bool
          Whether the reduce and update function allows batched computation.
862
863
        iterator : str or generator of steps.
          The iterator of the graph.
864
865
        kwargs : keyword arguments, optional
            Arguments for pre-defined iterators.
866
867
868
869
870
871
872
        """
        if isinstance(iterator, str):
            # TODO Call pre-defined routine to unroll the computation.
            raise RuntimeError('Not implemented.')
        else:
            # NOTE: the iteration can return multiple edges at each step.
            for u, v in iterator:
873
874
                self.update_by_edge(u, v,
                        message_func, reduce_func, update_func, batchable)
875
876
877
878
879
880
881
882

    def draw(self):
        """Plot the graph using dot."""
        from networkx.drawing.nx_agraph import graphviz_layout

        pos = graphviz_layout(self, prog='dot')
        nx.draw(self, pos, with_labels=True)

883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
    @property
    def cached_graph(self):
        # TODO: dirty flag when mutated
        if self._cached_graph is None:
            self._cached_graph = create_cached_graph(self)
        return self._cached_graph

    @property
    def msg_graph(self):
        # TODO: dirty flag when mutated
        if self._msg_graph is None:
            self._msg_graph = CachedGraph()
            self._msg_graph.add_nodes(self.number_of_nodes())
        return self._msg_graph

    def clear_messages(self):
        if self._msg_graph is not None:
            self._msg_graph = CachedGraph()
            self._msg_graph.add_nodes(self.number_of_nodes())
            self._msg_frame.clear()

    def _nodes_or_all(self, nodes):
        return self.nodes() if nodes == ALL else nodes

    def _edges_or_all(self, edges):
        return self.edges() if edges == ALL else edges

Minjie Wang's avatar
Minjie Wang committed
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
    def _add_node_callback(self, node):
        self._cached_graph = None

    def _add_edge_callback(self, u, v):
        # In networkx 2.1, two adjlists are maintained. One for succ, one for pred.
        # We only record once for the succ addition.
        if self._edge_cb_state:
            #print('New edge:', u, v)
            self._edge_list.append((u, v))
        self._edge_cb_state = not self._edge_cb_state
        self._cached_graph = None

    @property
    def edge_list(self):
        """Return edges in the addition order."""
        return self._edge_list

927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
def _get_repr(attr_dict):
    if len(attr_dict) == 1 and __REPR__ in attr_dict:
        return attr_dict[__REPR__]
    else:
        return attr_dict

def _set_repr(attr_dict, attr):
    if isinstance(attr, dict):
        attr_dict.update(attr)
    else:
        attr_dict[__REPR__] = attr

def _get_reduce_func(reduce_func):
    if isinstance(reduce_func, str):
        # built-in reduce func
        if reduce_func == 'sum':
            return builtin.reduce_sum
        elif reduce_func == 'max':
            return builtin.reduce_max
Minjie Wang's avatar
Minjie Wang committed
946
        else:
947
948
949
950
951
952
953
954
955
            raise ValueError(
                    "Unknown built-in reduce function: %s" % reduce_func)
    return reduce_func

def _get_message_func(message_func):
    if isinstance(message_func, str):
        # built-in message func
        if message_func == 'from_src':
            return builtin.message_from_src
Minjie Wang's avatar
Minjie Wang committed
956
        else:
957
958
959
            raise ValueError(
                    "Unknown built-in message function: %s" % message_func)
    return message_func