instruction stringclasses 100
values | code stringlengths 78 193k | response stringlengths 259 170k | file stringlengths 59 203 |
|---|---|---|---|
Auto-generate documentation strings for this file | from __future__ import absolute_import
import os
import numpy as np
from .. import backend as F
from ..convert import graph as dgl_graph
from .dgl_dataset import DGLBuiltinDataset
from .utils import load_graphs, load_info, loadtxt, save_graphs, save_info
class LegacyTUDataset(DGLBuiltinDataset):
_url = r"htt... | --- +++ @@ -12,6 +12,72 @@
class LegacyTUDataset(DGLBuiltinDataset):
+ r"""LegacyTUDataset contains lots of graph kernel datasets for graph classification.
+
+ Parameters
+ ----------
+ name : str
+ Dataset Name, such as ``ENZYMES``, ``DD``, ``COLLAB``, ``MUTAG``, can be the
+ datasets nam... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/data/tu.py |
Fully document this Python code with docstrings |
import os
import numpy as np
from .. import backend as F
from ..convert import graph as dgl_graph
from .dgl_dataset import DGLDataset
from .utils import _get_dgl_url, download, extract_archive
class QM9EdgeDataset(DGLDataset):
keys = [
"mu",
"alpha",
"homo",
"lumo",
"g... | --- +++ @@ -1,3 +1,4 @@+""" QM9 dataset for graph property prediction (regression) """
import os
@@ -11,6 +12,124 @@
class QM9EdgeDataset(DGLDataset):
+ r"""QM9Edge dataset for graph property prediction (regression)
+
+ This dataset consists of 130,831 molecules with 19 regression targets.
+ Nodes cor... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/data/qm9_edge.py |
Add docstrings for utility scripts | from __future__ import absolute_import
import os
import numpy as np
import scipy.sparse as sp
from .. import backend as F
from ..convert import from_scipy
from ..transforms import reorder_graph
from .dgl_dataset import DGLBuiltinDataset
from .utils import (
_get_dgl_url,
deprecate_property,
generate_ma... | --- +++ @@ -1,3 +1,4 @@+""" Reddit dataset for community detection """
from __future__ import absolute_import
import os
@@ -21,6 +22,66 @@
class RedditDataset(DGLBuiltinDataset):
+ r"""Reddit dataset for community detection (node classification)
+
+ This is a graph dataset from Reddit posts made in the mo... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/data/reddit.py |
Document all endpoints with docstrings | import os
import pickle
import numpy as np
from scipy.spatial.distance import cdist
from tqdm.auto import tqdm
from .. import backend as F
from ..convert import graph as dgl_graph
from .dgl_dataset import DGLDataset
from .utils import download, extract_archive, load_graphs, save_graphs, Subset
def sigma(dists, kth... | --- +++ @@ -108,20 +108,24 @@
@property
def img_size(self):
+ r"""Size of dataset image."""
if self._dataset_name == "MNIST":
return 28
return 32
@property
def save_path(self):
+ r"""Directory to save the processed dataset."""
return os.path.j... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/data/superpixel.py |
Help me write clear docstrings | import os
import numpy as np
import scipy.sparse as sp
from .. import backend as F, transforms
from ..convert import graph as dgl_graph
from .dgl_dataset import DGLBuiltinDataset
from .utils import (
_get_dgl_url,
deprecate_class,
deprecate_property,
load_graphs,
save_graphs,
)
__all__ = [
"... | --- +++ @@ -1,3 +1,4 @@+"""GNN Benchmark datasets for node classification."""
import os
import numpy as np
@@ -28,6 +29,7 @@
def eliminate_self_loops(A):
+ """Remove self-loops from the adjacency matrix."""
A = A.tolil()
A.setdiag(0)
A = A.tocsr()
@@ -36,6 +38,10 @@
class GNNBenchmarkDatas... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/data/gnn_benchmark.py |
Improve my code by adding docstrings | import os
import numpy as np
import scipy.sparse as sp
from .. import backend as F
from ..convert import graph
from .dgl_dataset import DGLBuiltinDataset
from .utils import _get_dgl_url, load_graphs, load_info, save_graphs, save_info
class FakeNewsDataset(DGLBuiltinDataset):
file_urls = {
"gossipcop": "... | --- +++ @@ -10,6 +10,108 @@
class FakeNewsDataset(DGLBuiltinDataset):
+ r"""Fake News Graph Classification dataset.
+
+ The dataset is composed of two sets of tree-structured fake/real
+ news propagation graphs extracted from Twitter. Different from
+ most of the benchmark datasets for the graph classif... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/data/fakenews.py |
Add structured docstrings to improve clarity | import math
import os
import pickle
import random
import networkx as nx
import numpy as np
from .. import backend as F
from ..batch import batch
from ..convert import graph
from ..transforms import reorder_graph
from .dgl_dataset import DGLBuiltinDataset
from .utils import _get_dgl_url, download, load_graphs, save_gr... | --- +++ @@ -1,3 +1,4 @@+"""Synthetic graph datasets."""
import math
import os
import pickle
@@ -15,6 +16,62 @@
class BAShapeDataset(DGLBuiltinDataset):
+ r"""BA-SHAPES dataset from `GNNExplainer: Generating Explanations for Graph Neural Networks
+ <https://arxiv.org/abs/1903.03894>`__
+
+ This is a synt... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/data/synthetic.py |
Document this script properly | import os
from .dgl_dataset import DGLBuiltinDataset
from .utils import _get_dgl_url, load_graphs
class ZINCDataset(DGLBuiltinDataset):
def __init__(
self,
mode="train",
raw_dir=None,
force_reload=False,
verbose=False,
transform=None,
):
self._url = _g... | --- +++ @@ -5,6 +5,67 @@
class ZINCDataset(DGLBuiltinDataset):
+ r"""ZINC dataset for the graph regression task.
+
+ A subset (12K) of ZINC molecular graphs (250K) dataset is used to
+ regress a molecular property known as the constrained solubility.
+ For each molecular graph, the node features are the... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/data/zinc.py |
Create docstrings for reusable components | import os
import numpy as np
from ..convert import graph
from .dgl_dataset import DGLBuiltinDataset
from .utils import _get_dgl_url
class GeomGCNDataset(DGLBuiltinDataset):
def __init__(self, name, raw_dir, force_reload, verbose, transform):
url = _get_dgl_url(f"dataset/{name}.zip")
super(GeomG... | --- +++ @@ -1,3 +1,4 @@+"""Datasets introduced in the Geom-GCN paper."""
import os
import numpy as np
@@ -8,6 +9,25 @@
class GeomGCNDataset(DGLBuiltinDataset):
+ r"""Datasets introduced in
+ `Geom-GCN: Geometric Graph Convolutional Networks
+ <https://arxiv.org/abs/2002.05287>`__
+
+ Parameters
+ ... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/data/geom_gcn.py |
Auto-generate documentation strings for this file | import torch as th
from ..._sparse_ops import (
_bwd_segment_cmp,
_csrmask,
_csrmm,
_csrsum,
_edge_softmax_backward,
_edge_softmax_forward,
_gather_mm,
_gather_mm_scatter,
_gsddmm,
_gsddmm_hetero,
_gspmm,
_gspmm_hetero,
_scatter_add,
_segment_mm,
_segment_mm_... | --- +++ @@ -41,6 +41,22 @@
def _reduce_grad(grad, shape):
+ """Reduce gradient on the broadcast dimension
+ If there is broadcast in forward pass, gradients need to be reduced on
+ broadcast dimension. This function checks the input tensor shape and
+ gradient shape and perform the reduction.
+
+ Par... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/backend/pytorch/sparse.py |
Add docstrings to clarify complex logic | # pylint: disable=line-too-long
import atexit
import gc
import multiprocessing as mp
import os
import queue
import sys
import time
import traceback
from enum import Enum
from .. import utils
from ..base import dgl_warning, DGLError
from . import rpc
from .constants import MAX_QUEUE_SIZE
from .kvstore import close_kvs... | --- +++ @@ -1,3 +1,4 @@+"""Initialize the distributed services"""
# pylint: disable=line-too-long
import atexit
@@ -24,11 +25,13 @@
def set_initialized(value=True):
+ """Set the initialized state of rpc"""
global INITIALIZED
INITIALIZED = value
def get_sampler_pool():
+ """Return the sample... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/distributed/dist_context.py |
Write docstrings including parameters and return values |
import gc
import os
from collections import namedtuple
from collections.abc import Mapping, MutableMapping
import numpy as np
import torch
from .. import backend as F, graphbolt as gb, heterograph_index
from .._ffi.ndarray import empty_shared_mem
from ..base import ALL, DGLError, EID, ETYPE, is_all, NID
from ..conv... | --- +++ @@ -1,3 +1,4 @@+"""Define distributed graph."""
import gc
@@ -56,6 +57,12 @@
class InitGraphRequest(rpc.Request):
+ """Init graph on the backup servers.
+
+ When the backup server starts, they don't load the graph structure.
+ This request tells the backup servers that they can map to the grap... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/distributed/dist_graph.py |
Add docstrings to improve collaboration |
import os
from collections import namedtuple
import numpy as np
import torch
from .. import backend as F, graphbolt as gb
from ..base import EID, ETYPE, NID
from ..convert import graph, heterograph
from ..sampling import (
sample_etype_neighbors as local_sample_etype_neighbors,
sample_neighbors as local_sam... | --- +++ @@ -1,3 +1,4 @@+"""A set of graph services of getting subgraphs from DistGraph"""
import os
from collections import namedtuple
@@ -40,6 +41,7 @@
class SubgraphResponse(Response):
+ """The response for sampling and in_subgraph"""
def __init__(
self, global_src, global_dst, *, global_ei... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/distributed/graph_services.py |
Create docstrings for reusable components | import abc
import warnings
from abc import abstractmethod
from os.path import exists
import torch as th
import dgl
from .... import backend as F
from ...dist_tensor import DistTensor
from ...graph_partition_book import EDGE_PART_POLICY, NODE_PART_POLICY
from ...nn.pytorch import DistEmbedding
from .utils import allt... | --- +++ @@ -1,3 +1,4 @@+"""Node embedding optimizers for distributed training"""
import abc
import warnings
from abc import abstractmethod
@@ -21,6 +22,17 @@
class DistSparseGradOptimizer(abc.ABC):
+ r"""The abstract dist sparse optimizer.
+
+ Note: dgl dist sparse optimizer only work with dgl.distributed.... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/distributed/optim/pytorch/sparse_optim.py |
Can you add docstrings to this Python file? | # pylint: disable=global-variable-undefined, invalid-name
import inspect
from abc import ABC, abstractmethod
from collections.abc import Mapping
from .. import backend as F, transforms, utils
from ..base import EID, NID
from ..convert import heterograph
from .dist_context import get_sampler_pool
__all__ = [
"Node... | --- +++ @@ -1,4 +1,5 @@ # pylint: disable=global-variable-undefined, invalid-name
+"""Multiprocess dataloader for distributed training"""
import inspect
from abc import ABC, abstractmethod
from collections.abc import Mapping
@@ -20,6 +21,57 @@
class DistDataLoader:
+ """DGL customized multiprocessing dataload... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/distributed/dist_dataloader.py |
Generate helpful docstrings for debugging |
import torch as th
from .... import backend as F, utils
from ...dist_tensor import DistTensor
class DistEmbedding:
def __init__(
self,
num_embeddings,
embedding_dim,
name=None,
init_func=None,
part_policy=None,
):
self._tensor = DistTensor(
... | --- +++ @@ -1,3 +1,4 @@+"""Define sparse embedding and optimizer."""
import torch as th
@@ -6,6 +7,64 @@
class DistEmbedding:
+ """Distributed node embeddings.
+
+ DGL provides a distributed embedding to support models that require learnable embeddings.
+ DGL's distributed embeddings are mainly used f... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/distributed/nn/pytorch/sparse_emb.py |
Generate missing documentation strings |
import pickle
from abc import ABC
import numpy as np
from .. import backend as F, utils
from .._ffi.ndarray import empty_shared_mem
from ..base import DGLError
from ..ndarray import exist_shared_mem_array
from ..partition import NDArrayPartition
from .constants import DEFAULT_ETYPE, DEFAULT_NTYPE
from .id_map import... | --- +++ @@ -1,3 +1,4 @@+"""Define graph partition book."""
import pickle
from abc import ABC
@@ -22,6 +23,16 @@
def _etype_tuple_to_str(c_etype):
+ """Convert canonical etype from tuple to string.
+
+ Examples
+ --------
+ >>> c_etype = ('user', 'like', 'item')
+ >>> c_etype_str = _etype_tuple_to... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/distributed/graph_partition_book.py |
Add docstrings to improve code quality | import os
import numpy as np
import pandas as pd
from torch import LongTensor, Tensor
from ..base import dgl_warning
from ..convert import heterograph
from .dgl_dataset import DGLDataset
from .utils import (
_get_dgl_url,
download,
extract_archive,
load_graphs,
load_info,
save_graphs,
sa... | --- +++ @@ -1,3 +1,4 @@+"""MovieLens dataset"""
import os
import numpy as np
@@ -53,6 +54,7 @@
def check_pytorch():
+ """Check if PyTorch is the backend."""
if not HAS_TORCH:
raise ModuleNotFoundError(
"MovieLensDataset requires PyTorch to be the backend."
@@ -60,6 +62,102 @@
c... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/data/movielens.py |
Replace inline comments with docstrings | import os
from .dgl_dataset import DGLBuiltinDataset
from .utils import _get_dgl_url, load_graphs
class PATTERNDataset(DGLBuiltinDataset):
def __init__(
self,
mode="train",
raw_dir=None,
force_reload=False,
verbose=False,
transform=None,
):
assert mode... | --- +++ @@ -1,3 +1,4 @@+""" PATTERNDataset for inductive learning. """
import os
from .dgl_dataset import DGLBuiltinDataset
@@ -5,6 +6,61 @@
class PATTERNDataset(DGLBuiltinDataset):
+ r"""PATTERN dataset for graph pattern recognition task.
+
+ Each graph G contains 5 communities with sizes randomly select... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/data/pattern.py |
Create docstrings for reusable components |
import os
from .. import backend as F, utils
from .dist_context import is_initialized
from .kvstore import get_kvstore
from .role import get_role
from .rpc import get_group_id
def _default_init_data(shape, dtype):
return F.zeros(shape, dtype, F.cpu())
# These IDs can identify the anonymous distributed tensor... | --- +++ @@ -1,3 +1,4 @@+"""Define distributed tensor."""
import os
@@ -18,6 +19,94 @@
class DistTensor:
+ """Distributed tensor.
+
+ ``DistTensor`` references to a distributed tensor sharded and stored in a cluster of machines.
+ It has the same interface as Pytorch Tensor to access its metadata (e.g.... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/distributed/dist_tensor.py |
Annotate my code with docstrings | import torch as th
import torch.distributed as dist
def alltoall_cpu(rank, world_size, output_tensor_list, input_tensor_list):
input_tensor_list = [
tensor.to(th.device("cpu")) for tensor in input_tensor_list
]
for i in range(world_size):
dist.scatter(
output_tensor_list[i], in... | --- +++ @@ -1,8 +1,24 @@+"""Provide utils for distributed sparse optimizers
+"""
import torch as th
import torch.distributed as dist
def alltoall_cpu(rank, world_size, output_tensor_list, input_tensor_list):
+ """Each process scatters list of input tensors to all processes in a cluster
+ and return gathere... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/distributed/optim/pytorch/utils.py |
Add verbose docstrings with examples |
import numpy as np
import torch
from .. import backend as F, utils
from .._ffi.function import _init_api
__all__ = ["IdMap"]
class IdMap:
def __init__(self, id_ranges):
id_ranges_values = list(id_ranges.values())
assert isinstance(
id_ranges_values[0], np.ndarray
), "id_r... | --- +++ @@ -1,3 +1,4 @@+"""Module for mapping between node/edge IDs and node/edge types."""
import numpy as np
import torch
@@ -11,6 +12,97 @@
class IdMap:
+ """A map for converting node/edge IDs to their type IDs and type-wise IDs.
+
+ For a heterogeneous graph, DGL assigns an integer ID to each node/edg... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/distributed/id_map.py |
Help me add docstrings to my project |
import atexit
import logging
import os
import socket
import time
from . import rpc
from .constants import MAX_QUEUE_SIZE
if os.name != "nt":
import fcntl
import struct
def local_ip4_addr_list():
assert os.name != "nt", "Do not support Windows rpc yet."
nic = set()
logger = logging.getLogger("dg... | --- +++ @@ -1,3 +1,4 @@+"""Functions used by client."""
import atexit
import logging
@@ -14,6 +15,12 @@
def local_ip4_addr_list():
+ """Return a set of IPv4 address
+
+ You can use
+ `logging.getLogger("dgl-distributed-socket").setLevel(logging.WARNING+1)`
+ to disable the warning here
+ """
... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/distributed/rpc_client.py |
Generate docstrings for this script |
from .._ffi.function import _init_api
# Remove C++ bindings for now, since not used
class ServerState:
def __init__(self, kv_store, local_g, partition_book, use_graphbolt=False):
self._kv_store = kv_store
self._graph = local_g
self.partition_book = partition_book
self._roles = {... | --- +++ @@ -1,3 +1,4 @@+"""Server data"""
from .._ffi.function import _init_api
@@ -5,6 +6,41 @@
class ServerState:
+ """Data stored in one DGL server.
+
+ In a distributed setting, DGL partitions all data associated with the graph
+ (e.g., node and edge features, graph structure, etc.) to multiple pa... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/distributed/server_state.py |
Generate NumPy-style docstrings | import abc
import os
import pickle
import random
import numpy as np
from .. import backend as F
from .._ffi.function import _init_api
from .._ffi.object import ObjectBase, register_object
from ..base import DGLError
from .constants import SERVER_EXIT
__all__ = [
"set_rank",
"get_rank",
"Request",
"Re... | --- +++ @@ -1,3 +1,5 @@+"""RPC components. They are typically functions or utilities used by both
+server and clients."""
import abc
import os
import pickle
@@ -52,6 +54,53 @@
def read_ip_config(filename, num_servers):
+ """Read network configuration information of server from file.
+
+ For exampple, the f... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/distributed/rpc.py |
Write Python docstrings for this snippet |
import os
import numpy as np
from . import rpc
REGISTER_ROLE = 700001
REG_ROLE_MSG = "Register_Role"
class RegisterRoleResponse(rpc.Response):
def __init__(self, msg):
self.msg = msg
def __getstate__(self):
return self.msg
def __setstate__(self, state):
self.msg = state
cl... | --- +++ @@ -1,3 +1,8 @@+"""Manage the roles in different clients.
+
+Right now, the clients have different roles. Some clients work as samplers and
+some work as trainers.
+"""
import os
@@ -10,6 +15,9 @@
class RegisterRoleResponse(rpc.Response):
+ """Send a confirmation signal (just a short string message)... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/distributed/role.py |
Add docstrings that explain inputs and outputs |
from .. import backend as F
class KVClient(object):
def __init__(self):
self._data = {}
self._all_possible_part_policy = {}
self._push_handlers = {}
self._pull_handlers = {}
# Store all graph data name
self._gdata_name_list = set()
@property
def all_possi... | --- +++ @@ -1,8 +1,17 @@+"""Define a fake kvstore
+
+This kvstore is used when running in the standalone mode
+"""
from .. import backend as F
class KVClient(object):
+ """The fake KVStore client.
+
+ This is to mimic the distributed KVStore client. It's used for DistGraph
+ in standalone mode.
+ ""... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/distributed/standalone_kvstore.py |
Please document this code using docstrings |
import os
import numpy as np
from .. import backend as F, utils
from .._ffi.ndarray import empty_shared_mem
from . import rpc
from .graph_partition_book import EdgePartitionPolicy, NodePartitionPolicy
from .standalone_kvstore import KVClient as SA_KVClient
############################ Register KVStore Requsts and ... | --- +++ @@ -1,3 +1,4 @@+"""Define distributed kvstore"""
import os
@@ -16,6 +17,15 @@
class PullResponse(rpc.Response):
+ """Send the sliced data tensor back to the client.
+
+ Parameters
+ ----------
+ server_id : int
+ ID of current server
+ data_tensor : tensor
+ sliced data ten... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/distributed/kvstore.py |
Create docstrings for all classes and functions |
import concurrent
import concurrent.futures
import copy
import json
import logging
import multiprocessing as mp
import os
import time
from functools import partial
import numpy as np
import torch
from .. import backend as F, graphbolt as gb
from ..base import dgl_warning, DGLError, EID, ETYPE, NID, NTYPE
from ..con... | --- +++ @@ -1,3 +1,4 @@+"""Functions for partitions. """
import concurrent
import concurrent.futures
@@ -48,6 +49,7 @@
def _format_part_metadata(part_metadata, formatter):
+ """Format etypes with specified formatter."""
for key in ["edge_map", "etypes"]:
if key not in part_metadata:
... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/distributed/partition.py |
Include argument descriptions in docstrings | import networkx as nx
import numpy as np
from .. import backend as F
from ..convert import from_networkx
from .dgl_dataset import DGLDataset
from .utils import deprecate_property
__all__ = ["KarateClubDataset", "KarateClub"]
class KarateClubDataset(DGLDataset):
def __init__(self, transform=None):
super... | --- +++ @@ -1,3 +1,5 @@+"""KarateClub Dataset
+"""
import networkx as nx
import numpy as np
@@ -10,6 +12,40 @@
class KarateClubDataset(DGLDataset):
+ r"""Karate Club dataset for Node Classification
+
+ Zachary's karate club is a social network of a university
+ karate club, described in the paper "An I... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/data/karate.py |
Write docstrings for this repository | # pylint: disable=redefined-builtin
from __future__ import absolute_import
import sys
from .base import BuiltinFunction
class ReduceFunction(BuiltinFunction):
@property
def name(self):
raise NotImplementedError
class SimpleReduceFunction(ReduceFunction):
def __init__(self, name, msg_field, o... | --- +++ @@ -1,3 +1,4 @@+"""Built-in reducer function."""
# pylint: disable=redefined-builtin
from __future__ import absolute_import
@@ -7,13 +8,17 @@
class ReduceFunction(BuiltinFunction):
+ """Base builtin reduce function class."""
@property
def name(self):
+ """Return the name of this bu... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/function/reducer.py |
Add docstrings that explain inputs and outputs | import os
import numpy as np
from .. import backend as F
from ..convert import graph as dgl_graph
from .dgl_dataset import DGLBuiltinDataset
from .utils import _get_dgl_url, load_graphs, loadtxt, save_graphs
class ICEWS18Dataset(DGLBuiltinDataset):
def __init__(
self,
mode="train",
raw_... | --- +++ @@ -1,3 +1,4 @@+"""ICEWS18 dataset for temporal graph"""
import os
import numpy as np
@@ -9,6 +10,62 @@
class ICEWS18Dataset(DGLBuiltinDataset):
+ r"""ICEWS18 dataset for temporal graph
+
+ Integrated Crisis Early Warning System (ICEWS18)
+
+ Event data consists of coded interactions between so... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/data/icews18.py |
Write documentation strings for class attributes | # pylint: disable=no-member, invalid-name
from .. import backend as F
from ..base import DGLError
from .capi import _farthest_point_sampler
__all__ = ["farthest_point_sampler"]
def farthest_point_sampler(pos, npoints, start_idx=None):
ctx = F.context(pos)
B, N, C = pos.shape
pos = pos.reshape(-1, C)
... | --- +++ @@ -1,3 +1,4 @@+"""Farthest Point Sampler for pytorch Geometry package"""
# pylint: disable=no-member, invalid-name
from .. import backend as F
@@ -8,6 +9,41 @@
def farthest_point_sampler(pos, npoints, start_idx=None):
+ """Farthest Point Sampler without the need to compute all pairs of distance.
+
+... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/geometry/fps.py |
Document this module using docstrings | from __future__ import absolute_import
import sys
from itertools import product
from .base import BuiltinFunction, TargetCode
__all__ = ["copy_u", "copy_e", "BinaryMessageFunction", "CopyMessageFunction"]
class MessageFunction(BuiltinFunction):
@property
def name(self):
raise NotImplementedError
... | --- +++ @@ -1,3 +1,4 @@+"""Built-in message function."""
from __future__ import absolute_import
import sys
@@ -10,13 +11,21 @@
class MessageFunction(BuiltinFunction):
+ """Base builtin message function class."""
@property
def name(self):
+ """Return the name of this builtin function."""
... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/function/message.py |
Add docstrings to my Python code | import numpy as np
from .. import backend as F, ndarray as nd
from .._ffi.base import DGLError
from .._ffi.function import _init_api
def _farthest_point_sampler(
data, batch_size, sample_points, dist, start_idx, result
):
assert F.shape(data)[0] >= sample_points * batch_size
assert F.shape(data)[0] % bat... | --- +++ @@ -1,3 +1,4 @@+"""Python interfaces to DGL farthest point sampler."""
import numpy as np
from .. import backend as F, ndarray as nd
@@ -8,6 +9,28 @@ def _farthest_point_sampler(
data, batch_size, sample_points, dist, start_idx, result
):
+ r"""Farthest Point Sampler
+
+ Parameters
+ --------... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/geometry/capi.py |
Document helper functions with docstrings | # pylint: disable=no-member, invalid-name, W0613
from .. import remove_self_loop
from .capi import _neighbor_matching
__all__ = ["neighbor_matching"]
def neighbor_matching(graph, e_weights=None, relabel_idx=True):
assert (
graph.is_homogeneous
), "The graph used in graph node matching must be homogen... | --- +++ @@ -1,3 +1,4 @@+"""Edge coarsening procedure used in Metis and Graclus, for pytorch"""
# pylint: disable=no-member, invalid-name, W0613
from .. import remove_self_loop
from .capi import _neighbor_matching
@@ -6,6 +7,48 @@
def neighbor_matching(graph, e_weights=None, relabel_idx=True):
+ r"""
+ Desc... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/geometry/edge_coarsening.py |
Generate docstrings with examples | import os
import numpy as np
from ..convert import graph
from ..transforms.functional import to_bidirected
from .dgl_dataset import DGLBuiltinDataset
from .utils import download
class HeterophilousGraphDataset(DGLBuiltinDataset):
def __init__(
self,
name,
raw_dir=None,
force_rel... | --- +++ @@ -1,3 +1,7 @@+"""
+Datasets introduced in the 'A Critical Look at the Evaluation of GNNs under Heterophily: Are We
+Really Making Progress? <https://arxiv.org/abs/2302.11640>'__ paper.
+"""
import os
import numpy as np
@@ -9,6 +13,25 @@
class HeterophilousGraphDataset(DGLBuiltinDataset):
+ r"""Data... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/data/heterophilous_graphs.py |
Write docstrings for utility functions | import inspect
from collections.abc import Mapping
from .. import backend as F
from ..base import EID, NID
from ..convert import heterograph
from ..frame import LazyFeature
from ..transforms import compact_graphs
from ..utils import context_of, recursive_apply
def _set_lazy_features(x, xdata, feature_names):
if ... | --- +++ @@ -1,3 +1,4 @@+"""Base classes and functionalities for dataloaders"""
import inspect
from collections.abc import Mapping
@@ -20,28 +21,205 @@
def set_node_lazy_features(g, feature_names):
+ """Assign lazy features to the ``ndata`` of the input graph for prefetching optimization.
+
+ When used in ... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/dataloading/base.py |
Document helper functions with docstrings | from __future__ import absolute_import
__all__ = ["BuiltinFunction", "TargetCode"]
class TargetCode(object):
SRC = 0
DST = 1
EDGE = 2
CODE2STR = {
0: "u",
1: "v",
2: "e",
}
class BuiltinFunction(object):
@property
def name(self):
raise NotImplementedEr... | --- +++ @@ -1,9 +1,15 @@+"""Built-in function base class"""
from __future__ import absolute_import
__all__ = ["BuiltinFunction", "TargetCode"]
class TargetCode(object):
+ """Code for target
+
+ Note: must be consistent with the target code definition in C++ side:
+ src/kernel/binary_reduce_commo... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/function/base.py |
Add docstrings to make code maintainable | from ._ffi.function import _init_api
__all__ = ["is_libxsmm_enabled", "use_libxsmm"]
def use_libxsmm(flag):
_CAPI_DGLConfigSetLibxsmm(flag)
def is_libxsmm_enabled():
return _CAPI_DGLConfigGetLibxsmm()
_init_api("dgl.global_config") | --- +++ @@ -1,14 +1,40 @@+"""Module for global configuration operators."""
from ._ffi.function import _init_api
__all__ = ["is_libxsmm_enabled", "use_libxsmm"]
def use_libxsmm(flag):
+ r"""Set whether DGL uses libxsmm at runtime.
+
+ Detailed information about libxsmm can be found here:
+ https://gith... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/global_config.py |
Write beginner-friendly docstrings |
from functools import partial
from typing import Dict
import torch
from torch.utils.data import functional_datapipe
from .base import etype_tuple_to_str
from .impl.cooperative_conv import CooperativeConvFunction
from .minibatch_transformer import MiniBatchTransformer
__all__ = [
"FeatureFetcher",
"Featur... | --- +++ @@ -1,3 +1,4 @@+"""Feature fetchers"""
from functools import partial
from typing import Dict
@@ -19,6 +20,7 @@
def get_feature_key_list(feature_keys, domain):
+ """Processes node_feature_keys and extracts their feature keys to a list."""
if isinstance(feature_keys, Dict):
return [
... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/graphbolt/feature_fetcher.py |
Create documentation for each function signature |
import torch
import torch.utils.data as torch_data
from .base import CopyTo
from .datapipes import (
datapipe_graph_to_adjlist,
find_dps,
replace_dp,
traverse_dps,
)
from .feature_fetcher import FeatureFetcher, FeatureFetcherStartMarker
from .impl.neighbor_sampler import SamplePerLayer
from .internal_... | --- +++ @@ -1,3 +1,4 @@+"""Graph Bolt DataLoaders"""
import torch
import torch.utils.data as torch_data
@@ -22,6 +23,7 @@
def _find_and_wrap_parent(datapipe_graph, target_datapipe, wrapper, **kwargs):
+ """Find parent of target_datapipe and wrap it with ."""
datapipes = find_dps(
datapipe_graph... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/graphbolt/dataloader.py |
Write docstrings describing each step | from functools import partial
from typing import Dict, Union
import torch
from torch.utils.data import functional_datapipe
from .minibatch import MiniBatch
from .minibatch_transformer import MiniBatchTransformer
@functional_datapipe("exclude_seed_edges")
class SeedEdgesExcluder(MiniBatchTransformer):
def __in... | --- +++ @@ -1,3 +1,4 @@+"""Utility functions for external use."""
from functools import partial
from typing import Dict, Union
@@ -11,6 +12,23 @@
@functional_datapipe("exclude_seed_edges")
class SeedEdgesExcluder(MiniBatchTransformer):
+ """A mini-batch transformer used to manipulate mini-batch.
+
+ Functi... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/graphbolt/external_utils.py |
Add clean documentation to messy code |
import textwrap
# pylint: disable= invalid-name
from typing import Dict, Optional, Union
import torch
from ..base import etype_str_to_tuple, etype_tuple_to_str, ORIGINAL_EDGE_ID
from ..internal_utils import gb_warning, is_wsl, recursive_apply
from ..sampling_graph import SamplingGraph
from .gpu_graph_cache import G... | --- +++ @@ -1,3 +1,4 @@+"""CSC format sampling graph."""
import textwrap
@@ -33,6 +34,7 @@ )
def wait(self):
+ """Returns the stored value when invoked."""
fn = self.fn
C_sampled_subgraph = self.future.wait()
seed_offsets = self.seed_offsets
@@ -50,6 +52,7 @@
cl... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/graphbolt/impl/fused_csc_sampling_graph.py |
Add docstrings that explain inputs and outputs | import os
import pickle
import numpy as np
from .. import backend as F
from ..base import DGLError
from ..partition import metis_partition_assignment
from .base import Sampler, set_edge_lazy_features, set_node_lazy_features
class ClusterGCNSampler(Sampler):
def __init__(
self,
g,
k,
... | --- +++ @@ -1,3 +1,4 @@+"""Cluster-GCN samplers."""
import os
import pickle
@@ -10,6 +11,56 @@
class ClusterGCNSampler(Sampler):
+ """Cluster sampler from `Cluster-GCN: An Efficient Algorithm for Training
+ Deep and Large Graph Convolutional Networks
+ <https://arxiv.org/abs/1905.07953>`__
+
+ This ... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/dataloading/cluster_gcn.py |
Create docstrings for reusable components |
from typing import Dict, List, Union
from .feature_store import FeatureStore
from .itemset import HeteroItemSet, ItemSet
from .sampling_graph import SamplingGraph
__all__ = [
"Task",
"Dataset",
]
class Task:
@property
def metadata(self) -> Dict:
raise NotImplementedError
@property
... | --- +++ @@ -1,3 +1,4 @@+"""GraphBolt Dataset."""
from typing import Dict, List, Union
@@ -12,42 +13,83 @@
class Task:
+ """An abstract task which consists of meta information and
+ Train/Validation/Test Set.
+
+ * meta information
+ The meta information of a task includes any kinds of data that... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/graphbolt/dataset.py |
Add docstrings to incomplete code | from collections.abc import Mapping
from .. import backend as F
class _BaseNegativeSampler(object):
def _generate(self, g, eids, canonical_etype):
raise NotImplementedError
def __call__(self, g, eids):
if isinstance(eids, Mapping):
eids = {g.to_canonical_etype(k): v for k, v in e... | --- +++ @@ -1,3 +1,4 @@+"""Negative samplers"""
from collections.abc import Mapping
from .. import backend as F
@@ -8,6 +9,20 @@ raise NotImplementedError
def __call__(self, g, eids):
+ """Returns negative samples.
+
+ Parameters
+ ----------
+ g : DGLGraph
+ Th... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/dataloading/negative_sampler.py |
Add docstrings explaining edge cases | from typing import Dict, Union
import torch
from ..feature_store import (
bytes_to_number_of_items,
Feature,
FeatureKey,
wrap_with_cached_feature,
)
from .gpu_feature_cache import GPUFeatureCache
__all__ = ["GPUCachedFeature", "gpu_cached_feature"]
class GPUCachedFeature(Feature):
_cache_type... | --- +++ @@ -1,3 +1,4 @@+"""GPU cached feature for GraphBolt."""
from typing import Dict, Union
import torch
@@ -15,6 +16,44 @@
class GPUCachedFeature(Feature):
+ r"""GPU cached feature wrapping a fallback feature. It uses the least
+ recently used (LRU) algorithm as the cache eviction policy. Use
+ `gp... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/graphbolt/impl/gpu_cached_feature.py |
Write docstrings for data processing functions |
import atexit
import inspect
import itertools
import math
import operator
import os
import re
import threading
from collections.abc import Mapping, Sequence
from contextlib import contextmanager
from functools import reduce
from queue import Empty, Full, Queue
import numpy as np
import psutil
import torch
import torc... | --- +++ @@ -1,3 +1,4 @@+"""DGL PyTorch DataLoaders"""
import atexit
import inspect
@@ -188,6 +189,9 @@
class TensorizedDataset(torch.utils.data.IterableDataset):
+ """Custom Dataset wrapper that returns a minibatch as tensors or dicts of tensors.
+ When the dataset is on the GPU, this significantly reduce... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/dataloading/dataloader.py |
Help me add docstrings to my project | #
# Copyright (c) 2022 by Contributors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... | --- +++ @@ -16,6 +16,7 @@ # Based off of neighbor_sampler.py
#
+"""Data loading components for labor sampling"""
from numpy.random import default_rng
from .. import backend as F
@@ -26,6 +27,116 @@
class LaborSampler(BlockSampler):
+ """Sampler that builds computational dependency of node representation... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/dataloading/labor_sampler.py |
Document functions with detailed explanations | from collections import defaultdict
import numpy as np
import torch
from ..sampling.utils import EidExcluder
from .base import Sampler, set_edge_lazy_features, set_node_lazy_features
class CappedNeighborSampler(Sampler):
def __init__(
self,
fanouts,
fixed_k,
upsample_rare_types,... | --- +++ @@ -1,3 +1,4 @@+"""Capped neighbor sampler."""
from collections import defaultdict
import numpy as np
@@ -8,6 +9,37 @@
class CappedNeighborSampler(Sampler):
+ """Subgraph sampler that sets an upper bound on the number of nodes included in
+ each layer of the sampled subgraph. At each layer, the fr... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/dataloading/capped_neighbor_sampler.py |
Write docstrings that follow conventions | from ..base import DGLError
from ..random import choice
from ..sampling import pack_traces, random_walk
from .base import Sampler, set_edge_lazy_features, set_node_lazy_features
try:
import torch
except ImportError:
pass
class SAINTSampler(Sampler):
def __init__(
self,
mode,
budg... | --- +++ @@ -1,3 +1,4 @@+"""GraphSAINT samplers."""
from ..base import DGLError
from ..random import choice
from ..sampling import pack_traces, random_walk
@@ -10,6 +11,61 @@
class SAINTSampler(Sampler):
+ """Random node/edge/walk sampler from
+ `GraphSAINT: Graph Sampling Based Inductive Learning Method
+ ... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/dataloading/graphsaint.py |
Turn comments into proper docstrings |
import threading
import time
from collections import deque
from typing import final, List, Set, Type # pylint: disable=no-name-in-module
from torch.utils.data import functional_datapipe, IterDataPipe, MapDataPipe
from torch.utils.data.graph import DataPipe, DataPipeGraph, traverse_dps
__all__ = [
"datapipe_gra... | --- +++ @@ -1,3 +1,4 @@+"""DataPipe utilities"""
import threading
import time
@@ -31,6 +32,42 @@
def datapipe_graph_to_adjlist(datapipe_graph):
+ """Given a DataPipe graph returned by
+ :func:`torch.utils.data.graph.traverse_dps` in DAG form, convert it into
+ adjacency list form.
+
+ Namely, :func:... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/graphbolt/datapipes/utils.py |
Add minimal docstrings for each function |
from typing import List, Union
from ..base import etype_tuple_to_str
from ..dataset import Dataset, Task
from ..itemset import HeteroItemSet, ItemSet
from ..sampling_graph import SamplingGraph
from .basic_feature_store import BasicFeatureStore
from .fused_csc_sampling_graph import from_dglgraph
from .ondisk_dataset i... | --- +++ @@ -1,3 +1,4 @@+"""Graphbolt dataset for legacy DGLDataset."""
from typing import List, Union
@@ -12,6 +13,7 @@
class LegacyDataset(Dataset):
+ """A Graphbolt dataset for legacy DGLDataset."""
def __init__(self, legacy):
# Only supports single graph cases.
@@ -132,20 +134,25 @@
... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/graphbolt/impl/legacy_dataset.py |
Please document this code using docstrings |
import torch
from torch.utils.data import functional_datapipe
from ..negative_sampler import NegativeSampler
__all__ = ["UniformNegativeSampler"]
@functional_datapipe("sample_uniform_negative")
class UniformNegativeSampler(NegativeSampler):
def __init__(
self,
datapipe,
graph,
... | --- +++ @@ -1,3 +1,4 @@+"""Uniform negative sampler for GraphBolt."""
import torch
from torch.utils.data import functional_datapipe
@@ -9,6 +10,47 @@
@functional_datapipe("sample_uniform_negative")
class UniformNegativeSampler(NegativeSampler):
+ """Sample negative destination nodes for each source node based... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/graphbolt/impl/uniform_negative_sampler.py |
Document functions with detailed explanations | from functools import reduce
from operator import mul
import torch
class GPUFeatureCache(object):
def __init__(self, cache_shape, dtype):
major, _ = torch.cuda.get_device_capability()
assert (
major >= 7
), "GPUFeatureCache is supported only on CUDA compute capability >= 70 (... | --- +++ @@ -1,3 +1,4 @@+"""HugeCTR gpu_cache wrapper for graphbolt."""
from functools import reduce
from operator import mul
@@ -5,6 +6,7 @@
class GPUFeatureCache(object):
+ """High-level wrapper for GPU embedding cache"""
def __init__(self, cache_shape, dtype):
major, _ = torch.cuda.get_devi... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/graphbolt/impl/gpu_feature_cache.py |
Document this code for team use | from .. import transforms
from ..base import NID
from ..sampling.utils import EidExcluder
from .base import Sampler, set_edge_lazy_features, set_node_lazy_features
class ShaDowKHopSampler(Sampler):
def __init__(
self,
fanouts,
replace=False,
prob=None,
prefetch_node_feats=... | --- +++ @@ -1,3 +1,4 @@+"""ShaDow-GNN subgraph samplers."""
from .. import transforms
from ..base import NID
from ..sampling.utils import EidExcluder
@@ -5,6 +6,69 @@
class ShaDowKHopSampler(Sampler):
+ """K-hop subgraph sampler from `Deep Graph Neural Networks with Shallow
+ Subgraph Samplers <https://arx... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/dataloading/shadow.py |
Help me add docstrings to my project |
from .. import backend as F
from ..base import EID, NID
from ..heterograph import DGLGraph
from ..transforms import to_block
from ..utils import get_num_threads
from .base import BlockSampler
class NeighborSampler(BlockSampler):
def __init__(
self,
fanouts,
edge_dir="in",
prob=No... | --- +++ @@ -1,3 +1,4 @@+"""Data loading components for neighbor sampling"""
from .. import backend as F
from ..base import EID, NID
@@ -8,6 +9,112 @@
class NeighborSampler(BlockSampler):
+ """Sampler that builds computational dependency of node representations via
+ neighbor sampling for multilayer GNN.
+... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/dataloading/neighbor_sampler.py |
Write docstrings that follow conventions | from __future__ import absolute_import
from collections import namedtuple
from collections.abc import MutableMapping
from . import backend as F
from .base import dgl_warning, DGLError
from .init import zero_initializer
from .storages import TensorStorage
from .utils import gather_pinned_tensor_rows, pin_memory_inplac... | --- +++ @@ -1,3 +1,4 @@+"""Columnar storage for DGLGraph."""
from __future__ import absolute_import
from collections import namedtuple
@@ -21,6 +22,7 @@ return len(self._indices[-1])
def slice(self, index):
+ """Create a new _LazyIndex object sliced by the given index tensor."""
# if ... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/frame.py |
Add well-formatted docstrings |
from torch.utils.data import functional_datapipe
from ..internal import unique_and_compact_csc_formats
from ..subgraph_sampler import SubgraphSampler
from .sampled_subgraph_impl import SampledSubgraphImpl
__all__ = ["InSubgraphSampler"]
@functional_datapipe("sample_in_subgraph")
class InSubgraphSampler(SubgraphS... | --- +++ @@ -1,3 +1,4 @@+"""In-subgraph sampler for GraphBolt."""
from torch.utils.data import functional_datapipe
@@ -12,6 +13,50 @@
@functional_datapipe("sample_in_subgraph")
class InSubgraphSampler(SubgraphSampler):
+ """Sample the subgraph induced on the inbound edges of the given nodes.
+
+ Functional... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/graphbolt/impl/in_subgraph_sampler.py |
Create structured documentation for my script |
import copy
import textwrap
from typing import Dict, List
import numpy as np
import torch
from ..base import (
get_device_to_host_uva_stream,
get_host_to_device_uva_stream,
index_select,
)
from ..feature_store import Feature
from ..internal_utils import gb_warning, is_wsl
from .basic_feature_store import... | --- +++ @@ -1,3 +1,4 @@+"""Torch-based feature store for GraphBolt."""
import copy
import textwrap
@@ -25,6 +26,7 @@ self.values = values
def wait(self):
+ """Returns the stored value when invoked."""
self.event.wait()
values = self.values
# Ensure there is no memory... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/graphbolt/impl/torch_based_feature_store.py |
Generate NumPy-style docstrings |
import os
import random
import requests
import torch as th
from scipy.io import mmread
import dgl
from dgl.base import DGLError
from dgl.data.utils import load_graphs, save_graphs, save_tensors
def rep_per_node(prefix, num_community):
ifile = os.path.join(prefix, "replicationlist.csv")
fhandle = open(ifile... | --- +++ @@ -1,3 +1,9 @@+r"""
+Copyright (c) 2021 Intel Corporation
+ \file distgnn/tools/tools.py
+ \brief Tools for use in Libra graph partitioner.
+ \author Vasimuddin Md <vasimuddin.md@intel.com>
+"""
import os
import random
@@ -12,6 +18,15 @@
def rep_per_node(prefix, num_community):
+ """
+ Used on Li... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/distgnn/tools/tools.py |
Generate helpful docstrings for debugging | import torch
from .base import find_exclude_eids
class SpotTarget(object):
def __init__(
self,
g,
exclude,
degree_threshold=10,
reverse_eids=None,
reverse_etypes=None,
):
self.g = g
self.exclude = exclude
self.degree_threshold = degree_... | --- +++ @@ -1,9 +1,61 @@+"""SpotTarget: Target edge excluder for link prediction"""
import torch
from .base import find_exclude_eids
class SpotTarget(object):
+ """Callable excluder object to exclude the edges by the degree threshold.
+
+ Besides excluding all the edges or given edges in the edge sampler... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/dataloading/spot_target.py |
Add docstrings for better understanding |
from functools import partial
import torch
import torch.distributed as thd
from torch.utils.data import functional_datapipe
from torch.utils.data.datapipes.iter import Mapper
from ..base import (
etype_str_to_tuple,
get_host_to_device_uva_stream,
index_select,
ORIGINAL_EDGE_ID,
)
from ..internal impo... | --- +++ @@ -1,3 +1,4 @@+"""Neighbor subgraph samplers for GraphBolt."""
from functools import partial
@@ -35,6 +36,9 @@
@functional_datapipe("fetch_cached_insubgraph_data")
class FetchCachedInsubgraphData(Mapper):
+ """Queries the GPUGraphCache and returns the missing seeds and a generator
+ handle that c... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/graphbolt/impl/neighbor_sampler.py |
Document helper functions with docstrings | # pylint: disable= invalid-name
from dataclasses import dataclass
from typing import Dict, Union
import torch
from ..base import CSCFormatBase, etype_str_to_tuple
from ..internal_utils import get_attributes
from ..sampled_subgraph import SampledSubgraph
__all__ = ["SampledSubgraphImpl"]
@dataclass
class SampledSub... | --- +++ @@ -1,3 +1,4 @@+"""Sampled subgraph for FusedCSCSamplingGraph."""
# pylint: disable= invalid-name
from dataclasses import dataclass
from typing import Dict, Union
@@ -13,6 +14,31 @@
@dataclass
class SampledSubgraphImpl(SampledSubgraph):
+ r"""Sampled subgraph of CSCSamplingGraph.
+
+ Examples
+ -... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/graphbolt/impl/sampled_subgraph_impl.py |
Document this module using docstrings |
# Copyright (c) 2021 Intel Corporation
# \file distgnn/partition/libra_partition.py
# \brief Libra - Vertex-cut based graph partitioner for distributed training
# \author Vasimuddin Md <vasimuddin.md@intel.com>,
# Guixiang Ma <guixiang.ma@intel.com>
# Sanchit Misra <sanchit.misra@intel.com>,
# ... | --- +++ @@ -1,3 +1,11 @@+r"""Libra partition functions.
+
+Libra partition is a vertex-cut based partitioning algorithm from
+`Distributed Power-law Graph Computing:
+Theoretical and Empirical Analysis
+<https://proceedings.neurips.cc/paper/2014/file/67d16d00201083a2b118dd5128dd6f59-Paper.pdf>`__
+from Xie et al.
+"""
... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/distgnn/partition/libra_partition.py |
Generate docstrings with parameter types | import torch
from torch.utils.data import functional_datapipe
from ..internal import compact_csc_format
from ..subgraph_sampler import SubgraphSampler
from .sampled_subgraph_impl import SampledSubgraphImpl
__all__ = ["TemporalNeighborSampler", "TemporalLayerNeighborSampler"]
class TemporalNeighborSamplerImpl(Subg... | --- +++ @@ -1,3 +1,4 @@+"""Temporal neighbor subgraph samplers for GraphBolt."""
import torch
from torch.utils.data import functional_datapipe
@@ -11,6 +12,7 @@
class TemporalNeighborSamplerImpl(SubgraphSampler):
+ """Base class for TemporalNeighborSamplers."""
def __init__(
self,
@@ -103,6 +... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/graphbolt/impl/temporal_neighbor_sampler.py |
Document all public functions with docstrings |
from enum import Enum
from typing import Any, Dict, List, Optional
import pydantic
from ..internal_utils import version
__all__ = [
"OnDiskFeatureDataFormat",
"OnDiskTVTSetData",
"OnDiskTVTSet",
"OnDiskFeatureDataDomain",
"OnDiskFeatureData",
"OnDiskMetaData",
"OnDiskGraphTopologyType",... | --- +++ @@ -1,3 +1,4 @@+"""Ondisk metadata of GraphBolt."""
from enum import Enum
from typing import Any, Dict, List, Optional
@@ -21,6 +22,7 @@
class ExtraMetaData(pydantic.BaseModel, extra="allow"):
+ """Group extra fields into metadata. Internal use only."""
extra_fields: Optional[Dict[str, Any]] =... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/graphbolt/impl/ondisk_metadata.py |
Create docstrings for all classes and functions |
import bisect
import json
import os
import shutil
import textwrap
from copy import deepcopy
from typing import Dict, List, Union
import numpy as np
import torch
import yaml
from ..base import etype_str_to_tuple, ORIGINAL_EDGE_ID
from ..dataset import Dataset, Task
from ..internal import (
calculate_dir_hash,
... | --- +++ @@ -1,3 +1,4 @@+"""GraphBolt OnDiskDataset."""
import bisect
import json
@@ -54,6 +55,25 @@ include_original_edge_id: bool,
auto_cast_to_optimal_dtype: bool,
) -> FusedCSCSamplingGraph:
+ """Convert the raw graph data into FusedCSCSamplingGraph.
+
+ Parameters
+ ----------
+ dataset_di... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/graphbolt/impl/ondisk_dataset.py |
Add docstrings that explain logic | import torch
class GPUGraphCache(object):
def __init__(
self, num_edges, threshold, indptr_dtype, dtypes, has_original_edge_ids
):
major, _ = torch.cuda.get_device_capability()
assert (
major >= 7
), "GPUGraphCache is supported only on CUDA compute capability >= 70... | --- +++ @@ -1,7 +1,25 @@+"""HugeCTR gpu_cache wrapper for graphbolt."""
import torch
class GPUGraphCache(object):
+ r"""High-level wrapper for GPU graph cache.
+
+ Places the GPU graph cache to torch.cuda.current_device().
+
+ Parameters
+ ----------
+ num_edges : int
+ Upperbound on number ... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/graphbolt/impl/gpu_graph_cache.py |
Help me comply with documentation standards | # pylint: disable=W0611
from . import function as fn, to_bidirected
try:
import torch
except ImportError:
HAS_TORCH = False
else:
HAS_TORCH = True
__all__ = [
"node_homophily",
"edge_homophily",
"linkx_homophily",
"adjusted_homophily",
]
def check_pytorch():
if HAS_TORCH is False:
... | --- +++ @@ -1,3 +1,4 @@+"""Utils for tracking graph homophily and heterophily"""
# pylint: disable=W0611
from . import function as fn, to_bidirected
@@ -17,6 +18,7 @@
def check_pytorch():
+ """Check if PyTorch is the backend."""
if HAS_TORCH is False:
raise ModuleNotFoundError(
"Th... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/homophily.py |
Document functions with detailed explanations | from . import to_bidirected
try:
import torch
except ImportError:
HAS_TORCH = False
else:
HAS_TORCH = True
__all__ = ["edge_label_informativeness", "node_label_informativeness"]
def check_pytorch():
if HAS_TORCH is False:
raise ModuleNotFoundError(
"This function requires PyTorch... | --- +++ @@ -1,3 +1,4 @@+"""Utils for computing graph label informativeness"""
from . import to_bidirected
try:
@@ -11,6 +12,7 @@
def check_pytorch():
+ """Check if PyTorch is the backend."""
if HAS_TORCH is False:
raise ModuleNotFoundError(
"This function requires PyTorch to be the... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/label_informativeness.py |
Replace inline comments with docstrings | from typing import Dict, Optional, Union
import torch
from ..base import get_device_to_host_uva_stream, get_host_to_device_uva_stream
from ..feature_store import (
bytes_to_number_of_items,
Feature,
FeatureKey,
wrap_with_cached_feature,
)
from .cpu_feature_cache import CPUFeatureCache
__all__ = ["CP... | --- +++ @@ -1,3 +1,4 @@+"""CPU cached feature for GraphBolt."""
from typing import Dict, Optional, Union
import torch
@@ -16,6 +17,20 @@
class CPUCachedFeature(Feature):
+ r"""CPU cached feature wrapping a fallback feature. Use `cpu_cached_feature`
+ to construct an instance of this class.
+
+ Paramete... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/graphbolt/impl/cpu_cached_feature.py |
Write docstrings that follow conventions | from __future__ import absolute_import
from . import backend as F
__all__ = ["base_initializer", "zero_initializer"]
def base_initializer(
shape, dtype, ctx, id_range
): # pylint: disable=unused-argument
raise NotImplementedError
def zero_initializer(
shape, dtype, ctx, id_range
): # pylint: disable... | --- +++ @@ -1,3 +1,4 @@+"""Module for common feature initializers."""
from __future__ import absolute_import
from . import backend as F
@@ -8,10 +9,59 @@ def base_initializer(
shape, dtype, ctx, id_range
): # pylint: disable=unused-argument
+ """The function signature for feature initializer.
+
+ Any c... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/init.py |
Document functions with detailed explanations |
from collections import defaultdict
from functools import partial
from typing import Dict
import torch
import torch.distributed as thd
from torch.utils.data import functional_datapipe
from .base import seed_type_str_to_ntypes
from .internal import compact_temporal_nodes, unique_and_compact
from .minibatch import Min... | --- +++ @@ -1,3 +1,4 @@+"""Subgraph samplers"""
from collections import defaultdict
from functools import partial
@@ -25,6 +26,7 @@ self.result = result
def wait(self):
+ """Returns the stored value when invoked."""
result = self.result
# Ensure there is no memory leak.
... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/graphbolt/subgraph_sampler.py |
Generate docstrings for each module | from __future__ import absolute_import
import itertools
import sys
import numpy as np
import scipy
from . import backend as F, utils
from ._ffi.function import _init_api
from ._ffi.object import ObjectBase, register_object
from ._ffi.streams import to_dgl_stream_handle
from .base import dgl_warning, DGLError
from .g... | --- +++ @@ -1,3 +1,4 @@+"""Module for heterogeneous graph index class definition."""
from __future__ import absolute_import
import itertools
@@ -16,6 +17,12 @@
@register_object("graph.HeteroGraph")
class HeteroGraphIndex(ObjectBase):
+ """HeteroGraph index object.
+
+ Note
+ ----
+ Do not create Grap... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/heterograph_index.py |
Write docstrings for algorithm functions |
from collections import deque
from dataclasses import dataclass
import torch
from torch.torch_version import TorchVersion
if (
TorchVersion(torch.__version__) >= "2.3.0"
and TorchVersion(torch.__version__) < "2.3.1"
):
# Due to https://github.com/dmlc/dgl/issues/7380, for torch 2.3.0, we need
# to ch... | --- +++ @@ -1,3 +1,4 @@+"""Base types and utilities for Graph Bolt."""
from collections import deque
from dataclasses import dataclass
@@ -51,22 +52,47 @@ # There needs to be a single instance of the uva_stream, if it is created
# multiple times, it leads to multiple CUDA memory pools and memory leaks.
def get_ho... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/graphbolt/base.py |
Write docstrings for utility functions |
from typing import Dict, NamedTuple, Union
import torch
__all__ = [
"bytes_to_number_of_items",
"Feature",
"FeatureStore",
"FeatureKey",
"wrap_with_cached_feature",
]
class FeatureKey(NamedTuple):
domain: str
type: str
name: int
class Feature:
def __init__(self):
pas... | --- +++ @@ -1,3 +1,4 @@+"""Feature store for GraphBolt."""
from typing import Dict, NamedTuple, Union
@@ -13,6 +14,9 @@
class FeatureKey(NamedTuple):
+ """A named tuple class to represent feature keys in FeatureStore classes.
+ The fields are domain, type and name all of which take string values.
+ ""... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/graphbolt/feature_store.py |
Turn comments into proper docstrings |
from typing import Dict, Union
import torch
__all__ = ["SamplingGraph"]
class SamplingGraph:
def __init__(self):
pass
def __repr__(self) -> str:
raise NotImplementedError
@property
def num_nodes(self) -> Union[int, Dict[str, int]]:
raise NotImplementedError
@propert... | --- +++ @@ -1,3 +1,4 @@+"""Sampling Graphs."""
from typing import Dict, Union
@@ -8,24 +9,78 @@
class SamplingGraph:
+ r"""Class for sampling graph."""
def __init__(self):
pass
def __repr__(self) -> str:
+ """Return a string representation of the graph.
+
+ Returns
+ ... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/graphbolt/sampling_graph.py |
Write docstrings for this repository | from typing import Dict, Union
import torch
from ..sampled_subgraph import SampledSubgraph
from ..subgraph_sampler import all_to_all, convert_to_hetero, revert_to_homo
__all__ = ["CooperativeConvFunction", "CooperativeConv"]
class CooperativeConvFunction(torch.autograd.Function):
@staticmethod
def forward... | --- +++ @@ -1,3 +1,4 @@+"""Graphbolt cooperative convolution."""
from typing import Dict, Union
import torch
@@ -9,6 +10,19 @@
class CooperativeConvFunction(torch.autograd.Function):
+ """Cooperative convolution operation from Cooperative Minibatching.
+
+ Implements the `all-to-all` message passing algor... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/graphbolt/impl/cooperative_conv.py |
Write docstrings for backend logic | import torch
__all__ = ["CPUFeatureCache"]
caching_policies = {
"s3-fifo": torch.ops.graphbolt.s3_fifo_cache_policy,
"sieve": torch.ops.graphbolt.sieve_cache_policy,
"lru": torch.ops.graphbolt.lru_cache_policy,
"clock": torch.ops.graphbolt.clock_cache_policy,
}
class CPUFeatureCache(object):
de... | --- +++ @@ -1,3 +1,4 @@+"""CPU Feature Cache implementation wrapper for graphbolt."""
import torch
__all__ = ["CPUFeatureCache"]
@@ -11,6 +12,23 @@
class CPUFeatureCache(object):
+ r"""High level wrapper for the CPU feature cache.
+
+ Parameters
+ ----------
+ cache_shape : List[int]
+ The sh... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/graphbolt/impl/cpu_feature_cache.py |
Add minimal docstrings for each function | import functools
import hashlib
import os
import platform
import warnings
from collections.abc import Mapping, Sequence
import requests
import torch
from tqdm.auto import tqdm
try:
from packaging import version # pylint: disable=unused-import
except ImportError:
# If packaging isn't installed, try and use th... | --- +++ @@ -1,3 +1,4 @@+"""Miscallenous internal utils."""
import functools
import hashlib
import os
@@ -18,6 +19,7 @@
@functools.lru_cache(maxsize=None)
def is_wsl(v: str = platform.uname().release) -> int:
+ """Detects if Python is running in WSL"""
if v.endswith("-Microsoft"):
return 1
@@ -3... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/graphbolt/internal_utils.py |
Help me document legacy Python code |
from typing import Dict, Tuple
from ..feature_store import Feature, FeatureKey, FeatureStore
__all__ = ["BasicFeatureStore"]
class BasicFeatureStore(FeatureStore):
def __init__(self, features: Dict[Tuple[str, str, str], Feature]):
super().__init__()
self._features = features
def __getitem... | --- +++ @@ -1,3 +1,4 @@+"""Basic feature store for GraphBolt."""
from typing import Dict, Tuple
@@ -7,22 +8,53 @@
class BasicFeatureStore(FeatureStore):
+ r"""A basic feature store to manage multiple features for access."""
def __init__(self, features: Dict[Tuple[str, str, str], Feature]):
+ r... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/graphbolt/impl/basic_feature_store.py |
Write clean docstrings for readability | # pylint: disable=invalid-name,unused-import
from __future__ import absolute_import as _abs
import ctypes
import functools
import operator
import numpy as _np
from . import backend as F
from ._ffi.function import _init_api
from ._ffi.ndarray import (
_set_class_ndarray,
context,
DGLContext,
DGLDataTy... | --- +++ @@ -1,3 +1,8 @@+"""DGL Runtime NDArray API.
+
+dgl.ndarray provides a minimum runtime array structure to be
+used with C++ library.
+"""
# pylint: disable=invalid-name,unused-import
from __future__ import absolute_import as _abs
@@ -24,41 +29,137 @@
class NDArray(NDArrayBase):
+ """Lightweight NDArra... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/ndarray.py |
Provide clean and structured docstrings |
import hashlib
import json
import os
import shutil
from typing import List, Union
import numpy as np
import pandas as pd
import torch
from numpy.lib.format import read_array_header_1_0, read_array_header_2_0
def numpy_save_aligned(*args, **kwargs):
# https://github.com/numpy/numpy/blob/2093a6d5b933f812d15a3de0e... | --- +++ @@ -1,3 +1,4 @@+"""Utility functions for GraphBolt."""
import hashlib
import json
@@ -12,6 +13,7 @@
def numpy_save_aligned(*args, **kwargs):
+ """A wrapper for numpy.save(), ensures the array is stored 4KiB aligned."""
# https://github.com/numpy/numpy/blob/2093a6d5b933f812d15a3de0eafeeb23c61f948... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/graphbolt/internal/utils.py |
Write docstrings for algorithm functions | # pylint: disable= no-member, arguments-differ, invalid-name
import mxnet as mx
from mxnet import nd
from mxnet.gluon import nn
from .... import function as fn
class APPNPConv(nn.Block):
def __init__(self, k, alpha, edge_drop=0.0):
super(APPNPConv, self).__init__()
self._k = k
self._alph... | --- +++ @@ -1,3 +1,4 @@+"""MXNet Module for APPNPConv"""
# pylint: disable= no-member, arguments-differ, invalid-name
import mxnet as mx
from mxnet import nd
@@ -7,6 +8,55 @@
class APPNPConv(nn.Block):
+ r"""Approximate Personalized Propagation of Neural Predictions layer from `Predict then
+ Propagate: Gr... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/nn/mxnet/conv/appnpconv.py |
Create docstrings for each class method | # pylint: disable= no-member, arguments-differ, invalid-name
import math
import mxnet as mx
from mxnet import nd
from mxnet.gluon import nn
from ....utils import check_eq_shape
class DenseSAGEConv(nn.Block):
def __init__(
self,
in_feats,
out_feats,
feat_drop=0.0,
bias=Tr... | --- +++ @@ -1,3 +1,4 @@+"""MXNet Module for DenseGraphSAGE"""
# pylint: disable= no-member, arguments-differ, invalid-name
import math
@@ -9,6 +10,33 @@
class DenseSAGEConv(nn.Block):
+ """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/mxnet/conv/densesageconv.py |
Write docstrings for this repository |
from . import backend as F, convert, random
__all__ = ["rand_graph", "rand_bipartite"]
def rand_graph(num_nodes, num_edges, idtype=F.int64, device=F.cpu()):
# TODO(minjie): support RNG as one of the arguments.
eids = random.choice(num_nodes * num_nodes, num_edges, replace=False)
eids = F.zerocopy_to_num... | --- +++ @@ -1,3 +1,4 @@+"""Module for various graph generator functions."""
from . import backend as F, convert, random
@@ -5,6 +6,45 @@
def rand_graph(num_nodes, num_edges, idtype=F.int64, device=F.cpu()):
+ """Generate a random graph of the given number of nodes/edges and return.
+
+ It uniformly choos... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/generators.py |
Generate consistent documentation across files | # 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
class EdgeConv(nn.Block):
def __init__(
self, in_feat, out_feat, batch_norm=False, allow_zero_in_d... | --- +++ @@ -1,3 +1,4 @@+"""MXNet Module for EdgeConv Layer"""
# pylint: disable= no-member, arguments-differ, invalid-name
import mxnet as mx
from mxnet.gluon import nn
@@ -8,6 +9,95 @@
class EdgeConv(nn.Block):
+ r"""EdgeConv layer from `Dynamic Graph CNN for Learning on Point Clouds
+ <https://arxiv.org/... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/nn/mxnet/conv/edgeconv.py |
Document classes and their methods | # pylint: disable= no-member, arguments-differ, invalid-name
import math
import mxnet as mx
from mxnet import gluon
from .... import function as fn
from ....base import DGLError
from ....utils import expand_as_pair
class GraphConv(gluon.Block):
def __init__(
self,
in_feats,
out_feats,
... | --- +++ @@ -1,3 +1,4 @@+"""MXNet modules for graph convolutions(GCN)"""
# pylint: disable= no-member, arguments-differ, invalid-name
import math
@@ -10,6 +11,129 @@
class GraphConv(gluon.Block):
+ r"""Graph convolutional layer from `Semi-Supervised Classification with Graph Convolutional
+ Networks <https... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/nn/mxnet/conv/graphconv.py |
Add docstrings for production code | # pylint: disable= no-member, arguments-differ, invalid-name
import math
import mxnet as mx
from mxnet import nd
from mxnet.gluon import nn
class DenseGraphConv(nn.Block):
def __init__(
self, in_feats, out_feats, norm="both", bias=True, activation=None
):
super(DenseGraphConv, self).__init__... | --- +++ @@ -1,3 +1,4 @@+"""MXNet Module for DenseGraphConv"""
# pylint: disable= no-member, arguments-differ, invalid-name
import math
@@ -7,6 +8,39 @@
class DenseGraphConv(nn.Block):
+ """Graph Convolutional layer from `Semi-Supervised Classification with Graph
+ Convolutional Networks <https://arxiv.org... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/nn/mxnet/conv/densegraphconv.py |
Generate docstrings for script automation | # pylint: disable= no-member, arguments-differ, invalid-name
import math
import mxnet as mx
from mxnet import nd
from mxnet.gluon import nn
from .... import broadcast_nodes, function as fn
from ....base import dgl_warning
class ChebConv(nn.Block):
def __init__(self, in_feats, out_feats, k, bias=True):
... | --- +++ @@ -1,3 +1,4 @@+"""MXNet Module for Chebyshev Spectral Graph Convolution layer"""
# pylint: disable= no-member, arguments-differ, invalid-name
import math
@@ -10,6 +11,56 @@
class ChebConv(nn.Block):
+ r"""Chebyshev Spectral Graph Convolution layer from `Convolutional Neural Networks on Graphs
+ w... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/nn/mxnet/conv/chebconv.py |
Document all public functions with docstrings |
def count_split(total, num_workers, worker_id, batch_size=1):
quotient, remainder = divmod(total, num_workers * batch_size)
if batch_size == 1:
assigned = quotient + (worker_id < remainder)
else:
batch_count, last_batch = divmod(remainder, batch_size)
assigned = quotient * batch_si... | --- +++ @@ -1,6 +1,11 @@+"""Utility functions for DistributedItemSampler."""
def count_split(total, num_workers, worker_id, batch_size=1):
+ """Calculate the number of assigned items after splitting them by batch
+ size evenly. It will return the number for this worker and also a sum of
+ previous workers... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/graphbolt/internal/item_sampler_utils.py |
Add inline docstrings for readability |
from collections import defaultdict
from typing import Dict, List, Optional, Tuple, Union
import torch
from ..base import CSCFormatBase, etype_str_to_tuple, expand_indptr
def unique_and_compact(
nodes: Union[
List[torch.Tensor],
Dict[str, List[torch.Tensor]],
],
rank: int = 0,
world... | --- +++ @@ -1,3 +1,4 @@+"""Utility functions for sampling."""
from collections import defaultdict
from typing import Dict, List, Optional, Tuple, Union
@@ -16,6 +17,54 @@ world_size: int = 1,
async_op: bool = False,
):
+ """
+ Compact a list of nodes tensor. The `rank` and `world_size` parameters ar... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/graphbolt/internal/sample_utils.py |
Help me document legacy Python code | from __future__ import absolute_import
import networkx as nx
import numpy as np
import scipy
from . import backend as F, utils
from ._ffi.function import _init_api
from ._ffi.object import ObjectBase, register_object
from .base import dgl_warning, DGLError
class BoolFlag(object):
BOOL_UNKNOWN = -1
BOOL_FAL... | --- +++ @@ -1,3 +1,4 @@+"""Module for graph index class definition."""
from __future__ import absolute_import
import networkx as nx
@@ -11,6 +12,7 @@
class BoolFlag(object):
+ """Bool flag with unknown value"""
BOOL_UNKNOWN = -1
BOOL_FALSE = 0
@@ -19,6 +21,20 @@
@register_object("graph.Graph")
... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/graph_index.py |
Document this script properly | # pylint: disable= no-member, arguments-differ, invalid-name
import math
import mxnet as mx
from mxnet import nd
from mxnet.gluon import nn
class DenseChebConv(nn.Block):
def __init__(self, in_feats, out_feats, k, bias=True):
super(DenseChebConv, self).__init__()
self._in_feats = in_feats
... | --- +++ @@ -1,3 +1,4 @@+"""MXNet Module for DenseChebConv"""
# pylint: disable= no-member, arguments-differ, invalid-name
import math
@@ -7,6 +8,28 @@
class DenseChebConv(nn.Block):
+ r"""Chebyshev Spectral Graph Convolution layer from `Convolutional Neural Networks on Graphs
+ with Fast Localized Spectra... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/nn/mxnet/conv/densechebconv.py |
Generate docstrings for script automation | # pylint: disable= no-member, arguments-differ, invalid-name
import math
import mxnet as mx
import numpy as np
from mxnet import gluon, nd
from mxnet.gluon import nn
from .... import function as fn
from .. import utils
class RelGraphConv(gluon.Block):
def __init__(
self,
in_feat,
out_fe... | --- +++ @@ -1,3 +1,4 @@+"""MXNet module for RelGraphConv"""
# pylint: disable= no-member, arguments-differ, invalid-name
import math
@@ -11,6 +12,93 @@
class RelGraphConv(gluon.Block):
+ r"""Relational graph convolution layer from `Modeling Relational Data with Graph
+ Convolutional Networks <https://arxi... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/nn/mxnet/conv/relgraphconv.py |
Add detailed docstrings explaining each function | # pylint: disable= no-member, arguments-differ, invalid-name
import mxnet as mx
from mxnet import nd
from mxnet.gluon import nn
from .... import function as fn
from ....base import DGLError
class SGConv(nn.Block):
def __init__(
self,
in_feats,
out_feats,
k=1,
cached=Fals... | --- +++ @@ -1,3 +1,4 @@+"""MXNet Module for Simplifying Graph Convolution layer"""
# pylint: disable= no-member, arguments-differ, invalid-name
import mxnet as mx
@@ -9,6 +10,80 @@
class SGConv(nn.Block):
+ r"""SGC layer from `Simplifying Graph Convolutional Networks
+ <https://arxiv.org/pdf/1902.07153.pd... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/nn/mxnet/conv/sgconv.py |
Fill in missing docstrings in my code | # pylint: disable= no-member, arguments-differ, invalid-name
import math
import mxnet as mx
from mxnet import nd
from mxnet.gluon import nn
from .... import function as fn
from ....base import DGLError
from ....utils import check_eq_shape, expand_as_pair
class SAGEConv(nn.Block):
def __init__(
self,
... | --- +++ @@ -1,3 +1,4 @@+"""MXNet Module for GraphSAGE layer"""
# pylint: disable= no-member, arguments-differ, invalid-name
import math
@@ -11,6 +12,85 @@
class SAGEConv(nn.Block):
+ r"""GraphSAGE layer from `Inductive Representation Learning on
+ Large Graphs <https://arxiv.org/pdf/1706.02216.pdf>`__
+
+... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/nn/mxnet/conv/sageconv.py |
Document my Python code with docstrings |
from dataclasses import dataclass
from typing import Dict, List, Tuple, Union
import torch
from .base import (
apply_to,
CSCFormatBase,
etype_str_to_tuple,
expand_indptr,
is_object_pinned,
)
from .internal_utils import (
get_attributes,
get_nonproperty_attributes,
recursive_apply,
)
f... | --- +++ @@ -1,3 +1,4 @@+"""Unified data structure for input and ouput of all the stages in loading process."""
from dataclasses import dataclass
from typing import Dict, List, Tuple, Union
@@ -23,6 +24,12 @@
@dataclass
class MiniBatch:
+ r"""A composite data class for data structure in the graphbolt.
+
+ I... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/graphbolt/minibatch.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.