instruction stringclasses 100
values | code stringlengths 78 193k | response stringlengths 259 170k | file stringlengths 59 203 |
|---|---|---|---|
Write documentation strings for class attributes |
import textwrap
from typing import Dict, Iterable, Tuple, Union
import torch
from .internal_utils import gb_warning
__all__ = ["ItemSet", "HeteroItemSet", "ItemSetDict"]
def is_scalar(x):
return (
len(x.shape) == 0 if isinstance(x, torch.Tensor) else isinstance(x, int)
)
class ItemSet:
def ... | --- +++ @@ -1,3 +1,4 @@+"""GraphBolt Itemset."""
import textwrap
from typing import Dict, Iterable, Tuple, Union
@@ -10,12 +11,123 @@
def is_scalar(x):
+ """Checks if the input is a scalar."""
return (
len(x.shape) == 0 if isinstance(x, torch.Tensor) else isinstance(x, int)
)
class It... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/graphbolt/itemset.py |
Create docstrings for all classes and functions | # pylint: disable= no-member, arguments-differ, invalid-name
import mxnet as mx
from mxnet.gluon import nn
from mxnet.gluon.contrib.nn import Identity
from .... import function as fn
from ....utils import expand_as_pair
class NNConv(nn.Block):
def __init__(
self,
in_feats,
out_feats,
... | --- +++ @@ -1,3 +1,4 @@+"""MXNet Module for NNConv layer"""
# pylint: disable= no-member, arguments-differ, invalid-name
import mxnet as mx
from mxnet.gluon import nn
@@ -8,6 +9,86 @@
class NNConv(nn.Block):
+ r"""Graph Convolution layer from `Neural Message Passing
+ for Quantum Chemistry <https://arxiv.o... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/nn/mxnet/conv/nnconv.py |
Add docstrings to my Python code | from mxnet import nd
from mxnet.gluon import nn
__all__ = ["HeteroGraphConv"]
class HeteroGraphConv(nn.Block):
def __init__(self, mods, aggregate="sum"):
super(HeteroGraphConv, self).__init__()
with self.name_scope():
for name, mod in mods.items():
self.register_child... | --- +++ @@ -1,3 +1,4 @@+"""Heterograph NN modules"""
from mxnet import nd
from mxnet.gluon import nn
@@ -5,6 +6,119 @@
class HeteroGraphConv(nn.Block):
+ r"""A generic module for computing convolution on heterogeneous graphs
+
+ The heterograph convolution applies sub-modules on their associating
+ rel... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/nn/mxnet/hetero.py |
Auto-generate documentation strings for this file |
# pylint: disable= invalid-name
from typing import Dict, NamedTuple, Tuple, Union
import torch
from .base import (
apply_to,
CSCFormatBase,
etype_str_to_tuple,
expand_indptr,
is_object_pinned,
isin,
)
from .internal_utils import recursive_apply
__all__ = ["SampledSubgraph"]
class _Exclud... | --- +++ @@ -1,3 +1,4 @@+"""Graphbolt sampled subgraph."""
# pylint: disable= invalid-name
from typing import Dict, NamedTuple, Tuple, Union
@@ -25,6 +26,7 @@ self.index = index
def wait(self):
+ """Returns the stored value when invoked."""
sampled_subgraph = self.sampled_subgraph
... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/graphbolt/sampled_subgraph.py |
Add docstrings that explain logic | # pylint: disable= no-member, arguments-differ, invalid-name
import math
import mxnet as mx
from mxnet import gluon
from .... import function as fn
class TAGConv(gluon.Block):
def __init__(self, in_feats, out_feats, k=2, bias=True, activation=None):
super(TAGConv, self).__init__()
self.out_feat... | --- +++ @@ -1,3 +1,4 @@+"""MXNet module for TAGConv"""
# pylint: disable= no-member, arguments-differ, invalid-name
import math
@@ -8,6 +9,57 @@
class TAGConv(gluon.Block):
+ r"""Topology Adaptive Graph Convolutional layer from `Topology
+ Adaptive Graph Convolutional Networks <https://arxiv.org/pdf/1710.... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/nn/mxnet/conv/tagconv.py |
Add verbose docstrings with examples | # pylint: disable=no-member, invalid-name
import numpy as np
from mxnet import gluon, nd
from ... import DGLGraph
def matmul_maybe_select(A, B):
if A.dtype in (np.int32, np.int64) and len(A.shape) == 1:
return nd.take(B, A, axis=0)
else:
return nd.dot(A, B)
def bmm_maybe_select(A, B, index... | --- +++ @@ -1,3 +1,4 @@+"""Utilities for pytorch NN package"""
# pylint: disable=no-member, invalid-name
import numpy as np
@@ -7,6 +8,41 @@
def matmul_maybe_select(A, B):
+ """Perform Matrix multiplication C = A * B but A could be an integer id vector.
+
+ If A is an integer vector, we treat it as multip... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/nn/mxnet/utils.py |
Document functions with detailed explanations | # pylint: disable= no-member, arguments-differ, invalid-name
import torch as th
from torch import nn
from torch.nn import init
class DenseChebConv(nn.Module):
def __init__(self, in_feats, out_feats, k, bias=True):
super(DenseChebConv, self).__init__()
self._in_feats = in_feats
self._out_f... | --- +++ @@ -1,3 +1,4 @@+"""Torch Module for DenseChebConv"""
# pylint: disable= no-member, arguments-differ, invalid-name
import torch as th
from torch import nn
@@ -5,6 +6,53 @@
class DenseChebConv(nn.Module):
+ r"""Chebyshev Spectral Graph Convolution layer from `Convolutional
+ Neural Networks on Graphs... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/nn/pytorch/conv/densechebconv.py |
Document classes and their methods | # pylint: disable=no-member, arguments-differ, invalid-name, too-many-arguments
from torch import nn
from .cugraph_base import CuGraphBaseConv
try:
from pylibcugraphops.pytorch import SampledCSC, StaticCSC
from pylibcugraphops.pytorch.operators import agg_concat_n2n as SAGEConvAgg
HAS_PYLIBCUGRAPHOPS = ... | --- +++ @@ -1,3 +1,5 @@+"""Torch Module for GraphSAGE layer using the aggregation primitives in
+cugraph-ops"""
# pylint: disable=no-member, arguments-differ, invalid-name, too-many-arguments
from torch import nn
@@ -14,6 +16,56 @@
class CuGraphSAGEConv(CuGraphBaseConv):
+ r"""An accelerated GraphSAGE layer ... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/nn/pytorch/conv/cugraph_sageconv.py |
Help me add docstrings to my project | # pylint: disable= no-member, arguments-differ, invalid-name, W0235
from mxnet import gluon, nd
from mxnet.gluon import nn
from ...readout import (
broadcast_nodes,
max_nodes,
mean_nodes,
softmax_nodes,
sum_nodes,
topk_nodes,
)
__all__ = [
"SumPooling",
"AvgPooling",
"MaxPooling",
... | --- +++ @@ -1,3 +1,4 @@+"""MXNet modules for graph global pooling."""
# pylint: disable= no-member, arguments-differ, invalid-name, W0235
from mxnet import gluon, nd
from mxnet.gluon import nn
@@ -22,11 +23,32 @@
class SumPooling(nn.Block):
+ r"""Apply sum pooling over the nodes in the graph.
+
+ .. math::... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/nn/mxnet/glob.py |
Add detailed docstrings explaining each function |
from _collections_abc import Mapping
from torch.utils.data import functional_datapipe
from .minibatch_transformer import MiniBatchTransformer
__all__ = [
"NegativeSampler",
]
@functional_datapipe("sample_negative")
class NegativeSampler(MiniBatchTransformer):
def __init__(
self,
datapipe,... | --- +++ @@ -1,3 +1,4 @@+"""Negative samplers."""
from _collections_abc import Mapping
@@ -12,6 +13,19 @@
@functional_datapipe("sample_negative")
class NegativeSampler(MiniBatchTransformer):
+ """
+ A negative sampler used to generate negative samples and return
+ a mix of positive and negative samples.... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/graphbolt/negative_sampler.py |
Add docstrings to existing functions | # pylint: disable= no-member, arguments-differ, invalid-name, cell-var-from-loop
import mxnet as mx
from mxnet import gluon, nd
from mxnet.gluon import nn
from .... import function as fn
class GatedGraphConv(nn.Block):
def __init__(self, in_feats, out_feats, n_steps, n_etypes, bias=True):
super(GatedGra... | --- +++ @@ -1,3 +1,4 @@+"""MXNet Module for Gated Graph Convolution layer"""
# pylint: disable= no-member, arguments-differ, invalid-name, cell-var-from-loop
import mxnet as mx
from mxnet import gluon, nd
@@ -7,6 +8,58 @@
class GatedGraphConv(nn.Block):
+ r"""Gated Graph Convolution layer from `Gated Graph Se... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/nn/mxnet/conv/gatedgraphconv.py |
Add docstrings to improve readability |
from collections.abc import Mapping
from typing import Callable, Iterator, Optional, Union
import numpy as np
import torch
import torch.distributed as dist
from torch.utils.data import IterDataPipe
from .internal import calculate_range
from .internal_utils import gb_warning
from .itemset import HeteroItemSet, ItemSe... | --- +++ @@ -1,3 +1,4 @@+"""Item Sampler"""
from collections.abc import Mapping
from typing import Callable, Iterator, Optional, Union
@@ -16,6 +17,25 @@
def minibatcher_default(batch, names):
+ """Default minibatcher which maps a list of items to a `MiniBatch` with the
+ same names as the items. The names... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/graphbolt/item_sampler.py |
Insert docstrings into my code | # pylint: disable= no-member, arguments-differ, invalid-name
import torch as th
from torch import nn
from .... import function as fn
from ....base import DGLError
from ....utils import expand_as_pair
from ...functional import edge_softmax
from ..utils import Identity
# pylint: enable=W0235
class GATv2Conv(nn.Module)... | --- +++ @@ -1,3 +1,4 @@+"""Torch modules for graph attention networks v2 (GATv2)."""
# pylint: disable= no-member, arguments-differ, invalid-name
import torch as th
from torch import nn
@@ -11,6 +12,129 @@
# pylint: enable=W0235
class GATv2Conv(nn.Module):
+ r"""GATv2 from `How Attentive are Graph Attention Ne... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/nn/pytorch/conv/gatv2conv.py |
Generate helpful docstrings for debugging | # pylint: disable= no-member, arguments-differ, invalid-name
import torch as th
from torch import nn
from .... import function as fn
from ....base import DGLError
from ....utils import expand_as_pair
from ...functional import edge_softmax
from ..utils import Identity
# pylint: enable=W0235
class GATConv(nn.Module):
... | --- +++ @@ -1,3 +1,4 @@+"""Torch modules for graph attention networks(GAT)."""
# pylint: disable= no-member, arguments-differ, invalid-name
import torch as th
from torch import nn
@@ -11,6 +12,125 @@
# pylint: enable=W0235
class GATConv(nn.Module):
+ r"""Graph attention layer from `Graph Attention Network
+ ... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/nn/pytorch/conv/gatconv.py |
Add docstrings to improve readability | # pylint: disable= no-member, arguments-differ, invalid-name, cell-var-from-loop
import torch
import torch.nn.functional as F
from torch import nn
from .... import function as fn
class GatedGCNConv(nn.Module):
def __init__(
self,
input_feats,
edge_feats,
output_feats,
dro... | --- +++ @@ -1,3 +1,4 @@+"""Torch Module for GatedGCN layer"""
# pylint: disable= no-member, arguments-differ, invalid-name, cell-var-from-loop
import torch
import torch.nn.functional as F
@@ -7,6 +8,58 @@
class GatedGCNConv(nn.Module):
+ r"""Gated graph convolutional layer from `Benchmarking Graph Neural Netw... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/nn/pytorch/conv/gatedgcnconv.py |
Annotate my code with docstrings | # pylint: disable= no-member, arguments-differ, invalid-name
import math
import mxnet as mx
from mxnet.gluon import nn
from mxnet.gluon.contrib.nn import Identity
from .... import function as fn
from ....base import DGLError
from ....utils import expand_as_pair
from ...functional import edge_softmax
# pylint: enabl... | --- +++ @@ -1,3 +1,4 @@+"""MXNet modules for graph attention networks(GAT)."""
# pylint: disable= no-member, arguments-differ, invalid-name
import math
@@ -13,6 +14,128 @@
# pylint: enable=W0235
class GATConv(nn.Block):
+ r"""Graph attention layer from `Graph Attention Network
+ <https://arxiv.org/pdf/1710... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/nn/mxnet/conv/gatconv.py |
Turn comments into proper docstrings | # pylint: disable= no-member, arguments-differ, invalid-name, cell-var-from-loop
import torch as th
from torch import nn
from torch.nn import init
from .... import function as fn
class GatedGraphConv(nn.Module):
def __init__(self, in_feats, out_feats, n_steps, n_etypes, bias=True):
super(GatedGraphConv,... | --- +++ @@ -1,3 +1,4 @@+"""Torch Module for Gated Graph Convolution layer"""
# pylint: disable= no-member, arguments-differ, invalid-name, cell-var-from-loop
import torch as th
from torch import nn
@@ -7,6 +8,55 @@
class GatedGraphConv(nn.Module):
+ r"""Gated Graph Convolution layer from `Gated Graph Sequence... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/nn/pytorch/conv/gatedgraphconv.py |
Fill in missing docstrings in my code | import random
import traceback
from _thread import start_new_thread
from functools import wraps
import torch
import torch.multiprocessing as mp
from ..utils import create_shared_mem_array, get_shared_mem_array
def thread_wrapped_func(func):
@wraps(func)
def decorated_function(*args, **kwargs):
queu... | --- +++ @@ -1,3 +1,4 @@+"""PyTorch multiprocessing wrapper."""
import random
import traceback
from _thread import start_new_thread
@@ -10,6 +11,9 @@
def thread_wrapped_func(func):
+ """
+ Wraps a process entry point to make it work with OpenMP.
+ """
@wraps(func)
def decorated_function(*args... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/multiprocessing/pytorch.py |
Add docstrings to incomplete code | # pylint: disable= no-member, arguments-differ, invalid-name
import torch as th
from torch import nn
from .... import function as fn
from .graphconv import EdgeWeightNorm
class TAGConv(nn.Module):
def __init__(
self,
in_feats,
out_feats,
k=2,
bias=True,
activation... | --- +++ @@ -1,3 +1,4 @@+"""Torch Module for Topology Adaptive Graph Convolutional layer"""
# pylint: disable= no-member, arguments-differ, invalid-name
import torch as th
from torch import nn
@@ -7,6 +8,54 @@
class TAGConv(nn.Module):
+ r"""Topology Adaptive Graph Convolutional layer from `Topology
+ Adapt... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/nn/pytorch/conv/tagconv.py |
Generate docstrings with parameter types | # pylint: disable= no-member, arguments-differ, invalid-name
import math
import mxnet as mx
from mxnet import nd
from mxnet.gluon import nn
from mxnet.gluon.contrib.nn import Identity
from .... import function as fn
from ....base import DGLError
from ....utils import expand_as_pair
class GMMConv(nn.Block):
def... | --- +++ @@ -1,3 +1,4 @@+"""Torch Module for GMM Conv"""
# pylint: disable= no-member, arguments-differ, invalid-name
import math
@@ -12,6 +13,101 @@
class GMMConv(nn.Block):
+ r"""Gaussian Mixture Model Convolution layer from `Geometric Deep Learning on Graphs and
+ Manifolds using Mixture Model CNNs <htt... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/nn/mxnet/conv/gmmconv.py |
Generate missing documentation strings | import sys
from .. import ops
__all__ = ["copy_u", "copy_v"]
#######################################################
# Edge-wise operators that fetch node data to edges
#######################################################
def copy_u(g, x_node, etype=None):
etype_subg = g if etype is None else g[etype]
r... | --- +++ @@ -1,3 +1,4 @@+"""Operators for computing edge data."""
import sys
from .. import ops
@@ -10,11 +11,109 @@
def copy_u(g, x_node, etype=None):
+ """Compute new edge data by fetching from source node data.
+
+ Given an input graph :math:`G(V, E)` (or a unidirectional bipartite graph
+ :math:`G(V... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/mpops/edgewise.py |
Help me write clear docstrings | # pylint: disable= no-member, arguments-differ, invalid-name
from functools import partial
import torch
import torch.nn as nn
from .pnaconv import AGGREGATORS, PNAConv, PNAConvTower, SCALERS
def aggregate_dir_av(h, eig_s, eig_d, eig_idx):
h_mod = torch.mul(
h,
(
torch.abs(eig_s[:, :,... | --- +++ @@ -1,3 +1,4 @@+"""Torch Module for Directional Graph Networks Convolution Layer"""
# pylint: disable= no-member, arguments-differ, invalid-name
from functools import partial
@@ -8,6 +9,7 @@
def aggregate_dir_av(h, eig_s, eig_d, eig_idx):
+ """directional average aggregation"""
h_mod = torch.mul... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/nn/pytorch/conv/dgnconv.py |
Generate consistent docstrings | # pylint: disable= no-member, arguments-differ, invalid-name
import torch
import torch.nn as nn
from .... import function as fn
class EGNNConv(nn.Module):
def __init__(self, in_size, hidden_size, out_size, edge_feat_size=0):
super(EGNNConv, self).__init__()
self.in_size = in_size
self.h... | --- +++ @@ -1,3 +1,4 @@+"""Torch Module for E(n) Equivariant Graph Convolutional Layer"""
# pylint: disable= no-member, arguments-differ, invalid-name
import torch
import torch.nn as nn
@@ -6,6 +7,47 @@
class EGNNConv(nn.Module):
+ r"""Equivariant Graph Convolutional Layer from `E(n) Equivariant Graph
+ Ne... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/nn/pytorch/conv/egnnconv.py |
Generate consistent documentation across files | # pylint: disable= no-member, arguments-differ, invalid-name
from torch import nn
from .... import function as fn
from ....base import DGLError
from ....utils import expand_as_pair
class EdgeConv(nn.Module):
def __init__(
self, in_feat, out_feat, batch_norm=False, allow_zero_in_degree=False
):
... | --- +++ @@ -1,3 +1,4 @@+"""Torch Module for EdgeConv Layer"""
# pylint: disable= no-member, arguments-differ, invalid-name
from torch import nn
@@ -8,6 +9,90 @@
class EdgeConv(nn.Module):
+ r"""EdgeConv layer from `Dynamic Graph CNN for Learning on Point Clouds
+ <https://arxiv.org/pdf/1801.07829>`__
+
+ ... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/nn/pytorch/conv/edgeconv.py |
Fully document this Python code with docstrings | # pylint: disable= no-member, arguments-differ, invalid-name
import torch as th
from torch import nn
from .... import function as fn
from ....base import DGLError
from ....utils import expand_as_pair
from ...functional import edge_softmax
# pylint: enable=W0235
class EdgeGATConv(nn.Module):
def __init__(
... | --- +++ @@ -1,3 +1,4 @@+"""Torch modules for graph attention networks(GAT)."""
# pylint: disable= no-member, arguments-differ, invalid-name
import torch as th
from torch import nn
@@ -9,6 +10,128 @@
# pylint: enable=W0235
class EdgeGATConv(nn.Module):
+ r"""Graph attention layer with edge features from `SCENE
... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/nn/pytorch/conv/edgegatconv.py |
Improve my code by adding docstrings | # pylint: disable= no-member, arguments-differ, invalid-name
from torch import nn
from .... import function as fn
from ....base import DGLError
from ....utils import expand_as_pair
from ...functional import edge_softmax
class DotGatConv(nn.Module):
def __init__(
self, in_feats, out_feats, num_heads, all... | --- +++ @@ -1,3 +1,4 @@+"""Torch modules for graph attention networks(GAT)."""
# pylint: disable= no-member, arguments-differ, invalid-name
from torch import nn
@@ -8,6 +9,115 @@
class DotGatConv(nn.Module):
+ r"""Apply dot product version of self attention in `Graph Attention Network
+ <https://arxiv.org... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/nn/pytorch/conv/dotgatconv.py |
Generate helpful docstrings for debugging | # pylint: disable= no-member, arguments-differ, invalid-name
import mxnet as mx
from mxnet.gluon import nn
from .... import function as fn
from ....base import DGLError
from ....utils import expand_as_pair
from ...functional import edge_softmax
from ..utils import normalize
class AGNNConv(nn.Block):
def __init_... | --- +++ @@ -1,3 +1,4 @@+"""MXNet Module for Attention-based Graph Neural Network layer"""
# pylint: disable= no-member, arguments-differ, invalid-name
import mxnet as mx
from mxnet.gluon import nn
@@ -10,6 +11,70 @@
class AGNNConv(nn.Block):
+ r"""Attention-based Graph Neural Network layer from `Attention-bas... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/nn/mxnet/conv/agnnconv.py |
Document functions with detailed explanations | # pylint: disable= no-member, arguments-differ, invalid-name
import math
import torch as th
from torch import nn
from .... import function as fn
from ....base import DGLError
from .graphconv import EdgeWeightNorm
class GCN2Conv(nn.Module):
def __init__(
self,
in_feats,
layer,
al... | --- +++ @@ -1,3 +1,5 @@+"""Torch Module for Graph Convolutional Network via Initial residual
+ and Identity mapping (GCNII) layer"""
# pylint: disable= no-member, arguments-differ, invalid-name
import math
@@ -10,6 +12,97 @@
class GCN2Conv(nn.Module):
+ r"""Graph Convolutional Network via Initial residual... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/nn/pytorch/conv/gcn2conv.py |
Write docstrings for backend logic | # pylint: disable= no-member, arguments-differ, invalid-name
import mxnet as mx
from mxnet.gluon import nn
from .... import function as fn
from ....utils import expand_as_pair
class GINConv(nn.Block):
def __init__(
self, apply_func, aggregator_type, init_eps=0, learn_eps=False
):
super(GINCo... | --- +++ @@ -1,3 +1,4 @@+"""MXNet Module for Graph Isomorphism Network layer"""
# pylint: disable= no-member, arguments-differ, invalid-name
import mxnet as mx
from mxnet.gluon import nn
@@ -7,6 +8,56 @@
class GINConv(nn.Block):
+ r"""Graph Isomorphism layer from `How Powerful are Graph
+ Neural Networks? <... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/nn/mxnet/conv/ginconv.py |
Write docstrings including parameters and return values | # pylint: disable= no-member, arguments-differ, invalid-name
from torch import nn
from ....utils import check_eq_shape
class DenseSAGEConv(nn.Module):
def __init__(
self,
in_feats,
out_feats,
feat_drop=0.0,
bias=True,
norm=None,
activation=None,
):
... | --- +++ @@ -1,3 +1,4 @@+"""Torch Module for DenseSAGEConv"""
# pylint: disable= no-member, arguments-differ, invalid-name
from torch import nn
@@ -5,6 +6,57 @@
class DenseSAGEConv(nn.Module):
+ """GraphSAGE layer from `Inductive Representation Learning on Large Graphs
+ <https://arxiv.org/abs/1706.02216>`... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/nn/pytorch/conv/densesageconv.py |
Add docstrings for production code | # pylint: disable= no-member, arguments-differ, invalid-name
import torch as th
from torch import nn
from torch.nn import init
from .... import function as fn
from ....base import DGLError
from ....utils import expand_as_pair
from ...functional import edge_softmax
# pylint: enable=W0235
class EGATConv(nn.Module):
... | --- +++ @@ -1,3 +1,4 @@+"""Torch modules for graph attention networks with fully valuable edges (EGAT)."""
# pylint: disable= no-member, arguments-differ, invalid-name
import torch as th
from torch import nn
@@ -11,6 +12,89 @@
# pylint: enable=W0235
class EGATConv(nn.Module):
+ r"""Graph attention layer that h... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/nn/pytorch/conv/egatconv.py |
Write proper docstrings for these functions | # pylint: disable= no-member, arguments-differ, invalid-name
import torch as th
from torch import nn
from .... import function as fn
from .graphconv import EdgeWeightNorm
class APPNPConv(nn.Module):
def __init__(self, k, alpha, edge_drop=0.0):
super(APPNPConv, self).__init__()
self._k = k
... | --- +++ @@ -1,3 +1,4 @@+"""Torch Module for APPNPConv"""
# pylint: disable= no-member, arguments-differ, invalid-name
import torch as th
from torch import nn
@@ -7,6 +8,53 @@
class APPNPConv(nn.Module):
+ r"""Approximate Personalized Propagation of Neural Predictions layer from `Predict then
+ Propagate: G... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/nn/pytorch/conv/appnpconv.py |
Document this script properly | # pylint: disable=no-member, arguments-differ, invalid-name, too-many-arguments
import math
import torch
from torch import nn
from .cugraph_base import CuGraphBaseConv
try:
from pylibcugraphops.pytorch import HeteroCSC
from pylibcugraphops.pytorch.operators import (
agg_hg_basis_n2n_post as RelGraphC... | --- +++ @@ -1,3 +1,5 @@+"""Torch Module for Relational graph convolution layer using the aggregation
+primitives in cugraph-ops"""
# pylint: disable=no-member, arguments-differ, invalid-name, too-many-arguments
import math
@@ -18,6 +20,67 @@
class CuGraphRelGraphConv(CuGraphBaseConv):
+ r"""An accelerated re... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/nn/pytorch/conv/cugraph_relgraphconv.py |
Write documentation strings for class attributes |
import torch
import torch.nn as nn
import torch.nn.functional as F
class EGTLayer(nn.Module):
def __init__(
self,
feat_size,
edge_feat_size,
num_heads,
num_virtual_nodes,
dropout=0,
attn_dropout=0,
activation=nn.ELU(),
edge_update=True,
... | --- +++ @@ -1,3 +1,4 @@+"""EGT Layer"""
import torch
import torch.nn as nn
@@ -5,6 +6,47 @@
class EGTLayer(nn.Module):
+ r"""EGTLayer for Edge-augmented Graph Transformer (EGT), as introduced in
+ `Global Self-Attention as a Replacement for Graph Convolution
+ Reference `<https://arxiv.org/pdf/2108.033... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/nn/pytorch/gt/egt.py |
Include argument descriptions in docstrings | # pylint: disable= no-member, arguments-differ, invalid-name
import numpy as np
import torch as th
import torch.nn as nn
class RadialPooling(nn.Module):
def __init__(
self, interaction_cutoffs, rbf_kernel_means, rbf_kernel_scaling
):
super(RadialPooling, self).__init__()
self.interac... | --- +++ @@ -1,3 +1,4 @@+"""Torch Module for Atomic Convolution Layer"""
# pylint: disable= no-member, arguments-differ, invalid-name
import numpy as np
import torch as th
@@ -5,6 +6,43 @@
class RadialPooling(nn.Module):
+ r"""Radial pooling from `Atomic Convolutional Networks for
+ Predicting Protein-Ligan... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/nn/pytorch/conv/atomicconv.py |
Create documentation for each function signature | import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from .... import batch, ETYPE, khop_in_subgraph, NID, to_homogeneous
__all__ = ["PGExplainer", "HeteroPGExplainer"]
class PGExplainer(nn.Module):
def __init__(
self,
model,
num_features,
num_hops=Non... | --- +++ @@ -1,3 +1,4 @@+"""Torch Module for PGExplainer"""
import math
import torch
@@ -10,6 +11,39 @@
class PGExplainer(nn.Module):
+ r"""PGExplainer from `Parameterized Explainer for Graph Neural Network
+ <https://arxiv.org/pdf/2011.04573>`
+
+ PGExplainer adopts a deep neural network (explanation n... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/nn/pytorch/explain/pgexplainer.py |
Help me document legacy Python code | # pylint: disable= no-member, arguments-differ, invalid-name
import torch as th
from torch import nn
from .... import function as fn
from ....utils import expand_as_pair
class GINConv(nn.Module):
def __init__(
self,
apply_func=None,
aggregator_type="sum",
init_eps=0,
lear... | --- +++ @@ -1,3 +1,4 @@+"""Torch Module for Graph Isomorphism Network layer"""
# pylint: disable= no-member, arguments-differ, invalid-name
import torch as th
from torch import nn
@@ -7,6 +8,83 @@
class GINConv(nn.Module):
+ r"""Graph Isomorphism Network layer from `How Powerful are Graph
+ Neural Networks... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/nn/pytorch/conv/ginconv.py |
Add docstrings to clarify complex logic | # pylint: disable= no-member, arguments-differ, invalid-name
import torch as th
from torch import nn
from torch.nn import init
class DenseGraphConv(nn.Module):
def __init__(
self, in_feats, out_feats, norm="both", bias=True, activation=None
):
super(DenseGraphConv, self).__init__()
se... | --- +++ @@ -1,3 +1,4 @@+"""Torch Module for DenseGraphConv"""
# pylint: disable= no-member, arguments-differ, invalid-name
import torch as th
from torch import nn
@@ -5,6 +6,63 @@
class DenseGraphConv(nn.Module):
+ """Graph Convolutional layer from `Semi-Supervised Classification with Graph
+ Convolutional... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/nn/pytorch/conv/densegraphconv.py |
Add docstrings to improve readability | # pylint: disable=invalid-name, useless-super-delegation, no-member
import torch as tc
import torch.nn as nn
import torch.nn.functional as F
from .... import function as fn
class TWIRLSConv(nn.Module):
def __init__(
self,
input_d,
output_d,
hidden_d,
prop_step,
n... | --- +++ @@ -1,3 +1,4 @@+"""Torch modules for TWIRLS"""
# pylint: disable=invalid-name, useless-super-delegation, no-member
import torch as tc
@@ -8,6 +9,72 @@
class TWIRLSConv(nn.Module):
+ r"""Convolution together with iteratively reweighting least squre from
+ `Graph Neural Networks Inspired by Classica... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/nn/pytorch/conv/twirlsconv.py |
Write docstrings for this repository | import torch
from torch import nn
class CuGraphBaseConv(nn.Module):
def __init__(self):
super().__init__()
self._cached_offsets_fg = None
def reset_parameters(self):
raise NotImplementedError
def forward(self, *args):
raise NotImplementedError
def pad_offsets(self, ... | --- +++ @@ -1,20 +1,49 @@+"""An abstract base class for cugraph-ops nn module."""
import torch
from torch import nn
class CuGraphBaseConv(nn.Module):
+ r"""An abstract base class for cugraph-ops nn module."""
def __init__(self):
super().__init__()
self._cached_offsets_fg = None
... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/nn/pytorch/conv/cugraph_base.py |
Fully document this Python code with docstrings | # pylint: disable= no-member, arguments-differ, invalid-name
import numpy as np
import torch.nn as nn
from .... import function as fn
class ShiftedSoftplus(nn.Module):
def __init__(self, beta=1, shift=2, threshold=20):
super(ShiftedSoftplus, self).__init__()
self.shift = shift
self.soft... | --- +++ @@ -1,3 +1,4 @@+"""Torch modules for interaction blocks in SchNet"""
# pylint: disable= no-member, arguments-differ, invalid-name
import numpy as np
import torch.nn as nn
@@ -6,6 +7,18 @@
class ShiftedSoftplus(nn.Module):
+ r"""Applies the element-wise function:
+
+ .. math::
+ \text{SSP}(x)... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/nn/pytorch/conv/cfconv.py |
Create structured documentation for my script |
import torch as th
import torch.nn as nn
import torch.nn.functional as F
class BiasedMHA(nn.Module):
def __init__(
self,
feat_size,
num_heads,
bias=True,
attn_bias_type="add",
attn_drop=0.1,
):
super().__init__()
self.feat_size = feat_size
... | --- +++ @@ -1,3 +1,4 @@+"""Biased Multi-head Attention"""
import torch as th
import torch.nn as nn
@@ -5,6 +6,47 @@
class BiasedMHA(nn.Module):
+ r"""Dense Multi-Head Attention Module with Graph Attention Bias.
+
+ Compute attention between nodes with attention bias obtained from graph
+ structures, as... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/nn/pytorch/gt/biased_mha.py |
Document all public functions with docstrings | import torch.nn as nn
from ...transforms import knn_graph, radius_graph, segmented_knn_graph
def pairwise_squared_distance(x):
x2s = (x * x).sum(-1, keepdim=True)
return x2s + x2s.transpose(-1, -2) - 2 * x @ x.transpose(-1, -2)
class KNNGraph(nn.Module):
def __init__(self, k):
super(KNNGraph, ... | --- +++ @@ -1,14 +1,65 @@+"""Modules that transforms between graphs and between graph and tensors."""
import torch.nn as nn
from ...transforms import knn_graph, radius_graph, segmented_knn_graph
def pairwise_squared_distance(x):
+ """
+ x : (n_samples, n_points, dims)
+ return : (n_samples, n_points, ... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/nn/pytorch/factory.py |
Add professional docstrings to my codebase | # pylint: disable= no-member, arguments-differ, invalid-name
from math import sqrt
import torch
from torch import nn
from tqdm.auto import tqdm
from ....base import EID, NID
from ....subgraph import khop_in_subgraph
__all__ = ["GNNExplainer", "HeteroGNNExplainer"]
class GNNExplainer(nn.Module):
def __init__(... | --- +++ @@ -1,3 +1,4 @@+"""Torch Module for GNNExplainer"""
# pylint: disable= no-member, arguments-differ, invalid-name
from math import sqrt
@@ -13,6 +14,56 @@
class GNNExplainer(nn.Module):
+ r"""GNNExplainer model from `GNNExplainer: Generating Explanations for
+ Graph Neural Networks <https://arxiv.o... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/nn/pytorch/explain/gnnexplainer.py |
Add docstrings including usage examples | # pylint: disable= no-member, arguments-differ, invalid-name, W0235
import numpy as np
import torch as th
import torch.nn as nn
from ...backend import pytorch as F
from ...base import dgl_warning
from ...readout import (
broadcast_nodes,
max_nodes,
mean_nodes,
softmax_nodes,
sum_nodes,
topk_nod... | --- +++ @@ -1,3 +1,4 @@+"""Torch modules for graph global pooling."""
# pylint: disable= no-member, arguments-differ, invalid-name, W0235
import numpy as np
import torch as th
@@ -28,11 +29,81 @@
class SumPooling(nn.Module):
+ r"""Apply sum pooling over the nodes in a graph.
+
+ .. math::
+ r^{(i)} ... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/nn/pytorch/glob.py |
Add docstrings to incomplete code | # pylint: disable=no-member, arguments-differ, invalid-name, too-many-arguments
import torch
from torch import nn
from .cugraph_base import CuGraphBaseConv
try:
from pylibcugraphops.pytorch import SampledCSC, StaticCSC
from pylibcugraphops.pytorch.operators import mha_gat_n2n as GATConvAgg
HAS_PYLIBCUGR... | --- +++ @@ -1,3 +1,5 @@+"""Torch Module for graph attention network layer using the aggregation
+primitives in cugraph-ops"""
# pylint: disable=no-member, arguments-differ, invalid-name, too-many-arguments
import torch
@@ -15,6 +17,70 @@
class CuGraphGATConv(CuGraphBaseConv):
+ r"""Graph attention layer from... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/nn/pytorch/conv/cugraph_gatconv.py |
Add docstrings to clarify complex logic | import math
import networkx as nx
import numpy as np
import torch
import torch.nn as nn
from .... import to_heterogeneous, to_homogeneous
from ....base import NID
from ....convert import to_networkx
from ....subgraph import node_subgraph
from ....transforms.functional import remove_nodes
__all__ = ["SubgraphX", "Het... | --- +++ @@ -1,3 +1,4 @@+"""Torch Module for SubgraphX"""
import math
import networkx as nx
@@ -15,6 +16,13 @@
class MCTSNode:
+ r"""Monte Carlo Tree Search Node
+
+ Parameters
+ ----------
+ nodes : Tensor
+ The node IDs of the graph that are associated with this tree node
+ """
def... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/nn/pytorch/explain/subgraphx.py |
Add docstrings to existing functions |
# pylint: disable= invalid-name
import random
import torch
import torch.nn.functional as F
from torch import nn
from torch.nn import init
from tqdm.auto import trange
from ...base import NID
from ...convert import to_heterogeneous, to_homogeneous
from ...random import choice
from ...sampling import random_walk
__a... | --- +++ @@ -1,3 +1,4 @@+"""Network Embedding NN Modules"""
# pylint: disable= invalid-name
@@ -18,6 +19,71 @@
class DeepWalk(nn.Module):
+ """DeepWalk module from `DeepWalk: Online Learning of Social Representations
+ <https://arxiv.org/abs/1403.6652>`__
+
+ For a graph, it learns the node representat... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/nn/pytorch/network_emb.py |
Generate missing documentation strings |
import torch as th
import torch.nn as nn
class DegreeEncoder(nn.Module):
def __init__(self, max_degree, embedding_dim, direction="both"):
super(DegreeEncoder, self).__init__()
self.direction = direction
if direction == "both":
self.encoder1 = nn.Embedding(
max... | --- +++ @@ -1,9 +1,48 @@+"""Degree Encoder"""
import torch as th
import torch.nn as nn
class DegreeEncoder(nn.Module):
+ r"""Degree Encoder, as introduced in
+ `Do Transformers Really Perform Bad for Graph Representation?
+ <https://proceedings.neurips.cc/paper/2021/file/f1c1592588411002af340cbaedd6fc... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/nn/pytorch/gt/degree_encoder.py |
Improve documentation using docstrings | # pylint: disable= no-member, arguments-differ, invalid-name
import torch as th
import torch.nn.functional as F
from torch import nn
from .... import broadcast_nodes, function as fn
from ....base import dgl_warning
class ChebConv(nn.Module):
def __init__(self, in_feats, out_feats, k, activation=F.relu, bias=Tru... | --- +++ @@ -1,3 +1,4 @@+"""Torch Module for Chebyshev Spectral Graph Convolution layer"""
# pylint: disable= no-member, arguments-differ, invalid-name
import torch as th
import torch.nn.functional as F
@@ -8,6 +9,56 @@
class ChebConv(nn.Module):
+ r"""Chebyshev Spectral Graph Convolution layer from `Convoluti... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/nn/pytorch/conv/chebconv.py |
Add docstrings to make code maintainable | # pylint: disable= no-member, arguments-differ, invalid-name
import torch as th
from torch import nn
from torch.nn import functional as F
from .... import function as fn
from ....base import DGLError
from ....utils import expand_as_pair
from ...functional import edge_softmax
class AGNNConv(nn.Module):
def __ini... | --- +++ @@ -1,3 +1,4 @@+"""Torch Module for Attention-based Graph Neural Network layer"""
# pylint: disable= no-member, arguments-differ, invalid-name
import torch as th
from torch import nn
@@ -10,6 +11,69 @@
class AGNNConv(nn.Module):
+ r"""Attention-based Graph Neural Network layer from `Attention-based Gr... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/nn/pytorch/conv/agnnconv.py |
Generate documentation strings for clarity | # pylint: disable=no-member, invalid-name
import torch as th
import torch.nn.functional as F
from torch import nn
from ... import DGLGraph, function as fn
from ...base import dgl_warning
def matmul_maybe_select(A, B):
if A.dtype == th.int64 and len(A.shape) == 1:
return B.index_select(0, A)
else:
... | --- +++ @@ -1,3 +1,4 @@+"""Utilities for pytorch NN package"""
# pylint: disable=no-member, invalid-name
import torch as th
@@ -9,6 +10,41 @@
def matmul_maybe_select(A, B):
+ """Perform Matrix multiplication C = A * B but A could be an integer id vector.
+
+ If A is an integer vector, we treat it as multi... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/nn/pytorch/utils.py |
Help me write clear docstrings | # pylint: disable= no-member, arguments-differ, invalid-name
import numpy as np
import tensorflow as tf
from tensorflow.keras import layers
class DenseChebConv(layers.Layer):
def __init__(self, in_feats, out_feats, k, bias=True):
super(DenseChebConv, self).__init__()
self._in_feats = in_feats
... | --- +++ @@ -1,3 +1,4 @@+"""Tensorflow Module for DenseChebConv"""
# pylint: disable= no-member, arguments-differ, invalid-name
import numpy as np
import tensorflow as tf
@@ -5,6 +6,29 @@
class DenseChebConv(layers.Layer):
+ r"""Chebyshev Spectral Graph Convolution layer from `Convolutional
+ Neural Network... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/nn/tensorflow/conv/densechebconv.py |
Add docstrings to improve code quality | # pylint: disable= no-member, arguments-differ, invalid-name
import torch as th
from torch import nn
from .... import function as fn
from ..linear import TypedLinear
class RelGraphConv(nn.Module):
def __init__(
self,
in_feat,
out_feat,
num_rels,
regularizer=None,
... | --- +++ @@ -1,3 +1,4 @@+"""Torch Module for Relational graph convolution layer"""
# pylint: disable= no-member, arguments-differ, invalid-name
import torch as th
from torch import nn
@@ -7,6 +8,93 @@
class RelGraphConv(nn.Module):
+ r"""Relational graph convolution layer from `Modeling Relational Data with Gr... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/nn/pytorch/conv/relgraphconv.py |
Add docstrings for utility scripts | # pylint: disable= no-member, arguments-differ, invalid-name
import math
import torch
import torch.nn as nn
from .... import function as fn
from ..linear import TypedLinear
from ..softmax import edge_softmax
class HGTConv(nn.Module):
def __init__(
self,
in_size,
head_size,
num_h... | --- +++ @@ -1,3 +1,4 @@+"""Heterogeneous Graph Transformer"""
# pylint: disable= no-member, arguments-differ, invalid-name
import math
@@ -10,6 +11,62 @@
class HGTConv(nn.Module):
+ r"""Heterogeneous graph transformer convolution from `Heterogeneous Graph Transformer
+ <https://arxiv.org/abs/2003.01332>`_... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/nn/pytorch/conv/hgtconv.py |
Insert docstrings into my code | # pylint: disable= no-member, arguments-differ, invalid-name
import torch as th
from torch import nn
from torch.nn import init
from .... import function as fn
from ....base import DGLError
from ....convert import block_to_graph
from ....heterograph import DGLBlock
from ....transforms import reverse
from ....utils impo... | --- +++ @@ -1,3 +1,4 @@+"""Torch modules for graph convolutions(GCN)."""
# pylint: disable= no-member, arguments-differ, invalid-name
import torch as th
from torch import nn
@@ -12,6 +13,53 @@
class EdgeWeightNorm(nn.Module):
+ r"""This module normalizes positive scalar edge weights on a graph
+ following ... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/nn/pytorch/conv/graphconv.py |
Document functions with detailed explanations | # pylint: disable= no-member, arguments-differ, invalid-name, C0116, R1728
from copy import deepcopy
import numpy as np
import torch
import torch.nn as nn
class InvertibleCheckpoint(torch.autograd.Function):
@staticmethod
def forward(ctx, fn, fn_inverse, num_inputs, *inputs_and_weights):
ctx.fn = fn... | --- +++ @@ -1,3 +1,4 @@+"""Torch module for grouped reversible residual connections for GNNs"""
# pylint: disable= no-member, arguments-differ, invalid-name, C0116, R1728
from copy import deepcopy
@@ -7,6 +8,7 @@
class InvertibleCheckpoint(torch.autograd.Function):
+ r"""Extension of torch.autograd"""
... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/nn/pytorch/conv/grouprevres.py |
Generate documentation strings for clarity | from datetime import timedelta
import torch as th
from ...backend import pytorch as F
from ...cuda import nccl
from ...partition import NDArrayPartition
from ...utils import create_shared_mem_array, get_shared_mem_array
_STORE = None
class NodeEmbedding: # NodeEmbedding
def __init__(
self,
nu... | --- +++ @@ -1,3 +1,4 @@+"""Torch NodeEmbedding."""
from datetime import timedelta
import torch as th
@@ -11,6 +12,60 @@
class NodeEmbedding: # NodeEmbedding
+ """Class for storing node embeddings.
+
+ The class is optimized for training large-scale node embeddings. It updates the embedding in
+ a spar... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/nn/pytorch/sparse_emb.py |
Document classes and their methods | # pylint: disable= no-member, arguments-differ, invalid-name
import torch as th
from torch import nn
from .... import function as fn
from ....base import DGLError
from .graphconv import EdgeWeightNorm
class SGConv(nn.Module):
def __init__(
self,
in_feats,
out_feats,
k=1,
... | --- +++ @@ -1,3 +1,4 @@+"""Torch Module for Simplifying Graph Convolution layer"""
# pylint: disable= no-member, arguments-differ, invalid-name
import torch as th
from torch import nn
@@ -8,6 +9,78 @@
class SGConv(nn.Module):
+ r"""SGC layer from `Simplifying Graph
+ Convolutional Networks <https://arxiv.o... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/nn/pytorch/conv/sgconv.py |
Generate helpful docstrings for debugging | # pylint: disable= no-member, arguments-differ, invalid-name
import torch
from torch import nn
from torch.nn import functional as F
from .... import function as fn
from ....base import DGLError
from ....utils import check_eq_shape, expand_as_pair
class SAGEConv(nn.Module):
def __init__(
self,
in... | --- +++ @@ -1,3 +1,4 @@+"""Torch Module for GraphSAGE layer"""
# pylint: disable= no-member, arguments-differ, invalid-name
import torch
from torch import nn
@@ -9,6 +10,90 @@
class SAGEConv(nn.Module):
+ r"""GraphSAGE layer from `Inductive Representation Learning on
+ Large Graphs <https://arxiv.org/pdf/1... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/nn/pytorch/conv/sageconv.py |
Create docstrings for API functions | # pylint: disable= no-member, arguments-differ, invalid-name
import numpy as np
import tensorflow as tf
from tensorflow.keras import layers
from .... import broadcast_nodes, function as fn
from ....base import dgl_warning
class ChebConv(layers.Layer):
def __init__(
self, in_feats, out_feats, k, activati... | --- +++ @@ -1,3 +1,4 @@+"""Tensorflow Module for Chebyshev Spectral Graph Convolution layer"""
# pylint: disable= no-member, arguments-differ, invalid-name
import numpy as np
import tensorflow as tf
@@ -8,6 +9,56 @@
class ChebConv(layers.Layer):
+ r"""Chebyshev Spectral Graph Convolution layer from `Convoluti... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/nn/tensorflow/conv/chebconv.py |
Document functions with detailed explanations | # pylint: disable= no-member, arguments-differ, invalid-name
import tensorflow as tf
from tensorflow.keras import layers
from .... import function as fn
from ....base import DGLError
from ....utils import expand_as_pair
class EdgeConv(layers.Layer):
def __init__(self, out_feats, batch_norm=False, allow_zero_in_... | --- +++ @@ -1,3 +1,4 @@+"""Tensorflow modules for EdgeConv Layer"""
# pylint: disable= no-member, arguments-differ, invalid-name
import tensorflow as tf
from tensorflow.keras import layers
@@ -8,6 +9,57 @@
class EdgeConv(layers.Layer):
+ r"""EdgeConv layer from `Dynamic Graph CNN for Learning on Point Clouds
... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/nn/tensorflow/conv/edgeconv.py |
Expand my code with proper documentation strings | import numpy as np
# pylint: disable= no-member, arguments-differ, invalid-name
import tensorflow as tf
from tensorflow.keras import layers
from .... import function as fn
from ....base import DGLError
from ...functional import edge_softmax
from ..utils import Identity
# pylint: enable=W0235
class GATConv(layers.L... | --- +++ @@ -1,3 +1,4 @@+"""Tensorflow modules for graph attention networks(GAT)."""
import numpy as np
# pylint: disable= no-member, arguments-differ, invalid-name
@@ -13,6 +14,127 @@
class GATConv(layers.Layer):
+ r"""Graph Attention Layer from `Graph Attention Network
+ <https://arxiv.org/pdf/1710.10903... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/nn/tensorflow/conv/gatconv.py |
Provide clean and structured docstrings | # pylint: disable= no-member, arguments-differ, invalid-name
import numpy as np
import tensorflow as tf
from tensorflow.keras import layers
from .... import function as fn
class APPNPConv(layers.Layer):
def __init__(self, k, alpha, edge_drop=0.0):
super(APPNPConv, self).__init__()
self._k = k
... | --- +++ @@ -1,3 +1,4 @@+"""TF Module for APPNPConv"""
# pylint: disable= no-member, arguments-differ, invalid-name
import numpy as np
import tensorflow as tf
@@ -7,6 +8,26 @@
class APPNPConv(layers.Layer):
+ r"""Approximate Personalized Propagation of Neural Predictions
+ layer from `Predict then Propagate... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/nn/tensorflow/conv/appnpconv.py |
Generate documentation strings for clarity | # pylint: disable= no-member, arguments-differ, invalid-name
import torch as th
from torch import nn
from torch.nn import init
from .... import function as fn
from ....utils import expand_as_pair
from ..utils import Identity
class NNConv(nn.Module):
def __init__(
self,
in_feats,
out_feat... | --- +++ @@ -1,3 +1,4 @@+"""Torch Module for NNConv layer"""
# pylint: disable= no-member, arguments-differ, invalid-name
import torch as th
from torch import nn
@@ -9,6 +10,80 @@
class NNConv(nn.Module):
+ r"""Graph Convolution layer from `Neural Message Passing
+ for Quantum Chemistry <https://arxiv.org/p... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/nn/pytorch/conv/nnconv.py |
Document functions with clear intent |
import torch as th
import torch.nn as nn
class LapPosEncoder(nn.Module):
def __init__(
self,
model_type,
num_layer,
k,
dim,
n_head=1,
batch_norm=False,
num_post_layer=0,
):
super(LapPosEncoder, self).__init__()
self.model_type =... | --- +++ @@ -1,9 +1,56 @@+"""Laplacian Positional Encoder"""
import torch as th
import torch.nn as nn
class LapPosEncoder(nn.Module):
+ r"""Laplacian Positional Encoder (LPE), as introduced in
+ `GraphGPS: General Powerful Scalable Graph Transformers
+ <https://arxiv.org/abs/2205.12454>`__
+
+ This ... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/nn/pytorch/gt/lap_pos_encoder.py |
Generate helpful docstrings for debugging | # pylint: disable= no-member, arguments-differ, invalid-name
import numpy as np
import torch
import torch.nn as nn
def aggregate_mean(h):
return torch.mean(h, dim=1)
def aggregate_max(h):
return torch.max(h, dim=1)[0]
def aggregate_min(h):
return torch.min(h, dim=1)[0]
def aggregate_sum(h):
retu... | --- +++ @@ -1,3 +1,4 @@+"""Torch Module for Principal Neighbourhood Aggregation Convolution Layer"""
# pylint: disable= no-member, arguments-differ, invalid-name
import numpy as np
import torch
@@ -5,26 +6,32 @@
def aggregate_mean(h):
+ """mean aggregation"""
return torch.mean(h, dim=1)
def aggregat... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/nn/pytorch/conv/pnaconv.py |
Generate documentation strings for clarity | import sys
from itertools import product
from .. import backend as F
from ..backend import (
gsddmm as gsddmm_internal,
gsddmm_hetero as gsddmm_internal_hetero,
)
__all__ = ["gsddmm", "copy_u", "copy_v", "copy_e"]
def reshape_lhs_rhs(lhs_data, rhs_data):
lhs_shape = F.shape(lhs_data)
rhs_shape = F.s... | --- +++ @@ -1,3 +1,4 @@+"""dgl sddmm operator module."""
import sys
from itertools import product
@@ -11,6 +12,18 @@
def reshape_lhs_rhs(lhs_data, rhs_data):
+ r"""Expand dims so that there will be no broadcasting issues with different
+ number of dimensions. For example, given two shapes (N, 3, 1), (E, 5... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/ops/sddmm.py |
Fill in missing docstrings in my code | # pylint: disable=no-member, invalid-name
import tensorflow as tf
from tensorflow.keras import layers # pylint: disable=W0235
def matmul_maybe_select(A, B):
if A.dtype == tf.int64 and len(A.shape) == 1:
return tf.gather(B, A)
else:
return tf.matmul(A, B)
def bmm_maybe_select(A, B, index):
... | --- +++ @@ -1,9 +1,45 @@+"""Utilities for tf NN package"""
# pylint: disable=no-member, invalid-name
import tensorflow as tf
from tensorflow.keras import layers # pylint: disable=W0235
def matmul_maybe_select(A, B):
+ """Perform Matrix multiplication C = A * B but A could be an integer id vector.
+
+ If ... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/nn/tensorflow/utils.py |
Auto-generate documentation strings for this file | from ..backend import (
astype,
edge_softmax as edge_softmax_internal,
edge_softmax_hetero as edge_softmax_hetero_internal,
)
from ..base import ALL, is_all
__all__ = ["edge_softmax"]
def edge_softmax(graph, logits, eids=ALL, norm_by="dst"):
if not is_all(eids):
eids = astype(eids, graph.idty... | --- +++ @@ -1,3 +1,4 @@+"""dgl edge_softmax operator module."""
from ..backend import (
astype,
edge_softmax as edge_softmax_internal,
@@ -9,6 +10,126 @@
def edge_softmax(graph, logits, eids=ALL, norm_by="dst"):
+ r"""Compute softmax over weights of incoming edges for every node.
+
+ For a node :ma... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/ops/edge_softmax.py |
Add docstrings to meet PEP guidelines | import torch as th
import torch.nn as nn
class PathEncoder(nn.Module):
def __init__(self, max_len, feat_dim, num_heads=1):
super().__init__()
self.max_len = max_len
self.feat_dim = feat_dim
self.num_heads = num_heads
self.embedding_table = nn.Embedding(max_len * num_heads,... | --- +++ @@ -1,8 +1,49 @@+"""Path Encoder"""
import torch as th
import torch.nn as nn
class PathEncoder(nn.Module):
+ r"""Path Encoder, as introduced in Edge Encoding of
+ `Do Transformers Really Perform Bad for Graph Representation?
+ <https://proceedings.neurips.cc/paper/2021/file/f1c1592588411002af340... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/nn/pytorch/gt/path_encoder.py |
Write beginner-friendly docstrings | import sys
from .. import backend as F
from ..backend import (
gspmm as gspmm_internal,
gspmm_hetero as gspmm_internal_hetero,
)
__all__ = ["gspmm"]
def reshape_lhs_rhs(lhs_data, rhs_data):
lhs_shape = F.shape(lhs_data)
rhs_shape = F.shape(rhs_data)
if len(lhs_shape) != len(rhs_shape):
m... | --- +++ @@ -1,3 +1,4 @@+"""Internal module for general spmm operators."""
import sys
from .. import backend as F
@@ -10,6 +11,18 @@
def reshape_lhs_rhs(lhs_data, rhs_data):
+ r"""Expand dims so that there will be no broadcasting issues with different
+ number of dimensions. For example, given two shapes (... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/ops/spmm.py |
Create structured documentation for my script | from functools import partial
import torch as th
import torch.nn as nn
from ...base import DGLError
__all__ = ["HeteroGraphConv", "HeteroLinear", "HeteroEmbedding"]
class HeteroGraphConv(nn.Module):
def __init__(self, mods, aggregate="sum"):
super(HeteroGraphConv, self).__init__()
self.mod_dic... | --- +++ @@ -1,3 +1,4 @@+"""Heterograph NN modules"""
from functools import partial
import torch as th
@@ -9,6 +10,119 @@
class HeteroGraphConv(nn.Module):
+ r"""A generic module for computing convolution on heterogeneous graphs.
+
+ The heterograph convolution applies sub-modules on their associating
+ ... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/nn/pytorch/hetero.py |
Add docstrings to my Python code |
import torch as th
import torch.nn as nn
import torch.nn.functional as F
def gaussian(x, mean, std):
const_pi = 3.14159
a = (2 * const_pi) ** 0.5
return th.exp(-0.5 * (((x - mean) / std) ** 2)) / (a * std)
class SpatialEncoder(nn.Module):
def __init__(self, max_dist, num_heads=1):
super().... | --- +++ @@ -1,3 +1,4 @@+"""Spatial Encoder"""
import torch as th
import torch.nn as nn
@@ -5,12 +6,49 @@
def gaussian(x, mean, std):
+ """compute gaussian basis kernel function"""
const_pi = 3.14159
a = (2 * const_pi) ** 0.5
return th.exp(-0.5 * (((x - mean) / std) ** 2)) / (a * std)
clas... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/nn/pytorch/gt/spatial_encoder.py |
Generate docstrings for exported functions | from __future__ import absolute_import
from . import backend as F, traversal as trv
from .heterograph import DGLGraph
__all__ = [
"prop_nodes",
"prop_nodes_bfs",
"prop_nodes_topo",
"prop_edges",
"prop_edges_dfs",
]
def prop_nodes(
graph,
nodes_generator,
message_func="default",
r... | --- +++ @@ -1,3 +1,4 @@+"""Module for message propagation."""
from __future__ import absolute_import
from . import backend as F, traversal as trv
@@ -19,6 +20,23 @@ reduce_func="default",
apply_node_func="default",
):
+ """Functional method for :func:`dgl.DGLGraph.prop_nodes`.
+
+ Parameters
+ --... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/propagate.py |
Generate descriptive docstrings automatically | # pylint: disable= no-member, arguments-differ, invalid-name, W0235
import math
import torch
import torch.nn as nn
from ...ops import gather_mm, segment_mm
__all__ = ["TypedLinear"]
class TypedLinear(nn.Module):
def __init__(
self, in_size, out_size, num_types, regularizer=None, num_bases=None
):
... | --- +++ @@ -1,3 +1,4 @@+"""Various commonly used linear modules"""
# pylint: disable= no-member, arguments-differ, invalid-name, W0235
import math
@@ -10,6 +11,78 @@
class TypedLinear(nn.Module):
+ r"""Linear transformation according to types.
+
+ For each sample of the input batch :math:`x \in X`, apply ... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/nn/pytorch/linear.py |
Please document this code using docstrings |
from .. import backend as F
from ..base import DGLError
__all__ = ["segment_reduce", "segment_softmax", "segment_mm"]
def segment_reduce(seglen, value, reducer="sum"):
offsets = F.cumsum(
F.cat([F.zeros((1,), F.dtype(seglen), F.context(seglen)), seglen], 0), 0
)
if reducer == "mean":
rst... | --- +++ @@ -1,3 +1,4 @@+"""Segment aggregation operators implemented using DGL graph."""
from .. import backend as F
from ..base import DGLError
@@ -6,6 +7,40 @@
def segment_reduce(seglen, value, reducer="sum"):
+ """Segment reduction operator.
+
+ It aggregates the value tensor along the first dimension ... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/ops/segment.py |
Add docstrings for better understanding | from __future__ import absolute_import
from . import backend as F
from .base import dgl_warning, DGLError
from .ops import segment
__all__ = [
"readout_nodes",
"readout_edges",
"sum_nodes",
"sum_edges",
"mean_nodes",
"mean_edges",
"max_nodes",
"max_edges",
"softmax_nodes",
"sof... | --- +++ @@ -1,3 +1,4 @@+"""Classes and functions for batching multiple graphs together."""
from __future__ import absolute_import
from . import backend as F
@@ -23,6 +24,77 @@
def readout_nodes(graph, feat, weight=None, *, op="sum", ntype=None):
+ """Generate a graph-level representation by aggregating node ... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/readout.py |
Annotate my code with docstrings | import numpy as np
from . import backend as F, ndarray as nd
from ._ffi.function import _init_api
__all__ = ["seed"]
def seed(val):
_CAPI_SetSeed(val)
def choice(a, size, replace=True, prob=None): # pylint: disable=invalid-name
# TODO(minjie): support RNG as one of the arguments.
if isinstance(size, ... | --- +++ @@ -1,3 +1,4 @@+"""Python interfaces to DGL random number generators."""
import numpy as np
from . import backend as F, ndarray as nd
@@ -7,10 +8,56 @@
def seed(val):
+ """Set the random seed of DGL.
+
+ Parameters
+ ----------
+ val : int
+ The seed.
+ """
_CAPI_SetSeed(val)
... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/random.py |
Improve documentation using docstrings | # pylint: disable= no-member, arguments-differ, invalid-name
import torch as th
import torch.nn.functional as F
from torch import nn
from .... import function as fn
from ....utils import expand_as_pair
class GINEConv(nn.Module):
def __init__(self, apply_func=None, init_eps=0, learn_eps=False):
super(GIN... | --- +++ @@ -1,3 +1,4 @@+"""Torch Module for Graph Isomorphism Network layer variant with edge features"""
# pylint: disable= no-member, arguments-differ, invalid-name
import torch as th
import torch.nn.functional as F
@@ -8,6 +9,43 @@
class GINEConv(nn.Module):
+ r"""Graph Isomorphism Network with Edge Featur... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/nn/pytorch/conv/gineconv.py |
Fill in missing docstrings in my code | # pylint: disable= no-member, arguments-differ, invalid-name, W0235
import torch
import torch.nn as nn
class TransR(nn.Module):
def __init__(self, num_rels, rfeats, nfeats, p=1):
super(TransR, self).__init__()
self.rel_emb = nn.Embedding(num_rels, rfeats)
self.rel_project = nn.Embedding(... | --- +++ @@ -1,9 +1,64 @@+"""TransR."""
# pylint: disable= no-member, arguments-differ, invalid-name, W0235
import torch
import torch.nn as nn
class TransR(nn.Module):
+ r"""Similarity measure from
+ `Learning entity and relation embeddings for knowledge graph completion
+ <https://ojs.aaai.org/index.ph... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/nn/pytorch/link/transr.py |
Document all public functions with docstrings |
import os
import torch
from .. import backend as F, ndarray as nd, utils
from .._ffi.function import _init_api
from ..base import DGLError, EID
from ..heterograph import DGLBlock, DGLGraph
from .utils import EidExcluder
__all__ = [
"sample_etype_neighbors",
"sample_neighbors",
"sample_neighbors_fused",
... | --- +++ @@ -1,3 +1,4 @@+"""Neighbor sampling APIs"""
import os
@@ -19,6 +20,14 @@
def _prepare_edge_arrays(g, arg):
+ """Converts the argument into a list of NDArrays.
+
+ If the argument is already a list of array-like objects, directly do the
+ conversion.
+
+ If the argument is a string, convert... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/sampling/neighbor.py |
Create docstrings for each class method |
import numpy as np
from .. import backend as F, convert, utils
from .._ffi.function import _init_api
from .randomwalks import random_walk
def _select_pinsage_neighbors(src, dst, num_samples_per_node, k):
src = F.to_dgl_nd(src)
dst = F.to_dgl_nd(dst)
src, dst, counts = _CAPI_DGLSamplingSelectPinSageNeigh... | --- +++ @@ -1,3 +1,4 @@+"""PinSAGE sampler & related functions and classes"""
import numpy as np
@@ -7,6 +8,11 @@
def _select_pinsage_neighbors(src, dst, num_samples_per_node, k):
+ """Determine the neighbors for PinSAGE algorithm from the given random walk traces.
+
+ This is fusing ``to_simple()``, ``s... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/sampling/pinsage.py |
Generate docstrings for each module | from collections.abc import Mapping
import numpy as np
from .. import backend as F, transforms, utils
from ..base import EID
from ..utils import recursive_apply, recursive_apply_pair
def _locate_eids_to_exclude(frontier_parent_eids, exclude_eids):
if not isinstance(frontier_parent_eids, Mapping):
retur... | --- +++ @@ -1,3 +1,4 @@+"""Sampling utilities"""
from collections.abc import Mapping
import numpy as np
@@ -9,6 +10,10 @@
def _locate_eids_to_exclude(frontier_parent_eids, exclude_eids):
+ """Find the edges whose IDs in parent graph appeared in exclude_eids.
+
+ Note that both arguments are numpy arrays o... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/sampling/utils.py |
Add docstrings explaining edge cases | from typing import Union
import torch
from .sparse_matrix import SparseMatrix, val_like
from .utils import is_scalar, Scalar
def spsp_add(A, B):
return SparseMatrix(
torch.ops.dgl_sparse.spsp_add(A.c_sparse_matrix, B.c_sparse_matrix)
)
def spsp_mul(A, B):
return SparseMatrix(
torch.ops... | --- +++ @@ -1,3 +1,4 @@+"""DGL elementwise operators for sparse matrix module."""
from typing import Union
import torch
@@ -7,48 +8,205 @@
def spsp_add(A, B):
+ """Invoke C++ sparse library for addition"""
return SparseMatrix(
torch.ops.dgl_sparse.spsp_add(A.c_sparse_matrix, B.c_sparse_matrix)
... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/sparse/elementwise_op_sp.py |
Add detailed documentation for each class |
from .. import backend as F, ndarray as nd, utils
from .._ffi.function import _init_api
from ..base import DGLError
__all__ = ["random_walk", "pack_traces"]
def random_walk(
g,
nodes,
*,
metapath=None,
length=None,
prob=None,
restart_prob=None,
return_eids=False
):
n_etypes = len... | --- +++ @@ -1,3 +1,5 @@+"""Random walk routines
+"""
from .. import backend as F, ndarray as nd, utils
from .._ffi.function import _init_api
@@ -16,6 +18,155 @@ restart_prob=None,
return_eids=False
):
+ """Generate random walk traces from an array of starting nodes based on the given metapath.
+
+ E... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/sampling/randomwalks.py |
Generate NumPy-style docstrings | # pylint: disable=W0622
from typing import Optional
import torch
from .sparse_matrix import SparseMatrix
def reduce(input: SparseMatrix, dim: Optional[int] = None, rtype: str = "sum"):
return torch.ops.dgl_sparse.reduce(input.c_sparse_matrix, rtype, dim)
def sum(input: SparseMatrix, dim: Optional[int] = None... | --- +++ @@ -1,3 +1,4 @@+"""DGL sparse matrix reduce operators"""
# pylint: disable=W0622
from typing import Optional
@@ -8,26 +9,374 @@
def reduce(input: SparseMatrix, dim: Optional[int] = None, rtype: str = "sum"):
+ """Computes the reduction of non-zero values of the :attr:`input` sparse
+ matrix along ... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/sparse/reduction.py |
Add docstrings for better understanding | # pylint: disable= invalid-name
from typing import Optional, Tuple
import torch
class SparseMatrix:
def __init__(self, c_sparse_matrix: torch.ScriptObject):
self.c_sparse_matrix = c_sparse_matrix
def __repr__(self):
return _sparse_matrix_str(self)
@property
def val(self) -> torch.T... | --- +++ @@ -1,3 +1,4 @@+"""DGL sparse matrix module."""
# pylint: disable= invalid-name
from typing import Optional, Tuple
@@ -5,6 +6,7 @@
class SparseMatrix:
+ r"""Class for sparse matrix."""
def __init__(self, c_sparse_matrix: torch.ScriptObject):
self.c_sparse_matrix = c_sparse_matrix
@@ -... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/sparse/sparse_matrix.py |
Add return value explanations in docstrings | # pylint: disable=anomalous-backslash-in-string
from typing import Union
from .sparse_matrix import SparseMatrix
from .utils import Scalar
__all__ = ["add", "sub", "mul", "div", "power"]
def add(A: SparseMatrix, B: SparseMatrix) -> SparseMatrix:
return A + B
def sub(A: SparseMatrix, B: SparseMatrix) -> Sparse... | --- +++ @@ -1,4 +1,5 @@ # pylint: disable=anomalous-backslash-in-string
+"""DGL elementwise operator module."""
from typing import Union
from .sparse_matrix import SparseMatrix
@@ -8,22 +9,193 @@
def add(A: SparseMatrix, B: SparseMatrix) -> SparseMatrix:
+ r"""Elementwise addition for ``SparseMatrix``, equiv... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/sparse/elementwise_op.py |
Expand my code with proper documentation strings | # pylint: disable=invalid-name
from typing import Union
import torch
from .sparse_matrix import SparseMatrix
__all__ = ["spmm", "bspmm", "spspmm", "matmul"]
def spmm(A: SparseMatrix, X: torch.Tensor) -> torch.Tensor:
assert isinstance(
A, SparseMatrix
), f"Expect arg1 to be a SparseMatrix object, g... | --- +++ @@ -1,3 +1,4 @@+"""Matmul ops for SparseMatrix"""
# pylint: disable=invalid-name
from typing import Union
@@ -9,6 +10,33 @@
def spmm(A: SparseMatrix, X: torch.Tensor) -> torch.Tensor:
+ """Multiplies a sparse matrix by a dense matrix, equivalent to ``A @ X``.
+
+ Parameters
+ ----------
+ A ... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/sparse/matmul.py |
Add docstrings to incomplete code | # pylint: disable= no-member, arguments-differ, invalid-name, W0235
import torch
import torch.nn as nn
class TransE(nn.Module):
def __init__(self, num_rels, feats, p=1):
super(TransE, self).__init__()
self.rel_emb = nn.Embedding(num_rels, feats)
self.p = p
def reset_parameters(self)... | --- +++ @@ -1,9 +1,59 @@+"""TransE."""
# pylint: disable= no-member, arguments-differ, invalid-name, W0235
import torch
import torch.nn as nn
class TransE(nn.Module):
+ r"""Similarity measure from `Translating Embeddings for Modeling Multi-relational Data
+ <https://papers.nips.cc/paper/2013/hash/1cecc7a7... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/nn/pytorch/link/transe.py |
Expand my code with proper documentation strings |
import threading
STORAGE_WRAPPERS = {}
def register_storage_wrapper(type_):
def deco(cls):
STORAGE_WRAPPERS[type_] = cls
return cls
return deco
def wrap_storage(storage):
for type_, storage_cls in STORAGE_WRAPPERS.items():
if isinstance(storage, type_):
return sto... | --- +++ @@ -1,3 +1,4 @@+"""Base classes and functionalities for feature storages."""
import threading
@@ -5,6 +6,7 @@
def register_storage_wrapper(type_):
+ """Decorator that associates a type to a ``FeatureStorage`` object."""
def deco(cls):
STORAGE_WRAPPERS[type_] = cls
@@ -14,6 +16,9 @@
... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/storages/base.py |
Create docstrings for reusable components | # pylint: disable= no-member, arguments-differ, invalid-name, W0235
import torch
import torch.nn as nn
import torch.nn.functional as F
class EdgePredictor(nn.Module):
def __init__(self, op, in_feats=None, out_feats=None, bias=False):
super(EdgePredictor, self).__init__()
assert op in [
... | --- +++ @@ -1,3 +1,4 @@+"""Predictor for edges in homogeneous graphs."""
# pylint: disable= no-member, arguments-differ, invalid-name, W0235
import torch
import torch.nn as nn
@@ -5,6 +6,103 @@
class EdgePredictor(nn.Module):
+ r"""Predictor/score function for pairs of node representations
+
+ Given a pair... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/nn/pytorch/link/edgepred.py |
Generate consistent docstrings | import numpy as np
from .. import backend as F
from .base import FeatureStorage, register_storage_wrapper, ThreadedFuture
@register_storage_wrapper(np.memmap)
class NumpyStorage(FeatureStorage):
def __init__(self, arr):
self.arr = arr
# pylint: disable=unused-argument
def _fetch(self, indices, ... | --- +++ @@ -1,3 +1,4 @@+"""Feature storage for ``numpy.memmap`` object."""
import numpy as np
from .. import backend as F
@@ -6,6 +7,7 @@
@register_storage_wrapper(np.memmap)
class NumpyStorage(FeatureStorage):
+ """FeatureStorage that asynchronously reads features from a ``numpy.memmap`` object."""
de... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/storages/numpy.py |
Include argument descriptions in docstrings | from collections.abc import Mapping
from . import backend as F, graph_index, heterograph_index, utils
from ._ffi.function import _init_api
from .base import DGLError
from .heterograph import DGLGraph
from .utils import context_of, recursive_apply
__all__ = [
"node_subgraph",
"edge_subgraph",
"node_type_su... | --- +++ @@ -1,3 +1,8 @@+"""Functions for extracting subgraphs.
+
+The module only contains functions for extracting subgraphs deterministically.
+For stochastic subgraph extraction, please see functions under :mod:`dgl.sampling`.
+"""
from collections.abc import Mapping
from . import backend as F, graph_index, hete... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/subgraph.py |
Annotate my code with docstrings | from numbers import Number
from typing import Union
import torch
def is_scalar(x):
return isinstance(x, Number) or (torch.is_tensor(x) and x.dim() == 0)
# Scalar type annotation
Scalar = Union[Number, torch.Tensor] | --- +++ @@ -1,3 +1,4 @@+"""Utilities for DGL sparse module."""
from numbers import Number
from typing import Union
@@ -5,8 +6,9 @@
def is_scalar(x):
+ """Check if the input is a scalar."""
return isinstance(x, Number) or (torch.is_tensor(x) and x.dim() == 0)
# Scalar type annotation
-Scalar = Union... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/sparse/utils.py |
Add docstrings for production code | from __future__ import absolute_import
from . import backend as F, utils
from ._ffi.function import _init_api
from .heterograph import DGLGraph
__all__ = [
"bfs_nodes_generator",
"bfs_edges_generator",
"topological_nodes_generator",
"dfs_edges_generator",
"dfs_labeled_edges_generator",
]
def bfs... | --- +++ @@ -1,3 +1,4 @@+"""Module for graph traversal methods."""
from __future__ import absolute_import
from . import backend as F, utils
@@ -14,6 +15,35 @@
def bfs_nodes_generator(graph, source, reverse=False):
+ """Node frontiers generator using breadth-first search.
+
+ Parameters
+ ----------
+ ... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/traversal.py |
Insert docstrings into my code | # pylint: disable= no-member, arguments-differ, invalid-name
import torch as th
from torch import nn
from torch.nn import init
from .... import function as fn
from ....base import DGLError
from ....utils import expand_as_pair
from ..utils import Identity
class GMMConv(nn.Module):
def __init__(
self,
... | --- +++ @@ -1,3 +1,4 @@+"""Torch Module for GMM Conv"""
# pylint: disable= no-member, arguments-differ, invalid-name
import torch as th
from torch import nn
@@ -10,6 +11,98 @@
class GMMConv(nn.Module):
+ r"""Gaussian Mixture Model Convolution layer from `Geometric Deep
+ Learning on Graphs and Manifolds us... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/nn/pytorch/conv/gmmconv.py |
Write docstrings for backend logic | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import glob
import os
import shutil
import sys
import sysconfig
from setuptools import find_packages, setup
from setuptools.dist import Distribution
from setuptools.extension import Extension
class BinaryDistribution(Distribution):
def has_ext_modules(self):
... | --- +++ @@ -20,6 +20,7 @@
def get_lib_path():
+ """Get library path, name and version"""
# We can not import `libinfo.py` in setup.py directly since __init__.py
# Will be invoked which introduces dependences
libinfo_py = os.path.join(CURRENT_DIR, "./dgl/_ffi/libinfo.py")
@@ -92,6 +93,7 @@
def ... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/setup.py |
Add docstrings to improve collaboration | from __future__ import absolute_import
class EdgeBatch(object):
def __init__(self, graph, eid, etype, src_data, edge_data, dst_data):
self._graph = graph
self._eid = eid
self._etype = etype
self._src_data = src_data
self._edge_data = edge_data
self._dst_data = dst_... | --- +++ @@ -1,7 +1,25 @@+"""User-defined function related data structures."""
from __future__ import absolute_import
class EdgeBatch(object):
+ """The class that can represent a batch of edges.
+
+ Parameters
+ ----------
+ graph : DGLGraph
+ Graph object.
+ eid : Tensor
+ Edge IDs.
+... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/udf.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.