instruction stringclasses 100
values | code stringlengths 78 193k | response stringlengths 259 170k | file stringlengths 59 203 |
|---|---|---|---|
Generate helpful docstrings for debugging | import torch
from torch import Tensor
from torch.nn import Parameter
from torch_geometric.nn.dense.linear import Linear
from torch_geometric.nn.inits import zeros
from torch_geometric.typing import OptTensor
class DenseGCNConv(torch.nn.Module):
def __init__(
self,
in_channels: int,
out_ch... | --- +++ @@ -8,6 +8,7 @@
class DenseGCNConv(torch.nn.Module):
+ r"""See :class:`torch_geometric.nn.conv.GCNConv`."""
def __init__(
self,
in_channels: int,
@@ -32,11 +33,30 @@ self.reset_parameters()
def reset_parameters(self):
+ r"""Resets all learnable parameters of t... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/dense/dense_gcn_conv.py |
Create simple docstrings for beginners | from typing import Callable
import torch
class QFormer(torch.nn.Module):
def __init__(
self,
input_dim: int,
hidden_dim: int,
output_dim: int,
num_heads: int,
num_layers: int,
dropout: float = 0.0,
activation: Callabl... | --- +++ @@ -4,6 +4,23 @@
class QFormer(torch.nn.Module):
+ r"""The Querying Transformer (Q-Former) from
+ `"BLIP-2: Bootstrapping Language-Image Pre-training
+ with Frozen Image Encoders and Large Language Models"
+ <https://arxiv.org/pdf/2301.12597>`_ paper.
+
+ Args:
+ input_dim (int): The n... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/attention/qformer.py |
Document functions with clear intent | from typing import Optional
import torch
from torch import Tensor
from torch.nn import Module
from torch_geometric.nn.inits import reset
class DenseGINConv(torch.nn.Module):
def __init__(
self,
nn: Module,
eps: float = 0.0,
train_eps: bool = False,
):
super().__init__... | --- +++ @@ -8,6 +8,7 @@
class DenseGINConv(torch.nn.Module):
+ r"""See :class:`torch_geometric.nn.conv.GINConv`."""
def __init__(
self,
nn: Module,
@@ -25,11 +26,30 @@ self.reset_parameters()
def reset_parameters(self):
+ r"""Resets all learnable parameters of the mod... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/dense/dense_gin_conv.py |
Document functions with clear intent | import typing
from typing import Optional, Tuple, Union
import torch
import torch.nn.functional as F
from torch import Tensor
from torch.nn import Parameter
from torch_geometric.nn.conv import MessagePassing
from torch_geometric.nn.dense.linear import Linear
from torch_geometric.nn.inits import glorot, zeros
from tor... | --- +++ @@ -33,6 +33,100 @@
class GATConv(MessagePassing):
+ r"""The graph attentional operator from the `"Graph Attention Networks"
+ <https://arxiv.org/abs/1710.10903>`_ paper.
+
+ .. math::
+ \mathbf{x}^{\prime}_i = \sum_{j \in \mathcal{N}(i) \cup \{ i \}}
+ \alpha_{i,j}\mathbf{\Theta}_t\m... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/conv/gat_conv.py |
Document all endpoints with docstrings | from typing import Optional
import torch
import torch.nn.functional as F
from torch import Tensor
from torch.nn import Module
from torch.utils.checkpoint import checkpoint
class DeepGCNLayer(torch.nn.Module):
def __init__(
self,
conv: Optional[Module] = None,
norm: Optional[Module] = None... | --- +++ @@ -8,6 +8,50 @@
class DeepGCNLayer(torch.nn.Module):
+ r"""The skip connection operations from the
+ `"DeepGCNs: Can GCNs Go as Deep as CNNs?"
+ <https://arxiv.org/abs/1904.03751>`_ and `"All You Need to Train Deeper
+ GCNs" <https://arxiv.org/abs/2006.07739>`_ papers.
+ The implemented skip... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/models/deepgcn.py |
Generate docstrings for each module | import os.path as osp
from pathlib import Path
from typing import Any, Dict, Optional, Union
import torch
from torch_geometric.io import fs
try:
from huggingface_hub import ModelHubMixin, hf_hub_download
except ImportError:
ModelHubMixin = object
hf_hub_download = None
CONFIG_NAME = 'config.json'
MODEL_... | --- +++ @@ -19,6 +19,57 @@
class PyGModelHubMixin(ModelHubMixin):
+ r"""A mixin for saving and loading models to the
+ `Huggingface Model Hub <https://huggingface.co/docs/hub/index>`_.
+
+ .. code-block:: python
+
+ from torch_geometric.datasets import Planetoid
+ from torch_geometric.nn import... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/model_hub.py |
Document helper functions with docstrings | import copy
import inspect
from typing import Any, Callable, Dict, Final, List, Optional, Tuple, Union
import torch
from torch import Tensor
from torch.nn import Linear, ModuleList
from tqdm import tqdm
from torch_geometric.data import Data
from torch_geometric.loader import CachedLoader, NeighborLoader
from torch_ge... | --- +++ @@ -30,6 +30,39 @@
class BasicGNN(torch.nn.Module):
+ r"""An abstract class for implementing basic GNN models.
+
+ Args:
+ in_channels (int or tuple): Size of each input sample, or :obj:`-1` to
+ derive the size from the first input(s) to the forward method.
+ A tuple corr... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/models/basic_gnn.py |
Add docstrings for internal functions | import copy
from typing import Callable, Tuple
import torch
from torch import Tensor
from torch.nn import Module, Parameter
from torch_geometric.nn.inits import reset, uniform
EPS = 1e-15
class DeepGraphInfomax(torch.nn.Module):
def __init__(
self,
hidden_channels: int,
encoder: Module,... | --- +++ @@ -11,6 +11,18 @@
class DeepGraphInfomax(torch.nn.Module):
+ r"""The Deep Graph Infomax model from the
+ `"Deep Graph Infomax" <https://arxiv.org/abs/1809.10341>`_
+ paper based on user-defined encoder and summary model :math:`\mathcal{E}`
+ and :math:`\mathcal{R}` respectively, and a corruptio... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/models/deep_graph_infomax.py |
Create documentation strings for testing functions | import os
import os.path as osp
from functools import partial
from math import pi as PI
from math import sqrt
from typing import Callable, Dict, Optional, Tuple, Union
import numpy as np
import torch
from torch import Tensor
from torch.nn import Embedding, Linear
from torch_geometric.data import Dataset, download_url... | --- +++ @@ -455,6 +455,45 @@
class DimeNet(torch.nn.Module):
+ r"""The directional message passing neural network (DimeNet) from the
+ `"Directional Message Passing for Molecular Graphs"
+ <https://arxiv.org/abs/2003.03123>`_ paper.
+ DimeNet transforms messages based on the angle between them in a
+ ... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/models/dimenet.py |
Write beginner-friendly docstrings | from typing import Optional
import torch
import torch.nn.functional as F
from torch import Tensor
from torch_geometric.nn import SimpleConv
from torch_geometric.nn.dense.linear import Linear
class PMLP(torch.nn.Module):
def __init__(
self,
in_channels: int,
hidden_channels: int,
... | --- +++ @@ -9,6 +9,24 @@
class PMLP(torch.nn.Module):
+ r"""The P(ropagational)MLP model from the `"Graph Neural Networks are
+ Inherently Good Generalizers: Insights by Bridging GNNs and MLPs"
+ <https://arxiv.org/abs/2212.09034>`_ paper.
+ :class:`PMLP` is identical to a standard MLP during training, ... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/models/pmlp.py |
Add professional docstrings to my codebase | from typing import Callable, Optional, Union
import torch
from torch import Tensor
from torch_geometric.nn.conv import MessagePassing
from torch_geometric.nn.dense.linear import Linear
from torch_geometric.nn.inits import reset
from torch_geometric.typing import (
Adj,
OptPairTensor,
OptTensor,
Size,
... | --- +++ @@ -17,6 +17,42 @@
class GINConv(MessagePassing):
+ r"""The graph isomorphism operator from the `"How Powerful are
+ Graph Neural Networks?" <https://arxiv.org/abs/1810.00826>`_ paper.
+
+ .. math::
+ \mathbf{x}^{\prime}_i = h_{\mathbf{\Theta}} \left( (1 + \epsilon) \cdot
+ \mathbf{x}... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/conv/gin_conv.py |
Add docstrings that explain purpose and usage | from typing import Optional, Tuple
import torch
from torch import Tensor
from torch.nn import Module
from torch_geometric.nn.inits import reset
from torch_geometric.utils import negative_sampling
EPS = 1e-15
MAX_LOGSTD = 10
class InnerProductDecoder(torch.nn.Module):
def forward(
self,
z: Tenso... | --- +++ @@ -12,21 +12,60 @@
class InnerProductDecoder(torch.nn.Module):
+ r"""The inner product decoder from the `"Variational Graph Auto-Encoders"
+ <https://arxiv.org/abs/1611.07308>`_ paper.
+
+ .. math::
+ \sigma(\mathbf{Z}\mathbf{Z}^{\top})
+
+ where :math:`\mathbf{Z} \in \mathbb{R}^{N \time... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/models/autoencoder.py |
Generate consistent docstrings | from typing import List, Optional, Tuple, Union
import torch
from torch import Tensor
from torch.nn import Embedding
from torch.utils.data import DataLoader
from torch_geometric.index import index2ptr
from torch_geometric.typing import WITH_PYG_LIB, WITH_TORCH_CLUSTER
from torch_geometric.utils import sort_edge_index... | --- +++ @@ -12,6 +12,37 @@
class Node2Vec(torch.nn.Module):
+ r"""The Node2Vec model from the
+ `"node2vec: Scalable Feature Learning for Networks"
+ <https://arxiv.org/abs/1607.00653>`_ paper where random walks of
+ length :obj:`walk_length` are sampled in a given graph, and node embeddings
+ are le... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/models/node2vec.py |
Document all endpoints with docstrings | from typing import Dict, List, Optional, Tuple
import torch
from torch import Tensor
from torch.nn import Embedding
from torch.utils.data import DataLoader
from torch_geometric.index import index2ptr
from torch_geometric.typing import EdgeType, NodeType, OptTensor
from torch_geometric.utils import sort_edge_index
EP... | --- +++ @@ -13,6 +13,41 @@
class MetaPath2Vec(torch.nn.Module):
+ r"""The MetaPath2Vec model from the `"metapath2vec: Scalable Representation
+ Learning for Heterogeneous Networks"
+ <https://ericdongyx.github.io/papers/
+ KDD17-dong-chawla-swami-metapath2vec.pdf>`_ paper where random walks based
+ o... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/models/metapath2vec.py |
Generate docstrings with parameter types | from typing import Optional, Union
import torch
import torch.nn.functional as F
from torch import Tensor
from torch.nn import Embedding, ModuleList
from torch.nn.modules.loss import _Loss
from torch_geometric.nn.conv import LGConv
from torch_geometric.typing import Adj, OptTensor
from torch_geometric.utils import is_... | --- +++ @@ -12,6 +12,55 @@
class LightGCN(torch.nn.Module):
+ r"""The LightGCN model from the `"LightGCN: Simplifying and Powering
+ Graph Convolution Network for Recommendation"
+ <https://arxiv.org/abs/2002.02126>`_ paper.
+
+ :class:`~torch_geometric.nn.models.LightGCN` learns embeddings by linearly
... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/models/lightgcn.py |
Add docstrings to existing functions | import inspect
import warnings
from typing import Any, Callable, Dict, Final, List, Optional, Union
import torch
import torch.nn.functional as F
from torch import Tensor
from torch.nn import Identity
from torch_geometric.nn.dense.linear import Linear
from torch_geometric.nn.resolver import (
activation_resolver,
... | --- +++ @@ -16,6 +16,63 @@
class MLP(torch.nn.Module):
+ r"""A Multi-Layer Perception (MLP) model.
+
+ There exists two ways to instantiate an :class:`MLP`:
+
+ 1. By specifying explicit channel sizes, *e.g.*,
+
+ .. code-block:: python
+
+ mlp = MLP([16, 32, 64, 128])
+
+ creates a th... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/models/mlp.py |
Document this module using docstrings | import torch
from torch import Tensor
from torch_geometric.nn.models import LabelPropagation
from torch_geometric.typing import Adj, OptTensor
from torch_geometric.utils import one_hot
class CorrectAndSmooth(torch.nn.Module):
def __init__(self, num_correction_layers: int, correction_alpha: float,
... | --- +++ @@ -7,6 +7,62 @@
class CorrectAndSmooth(torch.nn.Module):
+ r"""The correct and smooth (C&S) post-processing model from the
+ `"Combining Label Propagation And Simple Models Out-performs Graph Neural
+ Networks"
+ <https://arxiv.org/abs/2010.13993>`_ paper, where soft predictions
+ :math:`\ma... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/models/correct_and_smooth.py |
Help me add docstrings to my project | import torch
from torch import Tensor
class MaskLabel(torch.nn.Module):
def __init__(self, num_classes: int, out_channels: int,
method: str = "add"):
super().__init__()
self.method = method
if method not in ["add", "concat"]:
raise ValueError(
... | --- +++ @@ -3,6 +3,29 @@
class MaskLabel(torch.nn.Module):
+ r"""The label embedding and masking layer from the `"Masked Label
+ Prediction: Unified Message Passing Model for Semi-Supervised
+ Classification" <https://arxiv.org/abs/2009.03509>`_ paper.
+
+ Here, node labels :obj:`y` are merged to the in... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/models/mask_label.py |
Turn comments into proper docstrings | import os
import os.path as osp
import warnings
from math import pi as PI
from typing import Callable, Dict, Optional, Tuple
import numpy as np
import torch
import torch.nn.functional as F
from torch import Tensor
from torch.nn import Embedding, Linear, ModuleList, Sequential
from torch_geometric.data import Dataset,... | --- +++ @@ -33,6 +33,60 @@
class SchNet(torch.nn.Module):
+ r"""The continuous-filter convolutional neural network SchNet from the
+ `"SchNet: A Continuous-filter Convolutional Neural Network for Modeling
+ Quantum Interactions" <https://arxiv.org/abs/1706.08566>`_ paper that uses
+ the interactions blo... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/models/schnet.py |
Generate documentation strings for clarity | import torch
import torch.nn.functional as F
from torch import Tensor
from torch.nn import Linear
from torch_geometric.nn import GCNConv
from torch_geometric.typing import Adj, OptTensor
from torch_geometric.utils import scatter
class RECT_L(torch.nn.Module):
def __init__(self, in_channels: int, hidden_channels:... | --- +++ @@ -9,6 +9,27 @@
class RECT_L(torch.nn.Module):
+ r"""The RECT model, *i.e.* its supervised RECT-L part, from the
+ `"Network Embedding with Completely-imbalanced Labels"
+ <https://arxiv.org/abs/2007.03545>`_ paper.
+ In particular, a GCN model is trained that reconstructs semantic class
+ k... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/models/rect.py |
Add docstrings to meet PEP guidelines | from typing import Optional
import torch
import torch.nn.functional as F
from torch import Tensor
from torch_geometric.nn.attention import SGFormerAttention
from torch_geometric.nn.conv import GCNConv
from torch_geometric.utils import to_dense_batch
class GraphModule(torch.nn.Module):
def __init__(
self... | --- +++ @@ -121,6 +121,30 @@
class SGFormer(torch.nn.Module):
+ r"""The sgformer module from the
+ `"SGFormer: Simplifying and Empowering Transformers for
+ Large-Graph Representations"
+ <https://arxiv.org/abs/2306.10759>`_ paper.
+
+ Args:
+ in_channels (int): Input channels.
+ hidden... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/models/sgformer.py |
Turn comments into proper docstrings | import math
from typing import Optional
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch import Tensor
from torch.nn import Parameter
from ...nn.conv import MessagePassing
from ...nn.dense.linear import Linear
from ...nn.inits import glorot, zeros
from ...typing import Adj, OptTensor, Tup... | --- +++ @@ -16,6 +16,37 @@
class LPFormer(nn.Module):
+ r"""The LPFormer model from the
+ `"LPFormer: An Adaptive Graph Transformer for Link Prediction"
+ <https://arxiv.org/abs/2310.11009>`_ paper.
+
+ .. note::
+
+ For an example of using LPFormer, see
+ `examples/lpformer.py
+ <h... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/models/lpformer.py |
Create structured documentation for my script | import math
import torch
from torch import Tensor
from torch.nn import BatchNorm1d, Parameter
from torch_geometric.nn import inits
from torch_geometric.nn.conv import MessagePassing
from torch_geometric.nn.models import MLP
from torch_geometric.typing import Adj, OptTensor
from torch_geometric.utils import spmm
cla... | --- +++ @@ -55,6 +55,38 @@
class LINKX(torch.nn.Module):
+ r"""The LINKX model from the `"Large Scale Learning on Non-Homophilous
+ Graphs: New Benchmarks and Strong Simple Methods"
+ <https://arxiv.org/abs/2110.14446>`_ paper.
+
+ .. math::
+ \mathbf{H}_{\mathbf{A}} &= \textrm{MLP}_{\mathbf{A}}(... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/models/linkx.py |
Generate docstrings for script automation | from typing import Callable, Optional
import torch
from torch import Tensor
from torch_geometric.nn.conv import MessagePassing
from torch_geometric.nn.conv.gcn_conv import gcn_norm
from torch_geometric.typing import Adj, OptTensor, SparseTensor
from torch_geometric.utils import one_hot, spmm
class LabelPropagation(... | --- +++ @@ -10,6 +10,30 @@
class LabelPropagation(MessagePassing):
+ r"""The label propagation operator, firstly introduced in the
+ `"Learning from Labeled and Unlabeled Data with Label Propagation"
+ <http://mlg.eng.cam.ac.uk/zoubin/papers/CMU-CALD-02-107.pdf>`_ paper.
+
+ .. math::
+ \mathbf{Y... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/models/label_prop.py |
Add docstrings following best practices | from typing import Optional
import torch
from torch import Tensor
from torch_geometric.nn import Linear, MFConv, global_add_pool
from torch_geometric.typing import Adj
class NeuralFingerprint(torch.nn.Module):
def __init__(
self,
in_channels: int,
hidden_channels: int,
out_channe... | --- +++ @@ -8,6 +8,19 @@
class NeuralFingerprint(torch.nn.Module):
+ r"""The Neural Fingerprint model from the
+ `"Convolutional Networks on Graphs for Learning Molecular Fingerprints"
+ <https://arxiv.org/abs/1509.09292>`__ paper to generate fingerprints
+ of molecules.
+
+ Args:
+ in_channel... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/models/neural_fingerprint.py |
Add missing documentation to my Python functions | from typing import Optional
import torch
import torch.nn.functional as F
from torch import Tensor
from torch_geometric.nn import GATConv, GCNConv
from torch_geometric.nn.attention import PolynormerAttention
from torch_geometric.utils import to_dense_batch
class Polynormer(torch.nn.Module):
def __init__(
... | --- +++ @@ -10,6 +10,38 @@
class Polynormer(torch.nn.Module):
+ r"""The polynormer module from the
+ `"Polynormer: polynomial-expressive graph
+ transformer in linear time"
+ <https://arxiv.org/abs/2403.01232>`_ paper.
+
+ Args:
+ in_channels (int): Input channels.
+ hidden_channels (in... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/models/polynormer.py |
Create Google-style docstrings for my code | import math
from typing import Optional, Tuple
import torch
from torch import Tensor
from torch.autograd import grad
from torch.nn import Embedding, LayerNorm, Linear, Parameter
from torch_geometric.nn import MessagePassing, radius_graph
from torch_geometric.utils import scatter
class CosineCutoff(torch.nn.Module):... | --- +++ @@ -11,17 +11,55 @@
class CosineCutoff(torch.nn.Module):
+ r"""Applies a cosine cutoff to the input distances.
+
+ .. math::
+ \text{cutoffs} =
+ \begin{cases}
+ 0.5 * (\cos(\frac{\text{distances} * \pi}{\text{cutoff}}) + 1.0),
+ & \text{if } \text{distances} < \text{cutoff... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/models/visnet.py |
Create documentation strings for testing functions | import math
from typing import Callable, List, Tuple
import torch
import torch.nn.functional as F
from torch import Tensor
from torch.nn import GRU, Linear, Parameter
from torch_geometric.data.data import Data
from torch_geometric.utils import scatter
class RENet(torch.nn.Module):
def __init__(
self,
... | --- +++ @@ -11,6 +11,39 @@
class RENet(torch.nn.Module):
+ r"""The Recurrent Event Network model from the `"Recurrent Event Network
+ for Reasoning over Temporal Knowledge Graphs"
+ <https://arxiv.org/abs/1904.05530>`_ paper.
+
+ .. math::
+ f_{\mathbf{\Theta}}(\mathbf{e}_s, \mathbf{e}_r,
+ ... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/models/re_net.py |
Write docstrings for this repository | from typing import Optional
import torch
import torch.nn.functional as F
from torch import Tensor
from torch.nn.modules.instancenorm import _InstanceNorm
from torch_geometric.typing import OptTensor
from torch_geometric.utils import degree, scatter
class InstanceNorm(_InstanceNorm):
def __init__(
self,
... | --- +++ @@ -10,6 +10,36 @@
class InstanceNorm(_InstanceNorm):
+ r"""Applies instance normalization over each individual example in a batch
+ of node features as described in the `"Instance Normalization: The Missing
+ Ingredient for Fast Stylization" <https://arxiv.org/abs/1607.08022>`_
+ paper.
+
+ ... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/norm/instance_norm.py |
Add docstrings to make code maintainable | import copy
from typing import Callable, Dict, Tuple
import torch
from torch import Tensor
from torch.nn import GRUCell, Linear
from torch_geometric.nn.inits import zeros
from torch_geometric.utils import scatter
from torch_geometric.utils._scatter import scatter_argmax
TGNMessageStoreType = Dict[int, Tuple[Tensor, ... | --- +++ @@ -13,6 +13,28 @@
class TGNMemory(torch.nn.Module):
+ r"""The Temporal Graph Network (TGN) memory model from the
+ `"Temporal Graph Networks for Deep Learning on Dynamic Graphs"
+ <https://arxiv.org/abs/2006.10637>`_ paper.
+
+ .. note::
+
+ For an example of using TGN, see `examples/tgn... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/models/tgn.py |
Document this script properly | from typing import List, Optional, Union
import torch
import torch.nn.functional as F
from torch import Tensor
from torch.nn import Parameter
from torch_geometric.nn.inits import ones, zeros
from torch_geometric.typing import OptTensor
from torch_geometric.utils import degree, scatter
class LayerNorm(torch.nn.Modul... | --- +++ @@ -11,6 +11,33 @@
class LayerNorm(torch.nn.Module):
+ r"""Applies layer normalization over each individual example in a batch
+ of features as described in the `"Layer Normalization"
+ <https://arxiv.org/abs/1607.06450>`_ paper.
+
+ .. math::
+ \mathbf{x}^{\prime}_i = \frac{\mathbf{x} -
... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/norm/layer_norm.py |
Generate missing documentation strings | from typing import Optional
import torch
from torch import Tensor
from torch.nn import BatchNorm1d, Linear
class DiffGroupNorm(torch.nn.Module):
def __init__(
self,
in_channels: int,
groups: int,
lamda: float = 0.01,
eps: float = 1e-5,
momentum: float = 0.1,
... | --- +++ @@ -6,6 +6,44 @@
class DiffGroupNorm(torch.nn.Module):
+ r"""The differentiable group normalization layer from the `"Towards Deeper
+ Graph Neural Networks with Differentiable Group Normalization"
+ <https://arxiv.org/abs/2006.06972>`_ paper, which normalizes node features
+ group-wise via a lea... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/norm/diff_group_norm.py |
Add inline docstrings for readability | import copy
import warnings
from typing import Any, Callable, Dict, List, Optional, Type, Union
import torch
from torch import Tensor
from torch.nn import Module, ModuleDict, ModuleList, Sequential
try:
from torch.fx import Graph, GraphModule, Node
except (ImportError, ModuleNotFoundError, AttributeError):
Gr... | --- +++ @@ -13,6 +13,58 @@
class Transformer:
+ r"""A :class:`Transformer` executes an FX graph node-by-node, applies
+ transformations to each node, and produces a new :class:`torch.nn.Module`.
+ It exposes a :func:`transform` method that returns the transformed
+ :class:`~torch.nn.Module`.
+ :class... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/fx.py |
Create docstrings for API functions | from typing import Optional
import torch
from torch import Tensor
from torch_geometric.nn.inits import ones, zeros
from torch_geometric.typing import OptTensor
from torch_geometric.utils import scatter
class GraphNorm(torch.nn.Module):
def __init__(self, in_channels: int, eps: float = 1e-5,
dev... | --- +++ @@ -9,6 +9,26 @@
class GraphNorm(torch.nn.Module):
+ r"""Applies graph normalization over individual graphs as described in the
+ `"GraphNorm: A Principled Approach to Accelerating Graph Neural Network
+ Training" <https://arxiv.org/abs/2009.03294>`_ paper.
+
+ .. math::
+ \mathbf{x}^{\pr... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/norm/graph_norm.py |
Write reusable docstrings | from typing import Optional, Tuple
import torch
import torch.nn.functional as F
from torch import Tensor
from torch_geometric.nn import SignedConv
from torch_geometric.utils import (
coalesce,
negative_sampling,
structured_negative_sampling,
)
class SignedGCN(torch.nn.Module):
def __init__(
... | --- +++ @@ -13,6 +13,20 @@
class SignedGCN(torch.nn.Module):
+ r"""The signed graph convolutional network model from the `"Signed Graph
+ Convolutional Network" <https://arxiv.org/abs/1808.06354>`_ paper.
+ Internally, this module uses the
+ :class:`torch_geometric.nn.conv.SignedConv` operator.
+
+ A... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/models/signed_gcn.py |
Write docstrings describing each step | from typing import Optional
import torch
from torch import Tensor
from torch_geometric.typing import OptTensor
from torch_geometric.utils import scatter
class PairNorm(torch.nn.Module):
def __init__(self, scale: float = 1., scale_individually: bool = False,
eps: float = 1e-5):
super()._... | --- +++ @@ -8,6 +8,28 @@
class PairNorm(torch.nn.Module):
+ r"""Applies pair normalization over node features as described in the
+ `"PairNorm: Tackling Oversmoothing in GNNs"
+ <https://arxiv.org/abs/1909.12223>`_ paper.
+
+ .. math::
+ \mathbf{x}_i^c &= \mathbf{x}_i - \frac{1}{n}
+ \sum_... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/norm/pair_norm.py |
Add standardized docstrings across the file | from typing import NamedTuple, Optional, Tuple
import torch
import torch.nn.functional as F
from torch import Tensor
from torch_geometric.utils import (
dense_to_sparse,
one_hot,
to_dense_adj,
to_scipy_sparse_matrix,
)
class UnpoolInfo(NamedTuple):
edge_index: Tensor
cluster: Tensor
batc... | --- +++ @@ -19,6 +19,25 @@
class ClusterPooling(torch.nn.Module):
+ r"""The cluster pooling operator from the `"Edge-Based Graph Component
+ Pooling" <https://arxiv.org/abs/2409.11856>`_ paper.
+ :class:`ClusterPooling` computes a score for each edge.
+ Based on the selected edges, graph clusters are ca... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/pool/cluster_pool.py |
Add well-formatted docstrings | from typing import Callable, Optional, Tuple
from torch import Tensor
from torch_geometric.data import Batch, Data
from torch_geometric.nn.pool.consecutive import consecutive_cluster
from torch_geometric.nn.pool.pool import pool_batch, pool_edge, pool_pos
from torch_geometric.utils import add_self_loops, scatter
de... | --- +++ @@ -23,6 +23,26 @@ batch_size: Optional[int] = None,
size: Optional[int] = None,
) -> Tuple[Tensor, Optional[Tensor]]:
+ r"""Average pools node features according to the clustering defined in
+ :attr:`cluster`.
+ See :meth:`torch_geometric.nn.pool.max_pool_x` for more details.
+
+ Args:
+ ... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/pool/avg_pool.py |
Add standardized docstrings across the file | from typing import Optional
import torch
import torch.nn.functional as F
from torch import Tensor
from torch.nn import Parameter
class MessageNorm(torch.nn.Module):
def __init__(self, learn_scale: bool = False,
device: Optional[torch.device] = None):
super().__init__()
self.scale... | --- +++ @@ -7,6 +7,23 @@
class MessageNorm(torch.nn.Module):
+ r"""Applies message normalization over the aggregated messages as described
+ in the `"DeeperGCNs: All You Need to Train Deeper GCNs"
+ <https://arxiv.org/abs/2006.07739>`_ paper.
+
+ .. math::
+
+ \mathbf{x}_i^{\prime} = \mathrm{MLP}... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/norm/msg_norm.py |
Document functions with detailed explanations | from typing import Optional
import torch
from torch import Tensor
from torch_geometric.utils import scatter
class MeanSubtractionNorm(torch.nn.Module):
def forward(self, x: Tensor, batch: Optional[Tensor] = None,
dim_size: Optional[int] = None) -> Tensor:
if batch is None:
re... | --- +++ @@ -7,8 +7,26 @@
class MeanSubtractionNorm(torch.nn.Module):
+ r"""Applies layer normalization by subtracting the mean from the inputs
+ as described in the `"Revisiting 'Over-smoothing' in Deep GCNs"
+ <https://arxiv.org/abs/2003.13663>`_ paper.
+
+ .. math::
+ \mathbf{x}_i = \mathbf{x}... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/norm/mean_subtraction_norm.py |
Generate helpful docstrings for debugging | from dataclasses import dataclass
from typing import Optional
import torch
from torch import Tensor
from torch_geometric.nn.pool.select import SelectOutput
@dataclass(init=False)
class ConnectOutput:
edge_index: Tensor
edge_attr: Optional[Tensor] = None
batch: Optional[Tensor] = None
def __init__(
... | --- +++ @@ -9,6 +9,16 @@
@dataclass(init=False)
class ConnectOutput:
+ r"""The output of the :class:`Connect` method, which holds the coarsened
+ graph structure, and optional pooled edge features and batch vectors.
+
+ Args:
+ edge_index (torch.Tensor): The edge indices of the cooarsened graph.
+ ... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/pool/connect/base.py |
Create docstrings for API functions | import torch
from torch import Tensor
def approx_knn(
x: Tensor,
y: Tensor,
k: int,
batch_x: Tensor = None,
batch_y: Tensor = None,
) -> Tensor: # pragma: no cover
from pynndescent import NNDescent
if batch_x is None:
batch_x = x.new_zeros(x.size(0), dtype=torch.long)
if batc... | --- +++ @@ -9,6 +9,29 @@ batch_x: Tensor = None,
batch_y: Tensor = None,
) -> Tensor: # pragma: no cover
+ r"""Finds for each element in :obj:`y` the :obj:`k` approximated nearest
+ points in :obj:`x`.
+
+ .. note::
+
+ Approximated :math:`k`-nearest neighbor search is performed via the
+ ... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/pool/approx_knn.py |
Turn comments into proper docstrings |
import warnings
from typing import Optional
from torch import Tensor
import torch_geometric.typing
from torch_geometric.typing import OptTensor, torch_cluster
from .avg_pool import avg_pool, avg_pool_neighbor_x, avg_pool_x
from .glob import global_add_pool, global_max_pool, global_mean_pool
from .knn import (KNNInde... | --- +++ @@ -1,3 +1,4 @@+r"""Pooling package."""
import warnings
from typing import Optional
@@ -30,6 +31,34 @@ random_start: bool = True,
batch_size: Optional[int] = None,
) -> Tensor:
+ r"""A sampling algorithm from the `"PointNet++: Deep Hierarchical Feature
+ Learning on Point Sets in a Metric Sp... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/pool/__init__.py |
Auto-generate documentation strings for this file | from typing import Callable, List, NamedTuple, Optional, Tuple
import torch
import torch.nn.functional as F
from torch import Tensor
from torch_geometric.utils import coalesce, scatter, softmax
class UnpoolInfo(NamedTuple):
edge_index: Tensor
cluster: Tensor
batch: Tensor
new_edge_score: Tensor
cl... | --- +++ @@ -15,6 +15,45 @@
class EdgePooling(torch.nn.Module):
+ r"""The edge pooling operator from the `"Towards Graph Pooling by Edge
+ Contraction" <https://graphreason.github.io/papers/17.pdf>`__ and
+ `"Edge Contraction Pooling for Graph Neural Networks"
+ <https://arxiv.org/abs/1905.10990>`__ pape... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/pool/edge_pool.py |
Add docstrings to clarify complex logic | from typing import Optional
from torch import Tensor
from torch_geometric.utils import scatter
def global_add_pool(x: Tensor, batch: Optional[Tensor],
size: Optional[int] = None) -> Tensor:
dim = -1 if isinstance(x, Tensor) and x.dim() == 1 else -2
if batch is None:
return x.sum... | --- +++ @@ -7,6 +7,26 @@
def global_add_pool(x: Tensor, batch: Optional[Tensor],
size: Optional[int] = None) -> Tensor:
+ r"""Returns batch-wise graph-level-outputs by adding node features
+ across the node dimension.
+
+ For a single graph :math:`\mathcal{G}_i`, its output is computed b... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/pool/glob.py |
Help me document legacy Python code | from typing import Optional, Tuple
import torch
from torch import Tensor
from torch_geometric.index import index2ptr
from torch_geometric.nn.conv import GATConv
from torch_geometric.utils import sort_edge_index
class FusedGATConv(GATConv): # pragma: no cover
def __init__(self, *args, **kwargs):
super()... | --- +++ @@ -9,6 +9,23 @@
class FusedGATConv(GATConv): # pragma: no cover
+ r"""The fused graph attention operator from the
+ `"Understanding GNN Computational Graph: A Coordinated Computation, IO, and
+ Memory Perspective"
+ <https://proceedings.mlsys.org/paper/2022/file/
+ 9a1158154dfa42caddbd0694a... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/conv/fused_gat_conv.py |
Add docstrings to incomplete code | import warnings
from typing import NamedTuple, Optional
import torch
from torch import Tensor
from torch_geometric.utils import cumsum, degree, to_dense_batch
class KNNOutput(NamedTuple):
score: Tensor
index: Tensor
class KNNIndex:
def __init__(
self,
index_factory: Optional[str] = Non... | --- +++ @@ -13,6 +13,29 @@
class KNNIndex:
+ r"""A base class to perform fast :math:`k`-nearest neighbor search
+ (:math:`k`-NN) via the :obj:`faiss` library.
+
+ Please ensure that :obj:`faiss` is installed by running
+
+ .. code-block:: bash
+
+ pip install faiss-cpu
+ # or
+ pip ... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/pool/knn.py |
Generate docstrings for exported functions | from typing import Optional, Tuple
import torch
from torch import Tensor
from torch.nn import Conv2d, KLDivLoss, Linear, Parameter
from torch_geometric.utils import to_dense_batch
EPS = 1e-15
class MemPooling(torch.nn.Module):
def __init__(self, in_channels: int, out_channels: int, heads: int,
... | --- +++ @@ -10,6 +10,33 @@
class MemPooling(torch.nn.Module):
+ r"""Memory based pooling layer from `"Memory-Based Graph Networks"
+ <https://arxiv.org/abs/2002.09518>`_ paper, which learns a coarsened graph
+ representation based on soft cluster assignments.
+
+ .. math::
+ S_{i,j}^{(h)} &= \fra... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/pool/mem_pool.py |
Add docstrings to meet PEP guidelines | from typing import Callable, Optional, Tuple
from torch import Tensor
from torch_geometric.data import Batch, Data
from torch_geometric.nn.pool.consecutive import consecutive_cluster
from torch_geometric.nn.pool.pool import pool_batch, pool_edge, pool_pos
from torch_geometric.utils import add_self_loops, scatter
de... | --- +++ @@ -23,6 +23,28 @@ batch_size: Optional[int] = None,
size: Optional[int] = None,
) -> Tuple[Tensor, Optional[Tensor]]:
+ r"""Max-Pools node features according to the clustering defined in
+ :attr:`cluster`.
+
+ Args:
+ cluster (torch.Tensor): The cluster vector
+ :math:`\mat... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/pool/max_pool.py |
Add detailed docstrings explaining each function | from typing import Callable, Optional, Tuple, Union
import torch
from torch import Tensor
from torch_geometric.nn import GraphConv
from torch_geometric.nn.pool.connect import FilterEdges
from torch_geometric.nn.pool.select import SelectTopK
from torch_geometric.typing import OptTensor
class SAGPooling(torch.nn.Modu... | --- +++ @@ -10,6 +10,65 @@
class SAGPooling(torch.nn.Module):
+ r"""The self-attention pooling operator from the `"Self-Attention Graph
+ Pooling" <https://arxiv.org/abs/1904.08082>`_ and `"Understanding
+ Attention and Generalization in Graph Neural Networks"
+ <https://arxiv.org/abs/1905.02850>`_ pape... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/pool/sag_pool.py |
Auto-generate documentation strings for this file | from dataclasses import dataclass
from typing import Optional
import torch
from torch import Tensor
@dataclass(init=False)
class SelectOutput:
node_index: Tensor
num_nodes: int
cluster_index: Tensor
num_clusters: int
weight: Optional[Tensor] = None
def __init__(
self,
node_in... | --- +++ @@ -7,6 +7,18 @@
@dataclass(init=False)
class SelectOutput:
+ r"""The output of the :class:`Select` method, which holds an assignment
+ from selected nodes to their respective cluster(s).
+
+ Args:
+ node_index (torch.Tensor): The indices of the selected nodes.
+ num_nodes (int): The n... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/pool/select/base.py |
Write docstrings for utility functions | from typing import Callable, Optional, Tuple, Union
import torch
from torch import Tensor
from torch_geometric.nn.pool.connect import FilterEdges
from torch_geometric.nn.pool.select import SelectTopK
from torch_geometric.typing import OptTensor
class TopKPooling(torch.nn.Module):
def __init__(
self,
... | --- +++ @@ -9,6 +9,59 @@
class TopKPooling(torch.nn.Module):
+ r""":math:`\mathrm{top}_k` pooling operator from the `"Graph U-Nets"
+ <https://arxiv.org/abs/1905.05178>`_, `"Towards Sparse
+ Hierarchical Graph Classifiers" <https://arxiv.org/abs/1811.01287>`_
+ and `"Understanding Attention and Generali... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/pool/topk_pool.py |
Replace inline comments with docstrings | import copy
import inspect
import os.path as osp
import random
import sys
from typing import (
Any,
Callable,
Dict,
List,
NamedTuple,
Optional,
Tuple,
Union,
)
import torch
from torch import Tensor
from torch_geometric.inspector import Parameter, Signature, eval_type, split
from torch_... | --- +++ @@ -28,6 +28,60 @@
class Sequential(torch.nn.Module):
+ r"""An extension of the :class:`torch.nn.Sequential` container in order to
+ define a sequential GNN model.
+
+ Since GNN operators take in multiple input arguments,
+ :class:`torch_geometric.nn.Sequential` additionally expects both global
... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/sequential.py |
Help me write clear docstrings | import gc
import os
import os.path as osp
import random
import subprocess as sp
import sys
import warnings
from collections.abc import Mapping, Sequence
from typing import Any, Tuple
import torch
from torch import Tensor
from torch_geometric.data.data import BaseData
from torch_geometric.typing import SparseTensor
... | --- +++ @@ -16,10 +16,20 @@
def count_parameters(model: torch.nn.Module) -> int:
+ r"""Given a :class:`torch.nn.Module`, count its trainable parameters.
+
+ Args:
+ model (torch.nn.Model): The model.
+ """
return sum([p.numel() for p in model.parameters() if p.requires_grad])
def get_model... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/profile/utils.py |
Add docstrings to improve code quality | import copy
import math
import sys
import warnings
from typing import Callable, Dict, List, Literal, Optional, Tuple, Union
import torch
from torch import Tensor
import torch_geometric.typing
from torch_geometric.data import (
Data,
FeatureStore,
GraphStore,
HeteroData,
remote_backend_utils,
)
fro... | --- +++ @@ -38,6 +38,9 @@
class NeighborSampler(BaseSampler):
+ r"""An implementation of an in-memory (heterogeneous) neighbor sampler used
+ by :class:`~torch_geometric.loader.NeighborLoader`.
+ """
def __init__(
self,
data: Union[Data, HeteroData, Tuple[FeatureStore, GraphStore]],
... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/sampler/neighbor_sampler.py |
Add concise docstrings to each method | import copy
import math
import warnings
from abc import ABC, abstractmethod
from collections import defaultdict
from dataclasses import dataclass, field
from enum import Enum
from typing import Any, Dict, List, Literal, Optional, Union
import torch
from torch import Tensor
from torch_geometric.data import Data, Featu... | --- +++ @@ -22,6 +22,7 @@
class DataType(Enum):
+ r"""The data type a sampler is operating on."""
homogeneous = 'homogeneous'
heterogeneous = 'heterogeneous'
remote = 'remote'
@@ -43,6 +44,7 @@
class SubgraphType(Enum):
+ r"""The type of the returned subgraph."""
directional = 'directi... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/sampler/base.py |
Add detailed docstrings explaining each function | import torch
import torch.nn.functional as F
class ARLinkPredictor(torch.nn.Module):
def __init__(self, in_channels, hidden_channels, out_channels=None,
num_layers=2, dropout=0.0, attract_ratio=0.5):
super().__init__()
if out_channels is None:
out_channels = hidden_ch... | --- +++ @@ -3,6 +3,27 @@
class ARLinkPredictor(torch.nn.Module):
+ r"""Link predictor using Attract-Repel embeddings from the paper
+ `"Pseudo-Euclidean Attract-Repel Embeddings for Undirected Graphs"
+ <https://arxiv.org/abs/2106.09671>`_.
+
+ This model splits node embeddings into: attract and
+ re... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/models/attract_repel.py |
Provide docstrings following PEP 257 | import os
import pathlib
import time
from contextlib import ContextDecorator, contextmanager
from dataclasses import dataclass
from typing import Any, List, Tuple, Union
import torch
from torch.autograd.profiler import EventList
from torch.profiler import ProfilerActivity, profile
from torch_geometric.profile.utils i... | --- +++ @@ -46,6 +46,29 @@
def profileit(device: str): # pragma: no cover
+ r"""A decorator to facilitate profiling a function, *e.g.*, obtaining
+ training runtime and memory statistics of a specific model on a specific
+ dataset.
+ Returns a :obj:`GPUStats` if :obj:`device` is :obj:`xpu` or extended
... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/profile/profile.py |
Insert docstrings into my code | from typing import Optional
import torch
import torch.nn.functional as F
from torch import Tensor
from torch.nn import GRUCell, Linear, Parameter
from torch_geometric.nn import GATConv, MessagePassing, global_add_pool
from torch_geometric.nn.inits import glorot, zeros
from torch_geometric.typing import Adj, OptTensor... | --- +++ @@ -66,6 +66,23 @@
class AttentiveFP(torch.nn.Module):
+ r"""The Attentive FP model for molecular representation learning from the
+ `"Pushing the Boundaries of Molecular Representation for Drug Discovery
+ with the Graph Attention Mechanism"
+ <https://pubs.acs.org/doi/10.1021/acs.jmedchem.9b00... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/models/attentive_fp.py |
Write documentation strings for class attributes | from typing import Tuple
import torch
from torch import Tensor
from torch.nn import Embedding
from tqdm import tqdm
from torch_geometric.nn.kge.loader import KGTripletLoader
class KGEModel(torch.nn.Module):
def __init__(
self,
num_nodes: int,
num_relations: int,
hidden_channels: ... | --- +++ @@ -9,6 +9,15 @@
class KGEModel(torch.nn.Module):
+ r"""An abstract base class for implementing custom KGE models.
+
+ Args:
+ num_nodes (int): The number of nodes/entities in the graph.
+ num_relations (int): The number of relations in the graph.
+ hidden_channels (int): The hidd... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/kge/base.py |
Add docstrings for better understanding | import functools
from collections import OrderedDict, defaultdict, namedtuple
from typing import Any, List, NamedTuple, Optional, Tuple
import torch
import torch.profiler as torch_profiler
import torch_geometric.typing
# predefined namedtuple for variable setting (global template)
Trace = namedtuple('Trace', ['path'... | --- +++ @@ -25,6 +25,21 @@
class Profiler:
+ r"""Layer by layer profiling of PyTorch models, using the PyTorch profiler
+ for memory profiling. Parts of the code are adapted from :obj:`torchprof`
+ for layer-wise grouping.
+
+ Args:
+ model (torch.nn.Module): The underlying model to be profiled.
... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/profile/profiler.py |
Auto-generate documentation strings for this file | import torch
from torch import Tensor
from torch.nn import BatchNorm1d, Embedding, Linear, ModuleList, Sequential
from torch_geometric.nn import radius_graph
from torch_geometric.nn.inits import reset
from torch_geometric.nn.models.dimenet import triplets
from torch_geometric.nn.models.schnet import ShiftedSoftplus
fr... | --- +++ @@ -18,6 +18,7 @@ self.register_buffer('offset', offset)
def reset_parameters(self):
+ r"""Resets all learnable parameters of the module."""
def forward(self, dist: Tensor) -> Tensor:
dist = dist.view(-1, 1) - self.offset.view(1, -1)
@@ -115,6 +116,25 @@
class GNNFF(tor... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/models/gnnff.py |
Generate docstrings with parameter types | from typing import Any, Optional
import numpy as np
import torch
from torch import Tensor
import torch_geometric.typing
from torch_geometric.data import Data
from torch_geometric.data.datapipes import functional_transform
from torch_geometric.transforms import BaseTransform
from torch_geometric.utils import (
get... | --- +++ @@ -40,6 +40,25 @@
@functional_transform('add_laplacian_eigenvector_pe')
class AddLaplacianEigenvectorPE(BaseTransform):
+ r"""Adds the Laplacian eigenvector positional encoding from the
+ `"Benchmarking Graph Neural Networks" <https://arxiv.org/abs/2003.00982>`_
+ paper to the given graph
+ (fun... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/transforms/add_positional_encoding.py |
Add return value explanations in docstrings | import warnings
from typing import List, Optional, Tuple, Union, cast
import torch
from torch import Tensor
from torch_geometric import EdgeIndex
from torch_geometric.data import HeteroData
from torch_geometric.data.datapipes import functional_transform
from torch_geometric.transforms import BaseTransform
from torch_... | --- +++ @@ -14,6 +14,89 @@
@functional_transform('add_metapaths')
class AddMetaPaths(BaseTransform):
+ r"""Adds additional edge types to a
+ :class:`~torch_geometric.data.HeteroData` object between the source node
+ type and the destination node type of a given :obj:`metapath`, as described
+ in the `"He... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/transforms/add_metapaths.py |
Add docstrings to improve readability | import copy
from typing import Any, List, Optional, Union
import numpy as np
import torch
from torch import Tensor
import torch_geometric.typing
from torch_geometric.typing import Adj
class InvertibleFunction(torch.autograd.Function):
@staticmethod
def forward(ctx, fn: torch.nn.Module, fn_inverse: torch.nn.... | --- +++ @@ -10,6 +10,24 @@
class InvertibleFunction(torch.autograd.Function):
+ r"""An invertible autograd function. This allows for automatic
+ backpropagation in a reversible fashion so that the memory of intermediate
+ results can be freed during the forward pass and be constructed on-the-fly
+ durin... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/models/rev_gnn.py |
Add minimal docstrings for each function | from typing import Callable, List, Union
import torch
from torch import Tensor
from torch_geometric.nn import GCNConv, TopKPooling
from torch_geometric.nn.resolver import activation_resolver
from torch_geometric.typing import OptTensor, PairTensor
from torch_geometric.utils import (
add_self_loops,
remove_sel... | --- +++ @@ -15,6 +15,23 @@
class GraphUNet(torch.nn.Module):
+ r"""The Graph U-Net model from the `"Graph U-Nets"
+ <https://arxiv.org/abs/1905.05178>`_ paper which implements a U-Net like
+ architecture with graph pooling and unpooling operations.
+
+ Args:
+ in_channels (int): Size of each inpu... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/models/graph_unet.py |
Generate documentation strings for clarity | import numpy as np
import torch
import torch.nn.functional as F
from torch import Tensor
from torch.nn import LayerNorm, Linear
from torch_geometric.nn import TemporalEncoding
from torch_geometric.utils import scatter, to_dense_batch
class NodeEncoder(torch.nn.Module):
def __init__(self, time_window: int):
... | --- +++ @@ -9,6 +9,20 @@
class NodeEncoder(torch.nn.Module):
+ r"""The node encoder module from the `"Do We Really Need Complicated
+ Model Architectures for Temporal Networks?"
+ <https://openreview.net/forum?id=ayPPc0SyLv1>`_ paper.
+ :class:`NodeEncoder` captures the 1-hop temporal neighborhood infor... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/models/graph_mixer.py |
Create documentation strings for testing functions | from typing import Optional, Tuple
import torch
from torch import Tensor
class MetaLayer(torch.nn.Module):
def __init__(
self,
edge_model: Optional[torch.nn.Module] = None,
node_model: Optional[torch.nn.Module] = None,
global_model: Optional[torch.nn.Module] = None,
):
... | --- +++ @@ -5,6 +5,97 @@
class MetaLayer(torch.nn.Module):
+ r"""A meta layer for building any kind of graph network, inspired by the
+ `"Relational Inductive Biases, Deep Learning, and Graph Networks"
+ <https://arxiv.org/abs/1806.01261>`_ paper.
+
+ A graph network takes a graph as input and returns a... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/models/meta.py |
Add docstrings to improve code quality | from typing import Dict, List, Optional
import torch
from torch import Tensor
from torch.nn import LSTM, Linear
class JumpingKnowledge(torch.nn.Module):
def __init__(
self,
mode: str,
channels: Optional[int] = None,
num_layers: Optional[int] = None,
) -> None:
super().... | --- +++ @@ -6,6 +6,41 @@
class JumpingKnowledge(torch.nn.Module):
+ r"""The Jumping Knowledge layer aggregation module from the
+ `"Representation Learning on Graphs with Jumping Knowledge Networks"
+ <https://arxiv.org/abs/1806.03536>`_ paper.
+
+ Jumping knowledge is performed based on either **concat... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/models/jumping_knowledge.py |
Document this code for team use | from typing import Any, Dict, Optional, Tuple
import numpy as np
import torch
from torch import Tensor
from torch_geometric.data import Data
from torch_geometric.data.datapipes import functional_transform
from torch_geometric.transforms import BaseTransform
from torch_geometric.utils import (
add_self_loops,
... | --- +++ @@ -20,6 +20,59 @@
@functional_transform('gdc')
class GDC(BaseTransform):
+ r"""Processes the graph via Graph Diffusion Convolution (GDC) from the
+ `"Diffusion Improves Graph Learning" <https://arxiv.org/abs/1911.05485>`_
+ paper (functional name: :obj:`gdc`).
+
+ .. note::
+
+ The paper ... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/transforms/gdc.py |
Create docstrings for API functions | import logging
import os
import os.path as osp
import time
from collections import OrderedDict
from typing import List, Optional, Tuple
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import Module
from tqdm import trange
import torch_geometric.transforms as T
from ... | --- +++ @@ -261,6 +261,35 @@
class GNNInductiveHybridMultiHead(torch.nn.Module):
+ r"""GNN prediction head for inductive node and graph prediction tasks using
+ individual MLP for each task.
+
+ Args:
+ dim_in (int): Input dimension.
+ dim_out (int): Output dimension. Not used, as the dimensi... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/models/gpse.py |
Add docstrings to my Python code | from typing import List, Optional, Sequence, Union
from torch_geometric.data import Data, HeteroData
from torch_geometric.data.datapipes import functional_transform
from torch_geometric.data.storage import BaseStorage
from torch_geometric.transforms import BaseTransform
from torch_geometric.utils import index_to_mask,... | --- +++ @@ -31,6 +31,21 @@
@functional_transform('index_to_mask')
class IndexToMask(BaseTransform):
+ r"""Converts indices to a mask representation
+ (functional name: :obj:`index_to_mask`).
+
+ Args:
+ attrs (str, [str], optional): If given, will only perform index to mask
+ conversion fo... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/transforms/mask.py |
Write docstrings including parameters and return values | from typing import Callable, Optional, Tuple, Union
import torch
import torch.nn.functional as F
from torch import Tensor
from torch.nn import Linear
from torch_geometric.nn import LEConv
from torch_geometric.nn.pool.select import SelectTopK
from torch_geometric.utils import (
add_remaining_self_loops,
remove... | --- +++ @@ -19,6 +19,33 @@
class ASAPooling(torch.nn.Module):
+ r"""The Adaptive Structure Aware Pooling operator from the
+ `"ASAP: Adaptive Structure Aware Pooling for Learning Hierarchical
+ Graph Representations" <https://arxiv.org/abs/1911.07979>`_ paper.
+
+ Args:
+ in_channels (int): Size ... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/pool/asap.py |
Please document this code using docstrings | from abc import ABC, abstractmethod
from dataclasses import dataclass
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
import torch
import torch.nn.functional as F
from torch_geometric.data import Data, HeteroData
from torch_geometric.data.datapipes import functional_transform
from torch_geometric... | --- +++ @@ -13,6 +13,7 @@
class Padding(ABC):
+ r"""An abstract class for specifying padding values."""
@abstractmethod
def get_value(
self,
@@ -24,6 +25,12 @@
@dataclass(init=False)
class UniformPadding(Padding):
+ r"""Uniform padding independent of attribute name or node/edge type.
+
+... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/transforms/pad.py |
Add docstrings to my Python code | from typing import Callable, Optional, Tuple, Union
import torch
from torch import Tensor
from torch.nn import Parameter
from torch_geometric.nn.pool.connect import FilterEdges
from torch_geometric.nn.pool.select import SelectTopK
from torch_geometric.typing import OptTensor, SparseTensor
from torch_geometric.utils i... | --- +++ @@ -11,6 +11,34 @@
class PANPooling(torch.nn.Module):
+ r"""The path integral based pooling operator from the
+ `"Path Integral Based Convolution and Pooling for Graph Neural Networks"
+ <https://arxiv.org/abs/2006.16811>`_ paper.
+
+ PAN pooling performs top-:math:`k` pooling where global node ... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/pool/pan_pool.py |
Create docstrings for all classes and functions | from typing import Any, Dict, List, Optional, Tuple, TypeVar, Union
import torch
from torch import Tensor
from torch_geometric.data import Data, HeteroData
from torch_geometric.data.storage import EdgeStorage
from torch_geometric.index import index2ptr
from torch_geometric.typing import EdgeType, NodeType, OptTensor
... | --- +++ @@ -11,6 +11,9 @@
def reverse_edge_type(edge_type: EdgeType) -> EdgeType:
+ """Reverses edge types for heterogeneous graphs. Useful in cases of
+ backward sampling.
+ """
return (edge_type[2], edge_type[1],
edge_type[0]) if edge_type is not None else None
@@ -187,11 +190,33 @@
... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/sampler/utils.py |
Add detailed documentation for each class | from typing import Optional
import torch
from torch import Tensor
from torch_geometric.typing import OptTensor
from torch_geometric.utils import degree
class GraphSizeNorm(torch.nn.Module):
def __init__(self):
super().__init__()
def forward(self, x: Tensor, batch: OptTensor = None,
... | --- +++ @@ -8,11 +8,29 @@
class GraphSizeNorm(torch.nn.Module):
+ r"""Applies Graph Size Normalization over each individual graph in a batch
+ of node features as described in the
+ `"Benchmarking Graph Neural Networks" <https://arxiv.org/abs/2003.00982>`_
+ paper.
+
+ .. math::
+ \mathbf{x}^{... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/norm/graph_size_norm.py |
Add docstrings to my Python code | import copy
from abc import ABC, abstractmethod
from typing import Any, Tuple
import torch
from torch import Tensor
from torch_geometric.data import Data
from torch_geometric.transforms import BaseTransform
from torch_geometric.utils import to_torch_csc_tensor
class RootedSubgraphData(Data):
def __inc__(self, k... | --- +++ @@ -11,6 +11,23 @@
class RootedSubgraphData(Data):
+ r"""A data object describing a homogeneous graph together with each node's
+ rooted subgraph.
+
+ It contains several additional properties that hold the information to map
+ to batch of every node's rooted subgraph:
+
+ * :obj:`sub_edge_in... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/transforms/rooted_subgraph.py |
Write docstrings for utility functions | from typing import List
import torch
from torch_geometric.data import Data
from torch_geometric.data.datapipes import functional_transform
from torch_geometric.transforms import BaseTransform
class _QhullTransform(BaseTransform):
def forward(self, data: Data) -> Data:
assert data.pos is not None
... | --- +++ @@ -8,6 +8,7 @@
class _QhullTransform(BaseTransform):
+ r"""Q-hull implementation of delaunay triangulation."""
def forward(self, data: Data) -> Data:
assert data.pos is not None
import scipy.spatial
@@ -21,6 +22,7 @@
class _ShullTransform(BaseTransform):
+ r"""Sweep-hull im... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/transforms/delaunay.py |
Write reusable docstrings | from typing import Callable, List, Union
from torch_geometric.data import Data, HeteroData
from torch_geometric.transforms import BaseTransform
class Compose(BaseTransform):
def __init__(self, transforms: List[Callable]):
self.transforms = transforms
def forward(
self,
data: Union[Da... | --- +++ @@ -5,6 +5,11 @@
class Compose(BaseTransform):
+ r"""Composes several transforms together.
+
+ Args:
+ transforms (List[Callable]): List of transforms to compose.
+ """
def __init__(self, transforms: List[Callable]):
self.transforms = transforms
@@ -25,6 +30,11 @@
class C... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/transforms/compose.py |
Add docstrings to improve code quality | import importlib.util
import inspect
import os
import typing
import warnings
from typing import Any, Dict, List, Optional, Set, Tuple, TypeAlias, Union
import numpy as np
import torch
from torch import Tensor
WITH_PT20 = int(torch.__version__.split('.')[0]) >= 2
WITH_PT21 = WITH_PT20 and int(torch.__version__.split('... | --- +++ @@ -348,6 +348,9 @@
class EdgeTypeStr(str):
+ r"""A helper class to construct serializable edge types by merging an edge
+ type tuple into a single string.
+ """
edge_type: tuple[str, str, str]
def __new__(cls, *args: Any) -> 'EdgeTypeStr':
@@ -380,6 +383,7 @@ return out
... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/typing.py |
Add docstrings including usage examples | from typing import Optional
import torch
from torch import Tensor
from torch.nn import Parameter
from torch_geometric.nn.aggr.fused import FusedAggregation
class BatchNorm(torch.nn.Module):
def __init__(
self,
in_channels: int,
eps: float = 1e-5,
momentum: Optional[float] = 0.1,
... | --- +++ @@ -8,6 +8,40 @@
class BatchNorm(torch.nn.Module):
+ r"""Applies batch normalization over a batch of features as described in
+ the `"Batch Normalization: Accelerating Deep Network Training by
+ Reducing Internal Covariate Shift" <https://arxiv.org/abs/1502.03167>`_
+ paper.
+
+ .. math::
+ ... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/norm/batch_norm.py |
Add docstrings to existing functions | from typing import List, Optional, Tuple, Union
import torch
from torch import Tensor
import torch_geometric.typing
from torch_geometric import is_compiling, is_in_onnx_export, warnings
from torch_geometric.typing import torch_scatter
from torch_geometric.utils.functions import cumsum
warnings.filterwarnings('ignore... | --- +++ @@ -18,6 +18,22 @@ dim_size: Optional[int] = None,
reduce: str = 'sum',
) -> Tensor:
+ r"""Reduces all values from the :obj:`src` tensor at the indices specified
+ in the :obj:`index` tensor along a given dimension ``dim``. See the
+ `documentation <https://pytorch-scatter.readthedocs.io/en/l... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/utils/_scatter.py |
Write docstrings describing each step | import torch
from torch import Tensor
import torch_geometric.typing
from torch_geometric import is_compiling
from torch_geometric.index import ptr2index
from torch_geometric.typing import torch_scatter
from torch_geometric.utils import scatter
def segment(src: Tensor, ptr: Tensor, reduce: str = 'sum') -> Tensor:
... | --- +++ @@ -9,6 +9,21 @@
def segment(src: Tensor, ptr: Tensor, reduce: str = 'sum') -> Tensor:
+ r"""Reduces all values in the first dimension of the :obj:`src` tensor
+ within the ranges specified in the :obj:`ptr`. See the `documentation
+ <https://pytorch-scatter.readthedocs.io/en/latest/functions/
+ ... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/utils/_segment.py |
Document helper functions with docstrings | import random
from typing import Optional, Tuple, Union
import numpy as np
import torch
from torch import Tensor
from torch_geometric.utils import coalesce, cumsum, degree, remove_self_loops
from torch_geometric.utils.num_nodes import maybe_num_nodes
def negative_sampling(
edge_index: Tensor,
num_nodes: Opt... | --- +++ @@ -16,6 +16,50 @@ method: str = "sparse",
force_undirected: bool = False,
) -> Tensor:
+ r"""Samples random negative edges of a graph given by :attr:`edge_index`.
+
+ Args:
+ edge_index (LongTensor): The edge indices.
+ num_nodes (int or Tuple[int, int], optional): The number of n... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/utils/_negative_sampling.py |
Add docstrings to improve code quality | from typing import Any, List, Union
import torch
from torch import Tensor
from torch_geometric.typing import TensorFrame
from torch_geometric.utils.mask import mask_select
from torch_geometric.utils.sparse import is_torch_sparse_tensor
def select(
src: Union[Tensor, List[Any], TensorFrame],
index_or_mask: T... | --- +++ @@ -13,6 +13,14 @@ index_or_mask: Tensor,
dim: int,
) -> Union[Tensor, List[Any]]:
+ r"""Selects the input tensor or input list according to a given index or
+ mask vector.
+
+ Args:
+ src (torch.Tensor or list): The input tensor or list.
+ index_or_mask (torch.Tensor): The inde... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/utils/_select.py |
Create simple docstrings for beginners | from typing import List, Literal, Optional, Tuple, Union, overload
import torch
from torch import Tensor
from torch_geometric.typing import OptTensor, PairTensor
from torch_geometric.utils import scatter
from torch_geometric.utils.map import map_index
from torch_geometric.utils.mask import index_to_mask
from torch_ge... | --- +++ @@ -11,6 +11,32 @@
def get_num_hops(model: torch.nn.Module) -> int:
+ r"""Returns the number of hops the model is aggregating information
+ from.
+
+ .. note::
+
+ This function counts the number of message passing layers as an
+ approximation of the total number of hops covered by th... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/utils/_subgraph.py |
Add docstrings to my Python code | from collections import defaultdict
from typing import Any, Dict, Iterable, List, Literal, Optional, Tuple, Union
import torch
from torch import Tensor
from torch.utils.dlpack import from_dlpack, to_dlpack
import torch_geometric
from torch_geometric.utils.num_nodes import maybe_num_nodes
def to_scipy_sparse_matrix(... | --- +++ @@ -14,6 +14,25 @@ edge_attr: Optional[Tensor] = None,
num_nodes: Optional[int] = None,
) -> Any:
+ r"""Converts a graph given by edge indices and edge attributes to a scipy
+ sparse matrix.
+
+ Args:
+ edge_index (LongTensor): The edge indices.
+ edge_attr (Tensor, optional): E... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/utils/convert.py |
Document this module using docstrings | from typing import List, Optional
import torch
from torch import Tensor
from torch_geometric.utils import cumsum, degree
def unbatch(
src: Tensor,
batch: Tensor,
dim: int = 0,
batch_size: Optional[int] = None,
) -> List[Tensor]:
sizes = degree(batch, batch_size, dtype=torch.long).tolist()
re... | --- +++ @@ -12,6 +12,26 @@ dim: int = 0,
batch_size: Optional[int] = None,
) -> List[Tensor]:
+ r"""Splits :obj:`src` according to a :obj:`batch` vector along dimension
+ :obj:`dim`.
+
+ Args:
+ src (Tensor): The source tensor.
+ batch (LongTensor): The batch vector
+ :math:`... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/utils/_unbatch.py |
Write reusable docstrings | from typing import Dict, List, Optional, Tuple, Union, overload
import torch
from torch import Tensor
from torch_geometric import EdgeIndex
from torch_geometric.typing import (
Adj,
EdgeType,
MaybeHeteroAdjTensor,
MaybeHeteroEdgeTensor,
MaybeHeteroNodeTensor,
NodeType,
SparseStorage,
S... | --- +++ @@ -50,6 +50,28 @@ edge_attr: Optional[MaybeHeteroEdgeTensor] = None,
) -> Tuple[MaybeHeteroNodeTensor, MaybeHeteroAdjTensor,
Optional[MaybeHeteroEdgeTensor]]:
+ r"""Trims the :obj:`edge_index` representation, node features :obj:`x` and
+ edge features :obj:`edge_attr` to a minimal-sized ... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/utils/_trim_to_layer.py |
Auto-generate documentation strings for this file | from typing import Optional, Tuple
import torch
from torch import Tensor
import torch_geometric.typing
from torch_geometric import is_compiling
from torch_geometric.deprecation import deprecated
from torch_geometric.typing import OptTensor
from torch_geometric.utils import cumsum, degree, sort_edge_index, subgraph
fr... | --- +++ @@ -25,6 +25,44 @@ num_nodes: Optional[int] = None,
training: bool = True,
) -> Tuple[Tensor, OptTensor]:
+ r"""Randomly drops edges from the adjacency matrix
+ :obj:`(edge_index, edge_attr)` with probability :obj:`p` using samples from
+ a Bernoulli distribution.
+
+ .. warning::
+
+ ... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/utils/dropout.py |
Include argument descriptions in docstrings | import warnings
from typing import Any, Dict, List, Optional, Type
import torch
from torch import Tensor
from torch_geometric.typing import NodeType
def get_embeddings(
model: torch.nn.Module,
*args: Any,
**kwargs: Any,
) -> List[Tensor]:
from torch_geometric.nn import MessagePassing
embeddings... | --- +++ @@ -12,6 +12,20 @@ *args: Any,
**kwargs: Any,
) -> List[Tensor]:
+ """Returns the output embeddings of all
+ :class:`~torch_geometric.nn.conv.MessagePassing` layers in
+ :obj:`model`.
+
+ Internally, this method registers forward hooks on all
+ :class:`~torch_geometric.nn.conv.MessagePa... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/utils/embedding.py |
Write clean docstrings for readability | from typing import Optional, Tuple
import torch
from torch import Tensor
from torch_geometric.utils import remove_self_loops, segregate_self_loops
from torch_geometric.utils.num_nodes import maybe_num_nodes
def contains_isolated_nodes(
edge_index: Tensor,
num_nodes: Optional[int] = None,
) -> bool:
num_... | --- +++ @@ -11,6 +11,25 @@ edge_index: Tensor,
num_nodes: Optional[int] = None,
) -> bool:
+ r"""Returns :obj:`True` if the graph given by :attr:`edge_index` contains
+ isolated nodes.
+
+ Args:
+ edge_index (LongTensor): The edge indices.
+ num_nodes (int, optional): The number of node... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/utils/isolated.py |
Document all public functions with docstrings | from typing import List, Tuple, Union, cast
import torch
from torch import Tensor
from torch.autograd.functional import jacobian
from tqdm.auto import tqdm
from torch_geometric.data import Data
from torch_geometric.utils import k_hop_subgraph
def k_hop_subsets_rough(
node_idx: int,
num_hops: int,
edge_i... | --- +++ @@ -15,6 +15,31 @@ edge_index: Tensor,
num_nodes: int,
) -> List[Tensor]:
+ r"""Return *rough* (possibly overlapping) *k*-hop node subsets.
+
+ This is a thin wrapper around
+ :pyfunc:`torch_geometric.utils.k_hop_subgraph` that *additionally* returns
+ **all** intermediate hop subsets rath... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/utils/influence.py |
Document all public functions with docstrings | import warnings
from typing import List, Union
import numpy as np
import torch
from torch_geometric.utils import remove_self_loops, to_undirected
def erdos_renyi_graph(
num_nodes: int,
edge_prob: float,
directed: bool = False,
) -> torch.Tensor:
if directed:
idx = torch.arange((num_nodes - 1... | --- +++ @@ -12,6 +12,23 @@ edge_prob: float,
directed: bool = False,
) -> torch.Tensor:
+ r"""Returns the :obj:`edge_index` of a random Erdos-Renyi graph.
+
+ Args:
+ num_nodes (int): The number of nodes.
+ edge_prob (float): Probability of an edge.
+ directed (bool, optional): If s... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/utils/random.py |
Generate helpful docstrings for debugging | from typing import Optional, Tuple, Union
import torch
from torch import Tensor
from torch_geometric.utils import scatter
def to_nested_tensor(
x: Tensor,
batch: Optional[Tensor] = None,
ptr: Optional[Tensor] = None,
batch_size: Optional[int] = None,
) -> Tensor:
if ptr is not None:
offs... | --- +++ @@ -12,6 +12,25 @@ ptr: Optional[Tensor] = None,
batch_size: Optional[int] = None,
) -> Tensor:
+ r"""Given a contiguous batch of tensors
+ :math:`\mathbf{X} \in \mathbb{R}^{(N_1 + \ldots + N_B) \times *}`
+ (with :math:`N_i` indicating the number of elements in example :math:`i`),
+ creat... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/utils/nested.py |
Generate consistent documentation across files | import typing
from typing import List, Optional, Tuple, Union
import torch
from torch import Tensor
from torch_geometric.typing import OptTensor
from torch_geometric.utils import coalesce, sort_edge_index
from torch_geometric.utils.num_nodes import maybe_num_nodes
if typing.TYPE_CHECKING:
from typing import over... | --- +++ @@ -39,6 +39,32 @@ edge_attr: Union[Optional[Tensor], List[Tensor]] = None,
num_nodes: Optional[int] = None,
) -> bool:
+ r"""Returns :obj:`True` if the graph given by :attr:`edge_index` is
+ undirected.
+
+ Args:
+ edge_index (LongTensor): The edge indices.
+ edge_attr (Tensor ... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/utils/undirected.py |
Annotate my code with docstrings | from math import sqrt
from typing import Any, Dict, List, Optional, Set, Tuple
import torch
from torch import Tensor
BACKENDS = {'graphviz', 'networkx'}
def has_graphviz() -> bool:
try:
import graphviz
except ImportError:
return False
try:
graphviz.Digraph().pipe()
except gr... | --- +++ @@ -28,6 +28,23 @@ backend: Optional[str] = None,
node_labels: Optional[List[str]] = None,
) -> Any:
+ r"""Visualizes the graph given via :obj:`edge_index` and (optional)
+ :obj:`edge_weight`.
+
+ Args:
+ edge_index (torch.Tensor): The edge indices.
+ edge_weight (torch.Tensor, ... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/visualization/graph.py |
Create docstrings for API functions | # -*- coding: utf-8 -*-
# !/usr/bin/env python
__author__ = 'JHao'
from redis.exceptions import TimeoutError, ConnectionError, ResponseError
from redis.connection import BlockingConnectionPool
from handler.logHandler import LogHandler
from random import choice
from redis import Redis
import json
class SsdbClient(obje... | --- +++ @@ -1,5 +1,20 @@ # -*- coding: utf-8 -*-
# !/usr/bin/env python
+"""
+-------------------------------------------------
+ File Name: ssdbClient.py
+ Description : 封装SSDB操作
+ Author : JHao
+ date: 2016/12/2
+-------------------------------------------------
+ Change Activity:
+ ... | https://raw.githubusercontent.com/jhao104/proxy_pool/HEAD/db/ssdbClient.py |
Write proper docstrings for these functions | # -*- coding: utf-8 -*-
__author__ = 'JHao'
import re
import json
from time import sleep
from util.webRequest import WebRequest
class ProxyFetcher(object):
@staticmethod
def freeProxy01():
start_url = "https://www.zdaye.com/dayProxy.html"
html_tree = WebRequest().get(start_url, verify=False... | --- +++ @@ -1,4 +1,15 @@ # -*- coding: utf-8 -*-
+"""
+-------------------------------------------------
+ File Name: proxyFetcher
+ Description :
+ Author : JHao
+ date: 2016/11/25
+-------------------------------------------------
+ Change Activity:
+ 2016/11/25: proxyF... | https://raw.githubusercontent.com/jhao104/proxy_pool/HEAD/fetcher/proxyFetcher.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.