instruction stringclasses 100
values | code stringlengths 78 193k | response stringlengths 259 170k | file stringlengths 59 203 |
|---|---|---|---|
Generate docstrings for this script | import functools
import inspect
from typing import Any, Callable, Dict, List, Optional, Union
import torch
# TODO (matthias) This file currently requires manual imports to let
# TorchScript work on decorated functions. Not totally sure why :(
from torch_geometric.utils import * # noqa
__experimental_flag__: Dict[st... | --- +++ @@ -24,6 +24,10 @@
def is_experimental_mode_enabled(options: Options = None) -> bool:
+ r"""Returns :obj:`True` if the experimental mode is enabled. See
+ :class:`torch_geometric.experimental_mode` for a list of (optional)
+ options.
+ """
if torch.jit.is_scripting() or torch.jit.is_tracing... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/experimental.py |
Generate NumPy-style docstrings | import asyncio
import atexit
import logging
from threading import BoundedSemaphore, Thread
from typing import Callable, Optional
import torch
# Based on graphlearn-for-pytorch repository python/distributed/event_loop.py
# https://github.com/alibaba/graphlearn-for-pytorch/blob/main/graphlearn_torch/
# LICENSE: Apache ... | --- +++ @@ -12,6 +12,7 @@
def to_asyncio_future(future: torch.futures.Future) -> asyncio.futures.Future:
+ r"""Convert a :class:`torch.futures.Future` to a :obj:`asyncio` future."""
loop = asyncio.get_event_loop()
asyncio_future = loop.create_future()
@@ -29,6 +30,11 @@
class ConcurrentEventLoop:... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/distributed/event_loop.py |
Add missing documentation to my Python functions | import itertools
import logging
import math
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
from warnings import warn
import numpy as np
import torch
import torch.multiprocessing as mp
from torch import Tensor
from torch_geometric.distributed import (
DistContext,
LocalFeatureStore,
L... | --- +++ @@ -48,6 +48,9 @@
class RPCSamplingCallee(RPCCallBase):
+ r"""A wrapper for RPC callee that will perform RPC sampling from remote
+ processes.
+ """
def __init__(self, sampler: NeighborSampler):
super().__init__()
self.sampler = sampler
@@ -60,6 +63,10 @@
class DistNeighb... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/distributed/dist_neighbor_sampler.py |
Add docstrings to improve code quality | import functools
from enum import Enum
from typing import (
Any,
Callable,
Dict,
Iterable,
List,
Literal,
NamedTuple,
Optional,
Sequence,
Tuple,
Type,
Union,
get_args,
overload,
)
import numpy as np
import torch
import torch.utils._pytree as pytree
from torch imp... | --- +++ @@ -57,6 +57,7 @@
def implements(torch_function: Callable) -> Callable:
+ r"""Registers a :pytorch:`PyTorch` function override."""
@functools.wraps(torch_function)
def decorator(my_function: Callable) -> Callable:
HANDLED_FUNCTIONS[torch_function] = my_function
@@ -150,6 +151,69 @@
... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/edge_index.py |
Write docstrings that follow conventions | import logging
from typing import Dict, List, Optional, Union, overload
import torch
from torch import Tensor
from torch_geometric.explain import Explanation, HeteroExplanation
from torch_geometric.explain.algorithm import ExplainerAlgorithm
from torch_geometric.explain.config import ExplanationType, ModelTaskLevel
f... | --- +++ @@ -12,6 +12,18 @@
class AttentionExplainer(ExplainerAlgorithm):
+ r"""An explainer that uses the attention coefficients produced by an
+ attention-based GNN (*e.g.*,
+ :class:`~torch_geometric.nn.conv.GATConv`,
+ :class:`~torch_geometric.nn.conv.GATv2Conv`, or
+ :class:`~torch_geometric.nn.c... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/explain/algorithm/attention_explainer.py |
Help me add docstrings to my project | import inspect
import logging
import warnings
from typing import Any, Dict, Optional, Union
import torch
from torch import Tensor
from torch_geometric.explain import Explanation, HeteroExplanation
from torch_geometric.explain.algorithm import ExplainerAlgorithm
from torch_geometric.explain.algorithm.captum import (
... | --- +++ @@ -20,6 +20,27 @@
class CaptumExplainer(ExplainerAlgorithm):
+ """A `Captum <https://captum.ai>`__-based explainer for identifying compact
+ subgraph structures and node features that play a crucial role in the
+ predictions made by a GNN.
+
+ This explainer algorithm uses :captum:`null` `Captu... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/explain/algorithm/captum_explainer.py |
Create docstrings for all classes and functions | from enum import Enum
from typing import Dict, Optional, Tuple, Union
import torch
from torch import Tensor
from torch_geometric.explain.algorithm.utils import (
clear_masks,
set_hetero_masks,
set_masks,
)
from torch_geometric.explain.config import (
ModelConfig,
ModelMode,
ModelReturnType,
)
... | --- +++ @@ -18,6 +18,7 @@
class MaskLevelType(Enum):
+ """Enum class for the mask level type."""
node = 'node'
edge = 'edge'
node_and_edge = 'node_and_edge'
@@ -43,6 +44,7 @@ self.model_config = model_config
def forward(self, mask, *args):
+ """""" # noqa: D419
# Th... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/explain/algorithm/captum.py |
Write docstrings for algorithm functions | import copy
from typing import Dict, List, Optional, Tuple, Union
import torch
from torch import Tensor
from torch_geometric.data.data import Data, warn_or_raise
from torch_geometric.data.hetero_data import HeteroData
from torch_geometric.explain.config import ThresholdConfig, ThresholdType
from torch_geometric.typin... | --- +++ @@ -17,9 +17,11 @@ class ExplanationMixin:
@property
def available_explanations(self) -> List[str]:
+ """Returns the available explanation masks."""
return [key for key in self.keys() if key.endswith('_mask')]
def validate_masks(self, raise_on_error: bool = True) -> bool:
+ ... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/explain/explanation.py |
Write documentation strings for class attributes | from abc import abstractmethod
from typing import Dict, Optional, Tuple, Union
import torch
import torch.nn.functional as F
from torch import Tensor
from torch_geometric.explain import Explanation, HeteroExplanation
from torch_geometric.explain.config import (
ExplainerConfig,
ModelConfig,
ModelReturnType... | --- +++ @@ -17,6 +17,7 @@
class ExplainerAlgorithm(torch.nn.Module):
+ r"""An abstract base class for implementing explainer algorithms."""
@abstractmethod
def forward(
self,
@@ -28,14 +29,33 @@ index: Optional[Union[int, Tensor]] = None,
**kwargs,
) -> Union[Explanation,... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/explain/algorithm/base.py |
Please document this code using docstrings | from typing import Dict, Union
import torch
from torch import Tensor
from torch.nn import Parameter
from torch_geometric.nn import MessagePassing
from torch_geometric.typing import EdgeType
def set_masks(
model: torch.nn.Module,
mask: Union[Tensor, Parameter],
edge_index: Tensor,
apply_sigmoid: bool... | --- +++ @@ -14,6 +14,7 @@ edge_index: Tensor,
apply_sigmoid: bool = True,
):
+ r"""Apply mask to every graph layer in the :obj:`model`."""
loop_mask = edge_index[0] != edge_index[1]
# Loop over layers and set masks on MessagePassing layers:
@@ -42,6 +43,9 @@ edge_index_dict: Dict[EdgeType, ... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/explain/algorithm/utils.py |
Add standardized docstrings across the file | from typing import Tuple
import torch
from torch import Tensor
from torch_geometric.explain import Explainer, Explanation
from torch_geometric.explain.config import ExplanationType, ModelMode
def fidelity(
explainer: Explainer,
explanation: Explanation,
) -> Tuple[float, float]:
if explainer.model_confi... | --- +++ @@ -11,6 +11,42 @@ explainer: Explainer,
explanation: Explanation,
) -> Tuple[float, float]:
+ r"""Evaluates the fidelity of an
+ :class:`~torch_geometric.explain.Explainer` given an
+ :class:`~torch_geometric.explain.Explanation`, as described in the
+ `"GraphFramEx: Towards Systematic Ev... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/explain/metric/fidelity.py |
Insert docstrings into my code | import functools
import inspect
import logging
import os
import os.path as osp
import warnings
from collections.abc import Iterable
from dataclasses import asdict
from typing import Any
import torch_geometric.graphgym.register as register
from torch_geometric.io import fs
try: # Define global config object
from ... | --- +++ @@ -22,6 +22,16 @@
def set_cfg(cfg):
+ r"""This function sets the default config value.
+
+ 1) Note that for an experiment, only part of the arguments will be used
+ The remaining unused arguments won't affect anything.
+ So feel free to register any argument in graphgym.contrib.config
+ ... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/graphgym/config.py |
Write clean docstrings for readability | import math
from typing import List, Optional, Tuple, Union
import torch
import torch.nn.functional as F
from torch import Tensor
from torch.nn import LayerNorm, Linear, Parameter, ReLU
from tqdm import tqdm
from torch_geometric.explain import Explanation
from torch_geometric.explain.algorithm import ExplainerAlgorit... | --- +++ @@ -37,6 +37,42 @@
class GraphMaskExplainer(ExplainerAlgorithm):
+ r"""The GraphMask-Explainer model from the `"Interpreting Graph Neural
+ Networks for NLP With Differentiable Edge Masking"
+ <https://arxiv.org/abs/2010.00577>`_ paper for identifying layer-wise
+ compact subgraph structures and... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/explain/algorithm/graphmask_explainer.py |
Add detailed docstrings explaining each function | import json
import os
import os.path as osp
from glob import glob
from typing import Callable, Dict, List, Optional
import numpy as np
import torch
from tqdm import tqdm
from torch_geometric.data import (
Data,
InMemoryDataset,
download_url,
extract_zip,
)
class Teeth3DS(InMemoryDataset):
urls =... | --- +++ @@ -17,6 +17,37 @@
class Teeth3DS(InMemoryDataset):
+ r"""The Teeth3DS+ dataset from the `"An Extended Benchmark for Intra-oral
+ 3D Scans Analysis" <https://crns-smartvision.github.io/teeth3ds/>`_ paper.
+
+ This dataset is the first comprehensive public benchmark designed to
+ advance the fiel... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/datasets/teeth3ds.py |
Add docstrings to improve readability | import logging
from typing import Dict, Optional, Tuple, Union, overload
import torch
from torch import Tensor
from torch.nn import ReLU, Sequential
from torch_geometric.explain import Explanation, HeteroExplanation
from torch_geometric.explain.algorithm import ExplainerAlgorithm
from torch_geometric.explain.algorith... | --- +++ @@ -24,6 +24,41 @@
class PGExplainer(ExplainerAlgorithm):
+ r"""The PGExplainer model from the `"Parameterized Explainer for Graph
+ Neural Network" <https://arxiv.org/abs/2011.04573>`_ paper.
+
+ Internally, it utilizes a neural network to identify subgraph structures
+ that play a crucial role... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/explain/algorithm/pg_explainer.py |
Write docstrings describing functionality | # Code adapted from the G-Retriever paper: https://arxiv.org/abs/2402.07630
import gc
import os
from itertools import chain
from typing import Any, Dict, Iterator, List, Optional
import torch
from tqdm import tqdm
from torch_geometric.data import InMemoryDataset
from torch_geometric.llm.large_graph_indexer import (
... | --- +++ @@ -22,6 +22,29 @@
class KGQABaseDataset(InMemoryDataset):
+ r"""Base class for the 2 KGQA datasets used in `"Reasoning on Graphs:
+ Faithful and Interpretable Large Language Model Reasoning"
+ <https://arxiv.org/pdf/2310.01061>`_ paper.
+
+ Args:
+ dataset_name (str): HuggingFace `datase... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/datasets/web_qsp_dataset.py |
Generate docstrings for script automation | from itertools import chain
from typing import Callable, List, Optional
import torch
from torch_geometric.data import Data, InMemoryDataset, download_url
from torch_geometric.utils import index_sort
class WordNet18(InMemoryDataset):
url = ('https://raw.githubusercontent.com/villmow/'
'datasets_knowl... | --- +++ @@ -8,6 +8,35 @@
class WordNet18(InMemoryDataset):
+ r"""The WordNet18 dataset from the `"Translating Embeddings for Modeling
+ Multi-Relational Data"
+ <https://papers.nips.cc/paper/5071-translating-embeddings-for-modeling
+ -multi-relational-data>`_ paper,
+ containing 40,943 entities, 18 r... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/datasets/word_net.py |
Please document this code using docstrings | import torch
import torch.nn.functional as F
import torch_geometric.graphgym.register as register
from torch_geometric.graphgym.config import cfg
from torch_geometric.graphgym.init import init_weights
from torch_geometric.graphgym.models.layer import (
BatchNorm1dNode,
GeneralLayer,
GeneralMultiLayer,
... | --- +++ @@ -14,6 +14,15 @@
def GNNLayer(dim_in: int, dim_out: int, has_act: bool = True) -> GeneralLayer:
+ r"""Creates a GNN layer, given the specified input and output dimensions
+ and the underlying configuration in :obj:`cfg`.
+
+ Args:
+ dim_in (int): The input dimension
+ dim_out (int):... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/graphgym/models/gnn.py |
Write docstrings for backend logic | import torch
from torch_geometric.graphgym.register import (
register_edge_encoder,
register_node_encoder,
)
@register_node_encoder('Integer')
class IntegerFeatureEncoder(torch.nn.Module):
def __init__(self, emb_dim: int, num_classes: int):
super().__init__()
self.encoder = torch.nn.Embe... | --- +++ @@ -8,6 +8,18 @@
@register_node_encoder('Integer')
class IntegerFeatureEncoder(torch.nn.Module):
+ r"""Provides an encoder for integer node features.
+
+ Args:
+ emb_dim (int): The output embedding dimension.
+ num_classes (int): The number of classes/integers.
+
+ Example:
+ >>... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/graphgym/models/encoder.py |
Improve documentation using docstrings | import torch
from torch_geometric.utils import negative_sampling
def create_link_label(pos_edge_index, neg_edge_index):
num_links = pos_edge_index.size(1) + neg_edge_index.size(1)
link_labels = torch.zeros(num_links, dtype=torch.float,
device=pos_edge_index.device)
link_labe... | --- +++ @@ -4,6 +4,15 @@
def create_link_label(pos_edge_index, neg_edge_index):
+ """Create labels for link prediction, based on positive and negative edges.
+
+ Args:
+ pos_edge_index (torch.tensor): Positive edge index [2, num_edges]
+ neg_edge_index (torch.tensor): Negative edge index [2, num... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/graphgym/models/transform.py |
Document classes and their methods | import warnings
from typing import Any, Dict, Optional
import torch
from torch.utils.data import DataLoader
from torch_geometric.data.lightning.datamodule import LightningDataModule
from torch_geometric.graphgym import create_loader
from torch_geometric.graphgym.checkpoint import get_ckpt_dir
from torch_geometric.gra... | --- +++ @@ -14,6 +14,13 @@
class GraphGymDataModule(LightningDataModule):
+ r"""A :class:`pytorch_lightning.LightningDataModule` for handling data
+ loading routines in GraphGym.
+
+ This class provides data loaders for training, validation, and testing, and
+ can be accessed through the :meth:`train_da... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/graphgym/train.py |
Add docstrings that explain logic | import math
from torch_geometric.graphgym.config import cfg, set_cfg
from torch_geometric.graphgym.model_builder import create_model
def params_count(model):
return sum([p.numel() for p in model.parameters()])
def get_stats():
model = create_model(to_device=False, dim_in=1, dim_out=1)
return params_cou... | --- +++ @@ -5,6 +5,11 @@
def params_count(model):
+ """Computes the number of parameters.
+
+ Args:
+ model (nn.Module): PyTorch model
+ """
return sum([p.numel() for p in model.parameters()])
@@ -14,6 +19,7 @@
def match_computation(stats_baseline, key=None, mode='sqrt'):
+ """Match ... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/graphgym/utils/comp_budget.py |
Create docstrings for API functions | import os.path as osp
from typing import Any, Dict, List, Optional, Tuple, Union
import torch
from torch import Tensor
from torch_geometric.data import EdgeAttr, GraphStore
from torch_geometric.distributed.partition import load_partition_info
from torch_geometric.io import fs
from torch_geometric.typing import EdgeTe... | --- +++ @@ -12,6 +12,9 @@
class LocalGraphStore(GraphStore):
+ r"""Implements the :class:`~torch_geometric.data.GraphStore` interface to
+ act as a local graph store for distributed training.
+ """
def __init__(self):
super().__init__()
self._edge_index: Dict[Tuple, EdgeTensorType] =... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/distributed/local_graph_store.py |
Create docstrings for reusable components | import logging
import os
import os.path as osp
import numpy as np
from torch_geometric.graphgym.config import cfg
from torch_geometric.graphgym.utils.io import (
dict_list_to_json,
dict_list_to_tb,
dict_to_json,
json_to_dict_list,
makedirs_rm_exist,
string_to_python,
)
try:
from tensorboa... | --- +++ @@ -44,6 +44,11 @@
def agg_dict_list(dict_list):
+ """Aggregate a list of dictionaries: mean + std
+ Args:
+ dict_list: list of dictionaries.
+
+ """
dict_agg = {'epoch': dict_list[0]['epoch']}
for key in dict_list[0]:
if key != 'epoch':
@@ -75,6 +80,14 @@
def agg_runs... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/graphgym/utils/agg_runs.py |
Add documentation for all methods | import os
import subprocess
import numpy as np
import torch
from torch_geometric.graphgym.config import cfg
def get_gpu_memory_map():
result = subprocess.check_output([
'nvidia-smi', '--query-gpu=memory.used',
'--format=csv,nounits,noheader'
], encoding='utf-8')
gpu_memory = np.array([in... | --- +++ @@ -8,6 +8,7 @@
def get_gpu_memory_map():
+ """Get the current GPU usage."""
result = subprocess.check_output([
'nvidia-smi', '--query-gpu=memory.used',
'--format=csv,nounits,noheader'
@@ -17,6 +18,7 @@
def get_current_gpu_usage():
+ """Get the current GPU memory usage."""
... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/graphgym/utils/device.py |
Add docstrings for internal functions | import copy
from dataclasses import dataclass, replace
import torch
import torch.nn.functional as F
import torch_geometric as pyg
import torch_geometric.graphgym.models.act
import torch_geometric.graphgym.register as register
from torch_geometric.graphgym.contrib.layer.generalconv import (
GeneralConvLayer,
G... | --- +++ @@ -52,6 +52,17 @@ has_bias: bool,
cfg,
) -> LayerConfig:
+ r"""Create a layer configuration for a GNN layer.
+
+ Args:
+ dim_in (int): The input feature dimension.
+ dim_out (int): The output feature dimension.
+ num_layers (int): The number of hidden layers
+ has_ac... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/graphgym/models/layer.py |
Create docstrings for each class method | from torch_geometric.graphgym.config import cfg
def is_train_eval_epoch(cur_epoch):
return is_eval_epoch(cur_epoch) or not cfg.train.skip_train_eval
def is_eval_epoch(cur_epoch):
return ((cur_epoch + 1) % cfg.train.eval_period == 0 or cur_epoch == 0
or (cur_epoch + 1) == cfg.optim.max_epoch)
d... | --- +++ @@ -2,14 +2,17 @@
def is_train_eval_epoch(cur_epoch):
+ """Determines if the model should be evaluated at the training epoch."""
return is_eval_epoch(cur_epoch) or not cfg.train.skip_train_eval
def is_eval_epoch(cur_epoch):
+ """Determines if the model should be evaluated at the current epoc... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/graphgym/utils/epoch.py |
Add well-formatted docstrings | import ast
import json
import os
import os.path as osp
from torch_geometric.io import fs
def string_to_python(string):
try:
return ast.literal_eval(string)
except Exception:
return string
def dict_to_json(dict, fname):
with open(fname, 'a') as f:
json.dump(dict, f)
f.wri... | --- +++ @@ -14,12 +14,24 @@
def dict_to_json(dict, fname):
+ """Dump a :python:`Python` dictionary to a JSON file.
+
+ Args:
+ dict (dict): The :python:`Python` dictionary.
+ fname (str): The output file name.
+ """
with open(fname, 'a') as f:
json.dump(dict, f)
f.write... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/graphgym/utils/io.py |
Add detailed docstrings explaining each function | import functools
import warnings
from typing import (
Any,
Callable,
Dict,
Iterable,
List,
Optional,
Tuple,
Type,
Union,
)
import numpy as np
import torch
import torch.utils._pytree as pytree
import xxhash
from torch import Tensor
import torch_geometric.typing
from torch_geometric.... | --- +++ @@ -27,6 +27,7 @@
def implements(torch_function: Callable) -> Callable:
+ r"""Registers a :pytorch:`PyTorch` function override."""
@functools.wraps(torch_function)
def decorator(my_function: Callable) -> Callable:
HANDLED_FUNCTIONS[torch_function] = my_function
@@ -86,6 +87,62 @@
c... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/hash_tensor.py |
Write documentation strings for class attributes | import functools
from typing import (
Any,
Callable,
Dict,
Iterable,
List,
NamedTuple,
Optional,
Tuple,
Type,
Union,
)
import numpy as np
import torch
import torch.utils._pytree as pytree
from torch import Tensor
from torch_geometric.typing import INDEX_DTYPES
aten = torch.ops... | --- +++ @@ -44,6 +44,7 @@
def implements(torch_function: Callable) -> Callable:
+ r"""Registers a :pytorch:`PyTorch` function override."""
@functools.wraps(torch_function)
def decorator(my_function: Callable) -> Callable:
HANDLED_FUNCTIONS[torch_function] = my_function
@@ -85,6 +86,51 @@
c... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/index.py |
Include argument descriptions in docstrings | import os
import os.path as osp
from typing import Optional
ENV_PYG_HOME = 'PYG_HOME'
DEFAULT_CACHE_DIR = osp.join('~', '.cache', 'pyg')
_home_dir: Optional[str] = None
def get_home_dir() -> str:
if _home_dir is not None:
return _home_dir
return osp.expanduser(os.getenv(ENV_PYG_HOME, DEFAULT_CACHE_... | --- +++ @@ -9,6 +9,11 @@
def get_home_dir() -> str:
+ r"""Get the cache directory used for storing all :pyg:`PyG`-related data.
+
+ If :meth:`set_home_dir` is not called, the path is given by the environment
+ variable :obj:`$PYG_HOME` which defaults to :obj:`"~/.cache/pyg"`.
+ """
if _home_dir is ... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/home.py |
Add docstrings that explain logic | import inspect
import re
import sys
import typing
from typing import Any, Callable, Dict, List, NamedTuple, Optional, Type, Union
import torch
from torch import Tensor
class Parameter(NamedTuple):
name: str
type: Type
type_repr: str
default: Any
class Signature(NamedTuple):
param_dict: Dict[str... | --- +++ @@ -22,6 +22,12 @@
class Inspector:
+ r"""Inspects a given class and collects information about its instance
+ methods.
+
+ Args:
+ cls (Type): The class to inspect.
+ """
def __init__(self, cls: Type):
self._cls = cls
self._signature_dict: Dict[str, Signature] = {}... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/inspector.py |
Write clean docstrings for readability | import re
from typing import List
import torch
from torch import Tensor
from torch._tensor_str import PRINT_OPTS, _tensor_str
from torch_geometric.data import Data
from torch_geometric.io import parse_txt_array
def parse_off(src: List[str]) -> Data:
# Some files may contain a bug and do not have a carriage retu... | --- +++ @@ -45,12 +45,26 @@
def read_off(path: str) -> Data:
+ r"""Reads an OFF (Object File Format) file, returning both the position of
+ nodes and their connectivity in a :class:`torch_geometric.data.Data`
+ object.
+
+ Args:
+ path (str): The path to the file.
+ """
with open(path) as... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/io/off.py |
Generate docstrings with examples | import logging
import threading
from abc import ABC, abstractmethod
from typing import Any, Callable, Dict, List, Optional
from torch.distributed import rpc
from torch_geometric.distributed.dist_context import DistContext, DistRole
try:
from torch._C._distributed_rpc import _is_current_rpc_agent_set
except Excep... | --- +++ @@ -30,6 +30,7 @@
@rpc_require_initialized
def global_all_gather(obj, timeout: Optional[int] = None) -> Any:
+ r"""Gathers objects from all groups in a list."""
if timeout is None:
return rpc.api._all_gather(obj)
return rpc.api._all_gather(obj, timeout=timeout)
@@ -37,6 +38,7 @@
@rpc_... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/distributed/rpc.py |
Improve my code by adding docstrings | import os
import pickle as pkl
import shutil
from dataclasses import dataclass
from itertools import chain, islice, tee
from typing import (
Any,
Callable,
Dict,
Iterable,
Iterator,
List,
Optional,
Sequence,
Set,
Tuple,
Union,
)
import torch
from torch import Tensor
from tqd... | --- +++ @@ -71,6 +71,10 @@
class LargeGraphIndexer:
+ """For a dataset that consists of multiple subgraphs that are assumed to
+ be part of a much larger graph, collate the values into a large graph store
+ to save resources.
+ """
def __init__(
self,
nodes: Iterable[str],
@@ -78,... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/llm/large_graph_indexer.py |
Expand my code with proper documentation strings | from typing import List, Optional
import torch
from torch import Tensor
from torch_geometric.llm.models.llm import LLM, MAX_NEW_TOKENS
from torch_geometric.utils import scatter
class GRetriever(torch.nn.Module):
def __init__(
self,
llm: LLM,
gnn: torch.nn.Module = None,
use_lora:... | --- +++ @@ -8,6 +8,37 @@
class GRetriever(torch.nn.Module):
+ r"""The G-Retriever model from the `"G-Retriever: Retrieval-Augmented
+ Generation for Textual Graph Understanding and Question Answering"
+ <https://arxiv.org/abs/2402.07630>`_ paper.
+
+ Args:
+ llm (LLM): The LLM to use.
+ gn... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/llm/models/g_retriever.py |
Add docstrings that explain purpose and usage | import warnings
from contextlib import nullcontext
from typing import Any, Dict, List, Optional
import torch
from torch import Tensor
try:
from transformers.tokenization_utils_base import BatchEncoding
except ImportError:
BatchEncoding = Dict
IGNORE_INDEX = -100
MAX_TXT_LEN = 512
MAX_NEW_TOKENS = 128
PAD_TOK... | --- +++ @@ -49,6 +49,24 @@
class LLM(torch.nn.Module):
+ r"""A wrapper around a Large Language Model (LLM) from HuggingFace.
+
+ Args:
+ model_name (str): The HuggingFace model name
+ num_params (float, optional): An integer representing how many params
+ the HuggingFace model has, in... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/llm/models/llm.py |
Add docstrings to meet PEP guidelines | from enum import Enum
from typing import List, Optional, Union
import torch
import torch.nn.functional as F
from torch import Tensor
from tqdm import tqdm
class PoolingStrategy(Enum):
MEAN = 'mean'
LAST = 'last'
CLS = 'cls'
LAST_HIDDEN_STATE = 'last_hidden_state'
class SentenceTransformer(torch.nn.... | --- +++ @@ -15,6 +15,13 @@
class SentenceTransformer(torch.nn.Module):
+ r"""A wrapper around a Sentence-Transformer from HuggingFace.
+
+ Args:
+ model_name (str): The HuggingFace model name, *e.g.*, :obj:`"BERT"`.
+ pooling_strategy (str, optional): The pooling strategy to use
+ for... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/llm/models/sentence_transformer.py |
Write docstrings for data processing functions | from dataclasses import dataclass
from enum import Enum
from typing import Optional, Union
from torch_geometric.utils.mixin import CastMixin
class ExplanationType(Enum):
model = 'model'
phenomenon = 'phenomenon'
class MaskType(Enum):
object = 'object'
common_attributes = 'common_attributes'
att... | --- +++ @@ -6,35 +6,41 @@
class ExplanationType(Enum):
+ """Enum class for the explanation type."""
model = 'model'
phenomenon = 'phenomenon'
class MaskType(Enum):
+ """Enum class for the mask type."""
object = 'object'
common_attributes = 'common_attributes'
attributes = 'attrib... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/explain/config.py |
Add docstrings that explain inputs and outputs | from math import isnan
from typing import Optional
from torch_geometric.llm.models.txt2kg import \
_chunk_to_triples_str_cloud as call_NIM
# Credit for original "Marlin Accuracy" system goes to:
# Gilberto Titericz (NVIDIA)
# This work is an adaptation of his for PyG
SYSTEM_PROMPT_1 = (
"Instruction: You are ... | --- +++ @@ -51,6 +51,21 @@ # TODO: add support for Local LM
# TODO: add multiproc support like txt2kg
class LLMJudge():
+ """Uses NIMs to score a triple of (question, model_pred, correct_answer)
+ This whole class is an adaptation of Gilberto's work for PyG.
+
+ Args:
+ NVIDIA_NIM_MODEL : (str, option... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/llm/models/llm_judge.py |
Generate docstrings for script automation | import warnings
from typing import Any, Dict, Optional, Union
import torch
from torch import Tensor
from torch_geometric.explain import (
ExplainerAlgorithm,
Explanation,
HeteroExplanation,
)
from torch_geometric.explain.algorithm.utils import (
clear_masks,
set_hetero_masks,
set_masks,
)
from... | --- +++ @@ -27,6 +27,45 @@
class Explainer:
+ r"""An explainer class for instance-level explanations of Graph Neural
+ Networks.
+
+ Args:
+ model (torch.nn.Module): The model to explain.
+ algorithm (ExplainerAlgorithm): The explanation algorithm.
+ explanation_type (ExplanationType o... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/explain/explainer.py |
Expand my code with proper documentation strings | from math import sqrt
from typing import Dict, Optional, Tuple, Union, overload
import torch
from torch import Tensor
from torch.nn.parameter import Parameter
from torch_geometric.explain import (
ExplainerConfig,
Explanation,
HeteroExplanation,
ModelConfig,
)
from torch_geometric.explain.algorithm im... | --- +++ @@ -22,6 +22,44 @@
class GNNExplainer(ExplainerAlgorithm):
+ r"""The GNN-Explainer model from the `"GNNExplainer: Generating
+ Explanations for Graph Neural Networks"
+ <https://arxiv.org/abs/1903.03894>`_ paper for identifying compact subgraph
+ structures and node features that play a crucial ... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/explain/algorithm/gnn_explainer.py |
Generate docstrings for this script | # mypy: ignore-errors
import os
from abc import abstractmethod
from typing import Any, Callable, Dict, List, Optional, Protocol, Union
import torch
from torch import Tensor
from torch_geometric.data import Data
from torch_geometric.llm.models import SentenceTransformer
from torch_geometric.llm.utils.backend_utils imp... | --- +++ @@ -12,17 +12,31 @@
class VectorRetriever(Protocol):
+ """Protocol for VectorRAG."""
@abstractmethod
def query(self, query: Any, **kwargs: Optional[Dict[str, Any]]) -> Data:
+ """Retrieve a context for a given query."""
...
class DocumentRetriever(VectorRetriever):
+ """... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/llm/utils/vectorrag.py |
Generate docstrings for script automation | from typing import List, Optional, Union
import torch
import torch.nn as nn
from tqdm import tqdm
from torch_geometric.loader import DataLoader, NeighborLoader
from torch_geometric.nn.models import GraphSAGE, basic_gnn
def deal_nan(x):
if isinstance(x, torch.Tensor):
x = x.clone()
x[torch.isnan(... | --- +++ @@ -16,6 +16,33 @@
class GLEM(torch.nn.Module):
+ r"""This GNN+LM co-training model is based on GLEM from the `"Learning on
+ Large-scale Text-attributed Graphs via Variational Inference"
+ <https://arxiv.org/abs/2210.14709>`_ paper.
+
+ Args:
+ lm_to_use (str): A TextEncoder from hugging... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/llm/models/glem.py |
Create structured documentation for my script | from typing import Any, Dict, Optional, Tuple, Union
import torch
from torch import Tensor
from torch_geometric.data import FeatureStore
from torch_geometric.distributed.local_graph_store import LocalGraphStore
from torch_geometric.sampler import (
BidirectionalNeighborSampler,
NodeSamplerInput,
SamplerOu... | --- +++ @@ -22,11 +22,21 @@
class NeighborSamplingRAGGraphStore(LocalGraphStore):
+ """Neighbor sampling based graph-store to store & retrieve graph data."""
def __init__( # type: ignore[no-untyped-def]
self,
feature_store: Optional[FeatureStore] = None,
**kwargs,
):
+ ... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/llm/utils/graph_store.py |
Add professional docstrings to my codebase | import glob
import os
import os.path as osp
from typing import Any, Dict, List, Optional, Union
import torch
from torch_geometric.graphgym.config import cfg
from torch_geometric.io import fs
MODEL_STATE = 'model_state'
OPTIMIZER_STATE = 'optimizer_state'
SCHEDULER_STATE = 'scheduler_state'
def load_ckpt(
model... | --- +++ @@ -19,6 +19,7 @@ scheduler: Optional[Any] = None,
epoch: int = -1,
) -> int:
+ r"""Loads the model checkpoint at a given epoch."""
epoch = get_ckpt_epoch(epoch)
path = get_ckpt_path(epoch)
@@ -41,6 +42,7 @@ scheduler: Optional[Any] = None,
epoch: int = 0,
):
+ r"""Saves th... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/graphgym/checkpoint.py |
Help me write clear docstrings | import copy
import os
import os.path as osp
import sys
from dataclasses import dataclass
from typing import List, Literal, Optional
import torch
import torch.utils.data
from torch import Tensor
import torch_geometric.typing
from torch_geometric.data import Data
from torch_geometric.index import index2ptr, ptr2index
f... | --- +++ @@ -29,6 +29,31 @@
class ClusterData(torch.utils.data.Dataset):
+ r"""Clusters/partitions a graph data object into multiple subgraphs, as
+ motivated by the `"Cluster-GCN: An Efficient Algorithm for Training Deep
+ and Large Graph Convolutional Networks"
+ <https://arxiv.org/abs/1905.07953>`_ pa... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/loader/cluster.py |
Add concise docstrings to each method | import logging
import math
from typing import (
Any,
Callable,
Iterator,
List,
NamedTuple,
Optional,
Tuple,
Union,
)
import numpy as np
import torch
from torch import Tensor
from tqdm import tqdm
from torch_geometric.data import Data
from torch_geometric.typing import SparseTensor
from... | --- +++ @@ -553,6 +553,54 @@
class IBMBBatchLoader(IBMBBaseLoader):
+ r"""The batch-wise influence-based data loader from the
+ `"Influence-Based Mini-Batching for Graph Neural Networks"
+ <https://arxiv.org/abs/2212.09083>`__ paper.
+
+ First, the METIS graph partitioning algorithm separates the graph ... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/loader/ibmb_loader.py |
Write docstrings describing each step | import os.path as osp
from typing import Callable
import torch
import torch_geometric.graphgym.register as register
import torch_geometric.transforms as T
from torch_geometric.datasets import (
PPI,
Amazon,
Coauthor,
KarateClub,
MNISTSuperpixels,
Planetoid,
QM7b,
TUDataset,
)
from torc... | --- +++ @@ -49,6 +49,15 @@
def load_pyg(name, dataset_dir):
+ """Load PyG dataset objects. (More PyG datasets will be supported).
+
+ Args:
+ name (str): dataset name
+ dataset_dir (str): data directory
+
+ Returns: PyG dataset object
+
+ """
dataset_dir = osp.join(dataset_dir, name)
... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/graphgym/loader.py |
Add inline docstrings for readability | import os
import time
from typing import List, Optional, Tuple, Union
import torch
import torch.multiprocessing as mp
CLIENT_INITD = False
CLIENT = None
GLOBAL_NIM_KEY = ""
SYSTEM_PROMPT = "Please convert the above text into a list of knowledge triples with the form ('entity', 'relation', 'entity'). Separate each wi... | --- +++ @@ -17,6 +17,40 @@
class TXT2KG():
+ """A class to convert text data into a Knowledge Graph (KG) format.
+ Uses NVIDIA NIMs + Prompt engineering by default.
+ Default model `nvidia/llama-3.1-nemotron-70b-instruct`
+ is on par or better than GPT4o in benchmarks.
+ We need a high quality model ... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/llm/models/txt2kg.py |
Add docstrings for better understanding | import gc
from collections.abc import Iterable, Iterator
from typing import Any, Dict, List, Tuple, Union
import torch
from torch import Tensor
from torch_geometric.data import Data, HeteroData
from torch_geometric.distributed.local_feature_store import LocalFeatureStore
from torch_geometric.llm.utils.backend_utils i... | --- +++ @@ -14,7 +14,9 @@
# NOTE: Only compatible with Homogeneous graphs for now
class KNNRAGFeatureStore(LocalFeatureStore):
+ """A feature store that uses a KNN-based retrieval."""
def __init__(self) -> None:
+ """Initializes the feature store."""
# to be set by the config
self.en... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/llm/utils/feature_store.py |
Replace inline comments with docstrings | import copy
import logging
import math
from typing import Any, Dict, Optional, Tuple, Union
import numpy as np
import torch
from torch import Tensor
import torch_geometric.typing
from torch_geometric.data import (
Data,
FeatureStore,
GraphStore,
HeteroData,
TensorAttr,
remote_backend_utils,
)
... | --- +++ @@ -34,6 +34,22 @@ index: Tensor,
dim: int = 0,
) -> Tensor:
+ r"""Indexes the :obj:`value` tensor along dimension :obj:`dim` using the
+ entries in :obj:`index`.
+
+ Args:
+ value (torch.Tensor or np.ndarray): The input tensor.
+ index (torch.Tensor): The 1-D tensor containing ... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/loader/utils.py |
Document functions with clear intent | from abc import abstractmethod
from typing import Any, Callable, Dict, Optional, Protocol, Tuple, Union
from torch_geometric.data import Data, FeatureStore, HeteroData
from torch_geometric.llm.utils.vectorrag import VectorRetriever
from torch_geometric.sampler import HeteroSamplerOutput, SamplerOutput
from torch_geome... | --- +++ @@ -8,49 +8,68 @@
class RAGFeatureStore(Protocol):
+ """Feature store template for remote GNN RAG backend."""
@abstractmethod
def retrieve_seed_nodes(self, query: Any, **kwargs) -> InputNodes:
+ """Makes a comparison between the query and all the nodes to get all
+ the closest nod... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/llm/rag_loader.py |
Write reusable docstrings | from typing import Callable, List, Optional, Tuple
import torch
from torch import Tensor
from torch_geometric.nn.aggr import Aggregation
from torch_geometric.nn.inits import reset
from torch_geometric.utils import scatter
class ResNetPotential(torch.nn.Module):
def __init__(self, in_channels: int, out_channels:... | --- +++ @@ -48,6 +48,16 @@
class MomentumOptimizer(torch.nn.Module):
+ r"""Provides an inner loop optimizer for the implicitly defined output
+ layer. It is based on an unrolled Nesterov momentum algorithm.
+
+ Args:
+ learning_rate (float): learning rate for optimizer.
+ momentum (float): mo... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/aggr/equilibrium.py |
Write proper docstrings for these functions | from dataclasses import dataclass, field
from typing import Any, Iterator, List, Optional
from torch.nn import Parameter
from torch.optim import SGD, Adam, Optimizer
from torch.optim.lr_scheduler import CosineAnnealingLR, MultiStepLR, StepLR
import torch_geometric.graphgym.register as register
from torch_geometric.gr... | --- +++ @@ -31,6 +31,7 @@
def create_optimizer(params: Iterator[Parameter], cfg: Any) -> Any:
+ r"""Creates a config-driven optimizer."""
params = filter(lambda p: p.requires_grad, params)
func = register.optimizer_dict.get(cfg.optimizer, None)
if func is not None:
@@ -64,7 +65,8 @@
def create... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/graphgym/optim.py |
Help me add docstrings to my project | import os.path as osp
from typing import Optional
import torch
from tqdm import tqdm
from torch_geometric.io import fs
from torch_geometric.typing import SparseTensor
class GraphSAINTSampler(torch.utils.data.DataLoader):
def __init__(self, data, batch_size: int, num_steps: int = 1,
sample_cover... | --- +++ @@ -9,6 +9,40 @@
class GraphSAINTSampler(torch.utils.data.DataLoader):
+ r"""The GraphSAINT sampler base class from the `"GraphSAINT: Graph
+ Sampling Based Inductive Learning Method"
+ <https://arxiv.org/abs/1907.04931>`_ paper.
+ Given a graph in a :obj:`data` object, this class samples nodes ... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/loader/graph_saint.py |
Add professional docstrings to my codebase | import glob
import logging
import os
import os.path as osp
import warnings
from contextlib import contextmanager
from typing import Any, Callable, Dict, List, Optional, Union
import psutil
import torch
from torch_geometric.data import HeteroData
def get_numa_nodes_cores() -> Dict[str, Any]:
numa_node_paths = gl... | --- +++ @@ -13,6 +13,18 @@
def get_numa_nodes_cores() -> Dict[str, Any]:
+ """Parses numa nodes information into a dictionary.
+
+ ..code-block::
+
+ {<node_id>: [(<core_id>, [<sibling_thread_id_0>, <sibling_thread_id_1>
+ ...]), ...], ...}
+
+ # For example:
+ {0: [(0, [0, 4]), (1... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/loader/mixin.py |
Help me document legacy Python code | import torch
import torch_geometric.graphgym.register as register
from torch_geometric.graphgym.config import cfg
from torch_geometric.graphgym.models.layer import MLP, new_layer_config
from torch_geometric.graphgym.register import register_head
@register_head('node')
class GNNNodeHead(torch.nn.Module):
def __in... | --- +++ @@ -8,6 +8,12 @@
@register_head('node')
class GNNNodeHead(torch.nn.Module):
+ r"""A GNN prediction head for node-level prediction tasks.
+
+ Args:
+ dim_in (int): The input feature dimension.
+ dim_out (int): The output feature dimension.
+ """
def __init__(self, dim_in: int, dim_... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/graphgym/models/head.py |
Generate docstrings for each module | from dataclasses import dataclass
from typing import Dict, List, Optional, Tuple, Union
import torch
from torch import Tensor
from torch_geometric.utils import cumsum, scatter
try:
import torchmetrics # noqa
WITH_TORCHMETRICS = True
BaseMetric = torchmetrics.Metric
except Exception:
WITH_TORCHMETRIC... | --- +++ @@ -36,6 +36,10 @@
@property
def pred_rel_mat(self) -> Tensor:
+ r"""Returns a matrix indicating the relevance of the `k`-th prediction.
+ If :obj:`edge_label_weight` is not given, relevance will be denoted as
+ binary.
+ """
if hasattr(self, '_pred_rel_mat'):
... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/metrics/link_pred.py |
Add docstrings for utility scripts | from typing import Any, Iterator, List, Optional, Tuple, Union
import torch
from torch import Tensor
from torch_geometric.data import Data, HeteroData
from torch_geometric.loader import LinkLoader, NodeLoader
from torch_geometric.loader.base import DataLoaderIterator
from torch_geometric.loader.utils import infer_fil... | --- +++ @@ -10,6 +10,27 @@
class ZipLoader(torch.utils.data.DataLoader):
+ r"""A loader that returns a tuple of data objects by sampling from multiple
+ :class:`NodeLoader` or :class:`LinkLoader` instances.
+
+ Args:
+ loaders (List[NodeLoader] or List[LinkLoader]): The loader instances.
+ fi... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/loader/zip_loader.py |
Turn comments into proper docstrings | from typing import Any, Callable, Dict, Union
act_dict: Dict[str, Any] = {}
node_encoder_dict: Dict[str, Any] = {}
edge_encoder_dict: Dict[str, Any] = {}
stage_dict: Dict[str, Any] = {}
head_dict: Dict[str, Any] = {}
layer_dict: Dict[str, Any] = {}
pooling_dict: Dict[str, Any] = {}
network_dict: Dict[str, Any] = {}
co... | --- +++ @@ -20,6 +20,15 @@
def register_base(mapping: Dict[str, Any], key: str,
module: Any = None) -> Union[None, Callable]:
+ r"""Base function for registering a module in GraphGym.
+
+ Args:
+ mapping (dict): :python:`Python` dictionary to register the module.
+ hosting a... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/graphgym/register.py |
Document this module using docstrings | import os
from dataclasses import dataclass
from enum import Enum, auto
from typing import (
Any,
Callable,
Dict,
Iterable,
Iterator,
List,
Optional,
Protocol,
Tuple,
Type,
Union,
no_type_check,
runtime_checkable,
)
import numpy as np
import torch
from torch import T... | --- +++ @@ -256,6 +256,7 @@
@dataclass
class RemoteGraphBackendLoader:
+ """Utility class to load triplets into a RAG Backend."""
path: str
datatype: RemoteDataType
graph_store_type: Type[ConvertableGraphStore]
@@ -294,6 +295,7 @@ embedding_method_kwargs: Optional[Dict[str, Any]] = None,
p... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/llm/utils/backend_utils.py |
Create Google-style docstrings for my code | from typing import Final, Optional, Tuple
import torch
from torch import Tensor
from torch_geometric.experimental import disable_dynamic_shapes
from torch_geometric.utils import scatter, segment, to_dense_batch
class Aggregation(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
s... | --- +++ @@ -8,6 +8,57 @@
class Aggregation(torch.nn.Module):
+ r"""An abstract base class for implementing custom aggregations.
+
+ Aggregation can be either performed via an :obj:`index` vector, which
+ defines the mapping from input elements to their location in the output:
+
+ |
+
+ .. image:: htt... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/aggr/base.py |
Create documentation for each function signature | from typing import Any, Callable, Iterator, List, Optional, Tuple, Union
import torch
from torch import Tensor
from torch_geometric.data import Data, FeatureStore, GraphStore, HeteroData
from torch_geometric.loader.base import DataLoaderIterator
from torch_geometric.loader.mixin import (
AffinityMixin,
LogMem... | --- +++ @@ -34,6 +34,99 @@ MultithreadingMixin,
LogMemoryMixin,
):
+ r"""A data loader that performs mini-batch sampling from link information,
+ using a generic :class:`~torch_geometric.sampler.BaseSampler`
+ implementation that defines a
+ :meth:`~torch_geometric.sampler.BaseSampler.samp... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/loader/link_loader.py |
Add detailed docstrings explaining each function | import math
from typing import Any, Callable, Dict, Optional, Union
import torch
from torch import Tensor
from torch.nn import Parameter
from torch_geometric.nn.conv import GCNConv, MessagePassing
from torch_geometric.nn.inits import zeros
from torch_geometric.nn.resolver import activation_resolver
from torch_geometr... | --- +++ @@ -12,6 +12,45 @@
class AntiSymmetricConv(torch.nn.Module):
+ r"""The anti-symmetric graph convolutional operator from the
+ `"Anti-Symmetric DGN: a stable architecture for Deep Graph Networks"
+ <https://openreview.net/forum?id=J3Y7cgZOOS>`_ paper.
+
+ .. math::
+ \mathbf{x}^{\prime}_i ... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/conv/antisymmetric_conv.py |
Generate docstrings for each module | from typing import Any, Callable, Iterator, List, Optional, Tuple, Union
import torch
from torch import Tensor
from torch_geometric.data import Data, FeatureStore, GraphStore, HeteroData
from torch_geometric.loader.base import DataLoaderIterator
from torch_geometric.loader.mixin import (
AffinityMixin,
LogMem... | --- +++ @@ -33,6 +33,60 @@ MultithreadingMixin,
LogMemoryMixin,
):
+ r"""A data loader that performs mini-batch sampling from node information,
+ using a generic :class:`~torch_geometric.sampler.BaseSampler`
+ implementation that defines a
+ :meth:`~torch_geometric.sampler.BaseSampler.samp... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/loader/node_loader.py |
Add docstrings to improve readability | from typing import Optional
import torch
from torch import Tensor
from torch.nn import Parameter
from torch_geometric import EdgeIndex
from torch_geometric.nn.conv.cugraph import CuGraphModule
from torch_geometric.nn.conv.cugraph.base import LEGACY_MODE
from torch_geometric.nn.inits import glorot, zeros
try:
if ... | --- +++ @@ -21,6 +21,17 @@
class CuGraphRGCNConv(CuGraphModule): # pragma: no cover
+ r"""The relational graph convolutional operator from the `"Modeling
+ Relational Data with Graph Convolutional Networks"
+ <https://arxiv.org/abs/1703.06103>`_ paper.
+
+ :class:`CuGraphRGCNConv` is an optimized versi... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/conv/cugraph/rgcn_conv.py |
Add clean documentation to messy code | import math
from typing import Optional
import torch
from torch import Tensor
from torch.nn import Parameter
from torch_geometric.nn.aggr import Aggregation
from torch_geometric.utils import softmax
class SumAggregation(Aggregation):
def forward(self, x: Tensor, index: Optional[Tensor] = None,
p... | --- +++ @@ -10,6 +10,12 @@
class SumAggregation(Aggregation):
+ r"""An aggregation operator that sums up features across a set of elements.
+
+ .. math::
+ \mathrm{sum}(\mathcal{X}) = \sum_{\mathbf{x}_i \in \mathcal{X}}
+ \mathbf{x}_i.
+ """
def forward(self, x: Tensor, index: Optional[T... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/aggr/basic.py |
Generate docstrings with examples | from typing import Callable, Optional, Union
import torch
from torch import Tensor
import torch_geometric.typing
from torch_geometric.nn.conv import MessagePassing
from torch_geometric.nn.inits import reset
from torch_geometric.typing import Adj, OptTensor, PairOptTensor, PairTensor
if torch_geometric.typing.WITH_TO... | --- +++ @@ -15,6 +15,36 @@
class EdgeConv(MessagePassing):
+ r"""The edge convolutional operator from the `"Dynamic Graph CNN for
+ Learning on Point Clouds" <https://arxiv.org/abs/1801.07829>`_ paper.
+
+ .. math::
+ \mathbf{x}^{\prime}_i = \sum_{j \in \mathcal{N}(i)}
+ h_{\mathbf{\Theta}}(\... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/conv/edge_conv.py |
Write docstrings for backend logic | import copy
import torch
from torch import Tensor
from torch_geometric.nn.conv import MessagePassing
class DirGNNConv(torch.nn.Module):
def __init__(
self,
conv: MessagePassing,
alpha: float = 0.5,
root_weight: bool = True,
):
super().__init__()
self.alpha = ... | --- +++ @@ -7,6 +7,22 @@
class DirGNNConv(torch.nn.Module):
+ r"""A generic wrapper for computing graph convolution on directed
+ graphs as described in the `"Edge Directionality Improves Learning on
+ Heterophilic Graphs" <https://arxiv.org/abs/2305.10498>`_ paper.
+ :class:`DirGNNConv` will pass messa... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/conv/dir_gnn_conv.py |
Add concise docstrings to each method | import math
from typing import Optional
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.conv.gcn_conv import gcn_norm
from torch_geometric.nn.inits import kaiming_uniform, uniform
from torch... | --- +++ @@ -168,6 +168,64 @@
class DNAConv(MessagePassing):
+ r"""The dynamic neighborhood aggregation operator from the `"Just Jump:
+ Towards Dynamic Neighborhood Aggregation in Graph Neural Networks"
+ <https://arxiv.org/abs/1904.04849>`_ paper.
+
+ .. math::
+ \mathbf{x}_v^{(t)} = h_{\mathbf{... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/conv/dna_conv.py |
Fill in missing docstrings in my code | from typing import List, Optional, Union
import torch
from torch import Tensor
from torch_geometric.nn.aggr import Aggregation
from torch_geometric.utils import cumsum
class QuantileAggregation(Aggregation):
interpolations = {'linear', 'lower', 'higher', 'nearest', 'midpoint'}
def __init__(self, q: Union[f... | --- +++ @@ -8,6 +8,46 @@
class QuantileAggregation(Aggregation):
+ r"""An aggregation operator that returns the feature-wise :math:`q`-th
+ quantile of a set :math:`\mathcal{X}`.
+
+ That is, for every feature :math:`d`, it computes
+
+ .. math::
+ {\mathrm{Q}_q(\mathcal{X})}_d = \begin{cases}
+ ... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/aggr/quantile.py |
Add minimal docstrings for each function | from typing import Optional
import torch
from torch import Tensor
from torch.nn import LayerNorm, Linear, MultiheadAttention, Parameter
class MultiheadAttentionBlock(torch.nn.Module):
def __init__(self, channels: int, heads: int = 1, layer_norm: bool = True,
dropout: float = 0.0, device: Optiona... | --- +++ @@ -6,6 +6,29 @@
class MultiheadAttentionBlock(torch.nn.Module):
+ r"""The Multihead Attention Block (MAB) from the `"Set Transformer: A
+ Framework for Attention-based Permutation-Invariant Neural Networks"
+ <https://arxiv.org/abs/1810.00825>`_ paper.
+
+ .. math::
+
+ \mathrm{MAB}(\mat... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/aggr/utils.py |
Add detailed docstrings explaining each function | 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... | --- +++ @@ -32,6 +32,104 @@
class GATv2Conv(MessagePassing):
+ r"""The GATv2 operator from the `"How Attentive are Graph Attention
+ Networks?" <https://arxiv.org/abs/2105.14491>`_ paper, which fixes the
+ static attention problem of the standard
+ :class:`~torch_geometric.conv.GATConv` layer.
+ Sinc... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/conv/gatv2_conv.py |
Write docstrings for this repository | import inspect
from typing import Any, Dict, Optional
import torch
import torch.nn.functional as F
from torch import Tensor
from torch.nn import Dropout, Linear, Sequential
from torch_geometric.nn.attention import PerformerAttention
from torch_geometric.nn.conv import MessagePassing
from torch_geometric.nn.inits impo... | --- +++ @@ -18,6 +18,47 @@
class GPSConv(torch.nn.Module):
+ r"""The general, powerful, scalable (GPS) graph transformer layer from the
+ `"Recipe for a General, Powerful, Scalable Graph Transformer"
+ <https://arxiv.org/abs/2205.12454>`_ paper.
+
+ The GPS layer is based on a 3-part recipe:
+
+ 1. I... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/conv/gps_conv.py |
Create documentation for each function signature | import typing
from typing import Optional, Tuple, Union
import torch.nn.functional as F
from torch import Tensor
from torch_geometric.nn.conv import MessagePassing
from torch_geometric.nn.conv.gcn_conv import gcn_norm
from torch_geometric.nn.dense.linear import Linear
from torch_geometric.typing import PairTensor # ... | --- +++ @@ -25,6 +25,57 @@
class FAConv(MessagePassing):
+ r"""The Frequency Adaptive Graph Convolution operator from the
+ `"Beyond Low-Frequency Information in Graph Convolutional Networks"
+ <https://arxiv.org/abs/2101.00797>`_ paper.
+
+ .. math::
+ \mathbf{x}^{\prime}_i= \epsilon \cdot \math... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/conv/fa_conv.py |
Write clean docstrings for readability | from typing import Dict, List, Optional, Tuple, Union
import torch
import torch.nn.functional as F
from torch import Tensor, nn
from torch_geometric.nn.conv import MessagePassing
from torch_geometric.nn.dense import Linear
from torch_geometric.nn.inits import glorot, reset
from torch_geometric.typing import PairTenso... | --- +++ @@ -32,6 +32,36 @@
class HANConv(MessagePassing):
+ r"""The Heterogenous Graph Attention Operator from the
+ `"Heterogenous Graph Attention Network"
+ <https://arxiv.org/abs/1903.07293>`_ paper.
+
+ .. note::
+
+ For an example of using HANConv, see `examples/hetero/han_imdb.py
+ <... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/conv/han_conv.py |
Create Google-style docstrings for my code | from typing import Optional
import torch
import torch.nn.functional as F
from torch import Tensor
from torch.nn import Parameter
from torch_geometric.experimental import disable_dynamic_shapes
from torch_geometric.nn.conv import MessagePassing
from torch_geometric.nn.dense.linear import Linear
from torch_geometric.nn... | --- +++ @@ -13,6 +13,67 @@
class HypergraphConv(MessagePassing):
+ r"""The hypergraph convolutional operator from the `"Hypergraph Convolution
+ and Hypergraph Attention" <https://arxiv.org/abs/1901.08150>`_ paper.
+
+ .. math::
+ \mathbf{X}^{\prime} = \mathbf{D}^{-1} \mathbf{H} \mathbf{W}
+ ... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/conv/hypergraph_conv.py |
Document all public functions with docstrings | import warnings
from typing import Dict, List, Optional
import torch
from torch import Tensor
from torch_geometric.nn.conv import MessagePassing
from torch_geometric.nn.module_dict import ModuleDict
from torch_geometric.typing import EdgeType, NodeType
from torch_geometric.utils.hetero import check_add_self_loops
d... | --- +++ @@ -27,6 +27,39 @@
class HeteroConv(torch.nn.Module):
+ r"""A generic wrapper for computing graph convolution on heterogeneous
+ graphs.
+ This layer will pass messages from source nodes to target nodes based on
+ the bipartite GNN layer given for a specific edge type.
+ If multiple relations... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/conv/hetero_conv.py |
Generate NumPy-style docstrings | import os.path as osp
import warnings
from abc import abstractmethod
from inspect import Parameter
from typing import (
Any,
Callable,
Dict,
Final,
List,
Optional,
OrderedDict,
Set,
Tuple,
Union,
)
import torch
from torch import Tensor
from torch.utils.hooks import RemovableHand... | --- +++ @@ -37,6 +37,66 @@
class MessagePassing(torch.nn.Module):
+ r"""Base class for creating message passing layers.
+
+ Message passing layers follow the form
+
+ .. math::
+ \mathbf{x}_i^{\prime} = \gamma_{\mathbf{\Theta}} \left( \mathbf{x}_i,
+ \bigoplus_{j \in \mathcal{N}(i)} \, \phi_{... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/conv/message_passing.py |
Write docstrings for utility functions | # The below is to suppress the warning on torch.nn.conv.MeshCNNConv::update
# pyright: reportIncompatibleMethodOverride=false
import warnings
from typing import Optional
import torch
from torch.nn import Linear, Module, ModuleList
from torch_geometric.nn.conv import MessagePassing
from torch_geometric.typing import T... | --- +++ @@ -11,6 +11,264 @@
class MeshCNNConv(MessagePassing):
+ r"""The convolutional layer introduced by the paper
+ `"MeshCNN: A Network With An Edge" <https://arxiv.org/abs/1809.05910>`_.
+
+ Recall that, given a set of categories :math:`C`,
+ MeshCNN is a function that takes as its input
+ a tri... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/conv/meshcnn_conv.py |
Replace inline comments with docstrings | import math
from typing import Dict, List, Optional, Tuple, Union
import torch
from torch import Tensor
from torch.nn import Parameter
from torch_geometric.nn.conv import MessagePassing
from torch_geometric.nn.dense import HeteroDictLinear, HeteroLinear
from torch_geometric.nn.inits import ones
from torch_geometric.n... | --- +++ @@ -15,6 +15,31 @@
class HGTConv(MessagePassing):
+ r"""The Heterogeneous Graph Transformer (HGT) operator from the
+ `"Heterogeneous Graph Transformer" <https://arxiv.org/abs/2003.01332>`_
+ paper.
+
+ .. note::
+
+ For an example of using HGT, see `examples/hetero/hgt_dblp.py
+ <... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/conv/hgt_conv.py |
Help me write clear docstrings | from typing import Optional, Tuple, Union
import torch
from torch import Tensor
from torch.nn import Parameter
import torch_geometric.backend
import torch_geometric.typing
from torch_geometric import is_compiling
from torch_geometric.index import index2ptr
from torch_geometric.nn.conv import MessagePassing
from torch... | --- +++ @@ -27,6 +27,68 @@
class RGCNConv(MessagePassing):
+ r"""The relational graph convolutional operator from the `"Modeling
+ Relational Data with Graph Convolutional Networks"
+ <https://arxiv.org/abs/1703.06103>`_ paper.
+
+ .. math::
+ \mathbf{x}^{\prime}_i = \mathbf{\Theta}_{\textrm{root... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/conv/rgcn_conv.py |
Document this code for team use | from typing import Any, Callable, Dict, List, Optional, Union
import torch
from torch import Tensor
from torch.nn import ModuleList, Sequential
from torch.utils.data import DataLoader
from torch_geometric.nn.aggr import DegreeScalerAggregation
from torch_geometric.nn.conv import MessagePassing
from torch_geometric.nn... | --- +++ @@ -15,6 +15,79 @@
class PNAConv(MessagePassing):
+ r"""The Principal Neighbourhood Aggregation graph convolution operator
+ from the `"Principal Neighbourhood Aggregation for Graph Nets"
+ <https://arxiv.org/abs/2004.05718>`_ paper.
+
+ .. math::
+ \mathbf{x}_i^{\prime} = \gamma_{\mathbf... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/conv/pna_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 Parameter, ReLU
from torch_geometric.nn.conv import MessagePassing
from torch_geometric.nn.dense.linear import Linear
from torch_geometric.nn.inits import glorot, ones, zeros
from torch_geometric.typ... | --- +++ @@ -14,6 +14,160 @@
class RGATConv(MessagePassing):
+ r"""The relational graph attentional operator from the `"Relational Graph
+ Attention Networks" <https://arxiv.org/abs/1904.05811>`_ paper.
+
+ Here, attention logits :math:`\mathbf{a}^{(r)}_{i,j}` are computed for each
+ relation type :math:... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/conv/rgat_conv.py |
Write docstrings describing functionality | import math
from typing import Optional
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 torch_geometric.typ... | --- +++ @@ -23,6 +23,105 @@
class SuperGATConv(MessagePassing):
+ r"""The self-supervised graph attentional operator from the `"How to Find
+ Your Friendly Neighborhood: Graph Attention Design with Self-Supervision"
+ <https://openreview.net/forum?id=Wi5KUNlqWty>`_ paper.
+
+ .. math::
+
+ \mathb... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/conv/supergat_conv.py |
Write docstrings for utility functions | from typing import Optional
import torch
from torch import Tensor
from torch_geometric.typing import Adj
from torch_geometric.utils import (
degree,
is_sparse,
scatter,
sort_edge_index,
to_edge_index,
)
class WLConv(torch.nn.Module):
def __init__(self):
super().__init__()
sel... | --- +++ @@ -14,15 +14,34 @@
class WLConv(torch.nn.Module):
+ r"""The Weisfeiler Lehman (WL) operator from the `"A Reduction of a Graph
+ to a Canonical Form and an Algebra Arising During this Reduction"
+ <https://www.iti.zcu.cz/wl2018/pdf/wl_paper_translation.pdf>`_ paper.
+
+ :class:`WLConv` iterative... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/conv/wl_conv.py |
Generate docstrings for script automation | from math import ceil
from typing import Optional
import torch
from torch import Tensor
from torch.nn import ELU
from torch.nn import BatchNorm1d as BN
from torch.nn import Conv1d
from torch.nn import Linear as L
from torch.nn import Sequential as S
import torch_geometric.typing
from torch_geometric.nn import Reshape... | --- +++ @@ -20,6 +20,53 @@
class XConv(torch.nn.Module):
+ r"""The convolutional operator on :math:`\mathcal{X}`-transformed points
+ from the `"PointCNN: Convolution On X-Transformed Points"
+ <https://arxiv.org/abs/1801.07791>`_ paper.
+
+ .. math::
+ \mathbf{x}^{\prime}_i = \mathrm{Conv}\left(... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/conv/x_conv.py |
Generate docstrings for this script | import math
import typing
from typing import Optional, Tuple, Union
import torch
import torch.nn.functional as F
from torch import Tensor
from torch_geometric.nn.conv import MessagePassing
from torch_geometric.nn.dense.linear import Linear
from torch_geometric.typing import (
Adj,
NoneType,
OptTensor,
... | --- +++ @@ -24,6 +24,77 @@
class TransformerConv(MessagePassing):
+ r"""The graph transformer operator from the `"Masked Label Prediction:
+ Unified Message Passing Model for Semi-Supervised Classification"
+ <https://arxiv.org/abs/2009.03509>`_ paper.
+
+ .. math::
+ \mathbf{x}^{\prime}_i = \mat... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/conv/transformer_conv.py |
Add detailed documentation for each class | from typing import Any, Optional
import torch
from torch import Tensor
from torch_geometric import EdgeIndex
try: # pragma: no cover
LEGACY_MODE = False
from pylibcugraphops.pytorch import CSC, HeteroCSC
HAS_PYLIBCUGRAPHOPS = True
except ImportError:
HAS_PYLIBCUGRAPHOPS = False
try: # pragma: n... | --- +++ @@ -24,6 +24,9 @@
class CuGraphModule(torch.nn.Module): # pragma: no cover
+ r"""An abstract base class for implementing :obj:`cugraph`-based message
+ passing layers.
+ """
def __init__(self):
super().__init__()
@@ -32,12 +35,23 @@ f"'pylibcug... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/conv/cugraph/base.py |
Add documentation for all methods | import math
from typing import Callable, Optional
import torch
from torch import Tensor
def _orthogonal_matrix(dim: int) -> Tensor:
# Random matrix from normal distribution
mat = torch.randn((dim, dim))
# QR decomposition to two orthogonal matrices
q, _ = torch.linalg.qr(mat.cpu(), mode='reduced')
... | --- +++ @@ -6,6 +6,7 @@
def _orthogonal_matrix(dim: int) -> Tensor:
+ r"""Get an orthogonal matrix by applying QR decomposition."""
# Random matrix from normal distribution
mat = torch.randn((dim, dim))
# QR decomposition to two orthogonal matrices
@@ -14,6 +15,9 @@
def orthogonal_matrix(num_r... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/attention/performer.py |
Write beginner-friendly docstrings | from typing import Optional
import torch
from torch import Tensor
from torch.nn import Linear
class DenseGraphConv(torch.nn.Module):
def __init__(
self,
in_channels: int,
out_channels: int,
aggr: str = 'add',
bias: bool = True,
):
assert aggr in ['add', 'mean',... | --- +++ @@ -6,6 +6,7 @@
class DenseGraphConv(torch.nn.Module):
+ r"""See :class:`torch_geometric.nn.conv.GraphConv`."""
def __init__(
self,
in_channels: int,
@@ -26,11 +27,27 @@ self.reset_parameters()
def reset_parameters(self):
+ r"""Resets all learnable parameters ... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/dense/dense_graph_conv.py |
Write docstrings describing each step | import math
from typing import Optional
import torch
from torch import Tensor
__all__ = classes = [
'PositionalEncoding',
'TemporalEncoding',
]
class PositionalEncoding(torch.nn.Module):
def __init__(
self,
out_channels: int,
base_freq: float = 1e-4,
granularity: float = ... | --- +++ @@ -11,6 +11,27 @@
class PositionalEncoding(torch.nn.Module):
+ r"""The positional encoding scheme from the `"Attention Is All You Need"
+ <https://arxiv.org/abs/1706.03762>`_ paper.
+
+ .. math::
+
+ PE(x)_{2 \cdot i} &= \sin(x / 10000^{2 \cdot i / d})
+
+ PE(x)_{2 \cdot i + 1} &= \c... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/encoding.py |
Create docstrings for reusable components | import torch
import torch.nn.functional as F
from torch import Tensor
from torch.nn import Linear
from torch_geometric.typing import OptTensor
class DenseSAGEConv(torch.nn.Module):
def __init__(
self,
in_channels: int,
out_channels: int,
normalize: bool = False,
bias: bool... | --- +++ @@ -7,6 +7,15 @@
class DenseSAGEConv(torch.nn.Module):
+ r"""See :class:`torch_geometric.nn.conv.SAGEConv`.
+
+ .. note::
+
+ :class:`~torch_geometric.nn.dense.DenseSAGEConv` expects to work on
+ binary adjacency matrices.
+ If you want to make use of weighted dense adjacency matr... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/dense/dense_sage_conv.py |
Turn comments into proper docstrings | from typing import List, Optional, Tuple, Union
import torch
import torch.nn.functional as F
from torch import Tensor
from torch_geometric.nn.dense.mincut_pool import _rank3_trace
EPS = 1e-15
class DMoNPooling(torch.nn.Module):
def __init__(self, channels: Union[int, List[int]], k: int,
dropou... | --- +++ @@ -10,6 +10,53 @@
class DMoNPooling(torch.nn.Module):
+ r"""The spectral modularity pooling operator from the `"Graph Clustering
+ with Graph Neural Networks" <https://arxiv.org/abs/2006.16904>`_ paper.
+
+ .. math::
+ \mathbf{X}^{\prime} &= {\mathrm{softmax}(\mathbf{S})}^{\top} \cdot
+ ... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/dense/dmon_pool.py |
Add missing documentation to my Python functions | from typing import Optional
import torch
from torch import Tensor
class SGFormerAttention(torch.nn.Module):
def __init__(
self,
channels: int,
heads: int = 1,
head_channels: int = 64,
qkv_bias: bool = False,
) -> None:
super().__init__()
assert channels... | --- +++ @@ -5,6 +5,20 @@
class SGFormerAttention(torch.nn.Module):
+ r"""The simple global attention mechanism from the
+ `"SGFormer: Simplifying and Empowering Transformers for
+ Large-Graph Representations"
+ <https://arxiv.org/abs/2306.10759>`_ paper.
+
+ Args:
+ channels (int): Size of eac... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/attention/sgformer.py |
Add docstrings following best practices | import math
import os
import time
from typing import Any, Dict, Optional, Tuple, Union
import torch
import torch.nn.functional as F
from torch import Tensor
from torch.nn.parameter import Parameter
import torch_geometric.backend
import torch_geometric.typing
from torch_geometric import is_compiling
from torch_geometr... | --- +++ @@ -57,6 +57,34 @@
class Linear(torch.nn.Module):
+ r"""Applies a linear transformation to the incoming data.
+
+ .. math::
+ \mathbf{x}^{\prime} = \mathbf{x} \mathbf{W}^{\top} + \mathbf{b}
+
+ In contrast to :class:`torch.nn.Linear`, it supports lazy initialization
+ and customizable wei... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/dense/linear.py |
Add docstrings explaining edge cases | from typing import Optional
import torch
import torch.nn.functional as F
from torch import Tensor
from torch.nn import Parameter
from torch_geometric.nn.dense.linear import Linear
from torch_geometric.nn.inits import glorot, zeros
class DenseGATConv(torch.nn.Module):
def __init__(
self,
in_chann... | --- +++ @@ -10,6 +10,7 @@
class DenseGATConv(torch.nn.Module):
+ r"""See :class:`torch_geometric.nn.conv.GATConv`."""
def __init__(
self,
in_channels: int,
@@ -54,6 +55,24 @@
def forward(self, x: Tensor, adj: Tensor, mask: Optional[Tensor] = None,
add_loop: bool = Tr... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/dense/dense_gat_conv.py |
Generate docstrings for exported functions | from typing import Optional
import torch
import torch.nn.functional as F
from torch import Tensor
class PolynormerAttention(torch.nn.Module):
def __init__(
self,
channels: int,
heads: int,
head_channels: int = 64,
beta: float = 0.9,
qkv_bias: bool = False,
... | --- +++ @@ -6,6 +6,24 @@
class PolynormerAttention(torch.nn.Module):
+ r"""The polynomial-expressive attention mechanism from the
+ `"Polynormer: Polynomial-Expressive Graph Transformer in Linear Time"
+ <https://arxiv.org/abs/2403.01232>`_ paper.
+
+ Args:
+ channels (int): Size of each input sa... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/attention/polynormer.py |
Add standardized docstrings across the file | # See HuggingFace `transformers/optimization.py`.
import functools
import math
from torch.optim import Optimizer
from torch.optim.lr_scheduler import LambdaLR
class ConstantWithWarmupLR(LambdaLR):
def __init__(
self,
optimizer: Optimizer,
num_warmup_steps: int,
last_epoch: int = -... | --- +++ @@ -7,6 +7,16 @@
class ConstantWithWarmupLR(LambdaLR):
+ r"""Creates a LR scheduler with a constant learning rate preceded by a
+ warmup period during which the learning rate increases linearly between
+ :obj:`0` and the initial LR set in the optimizer.
+
+ Args:
+ optimizer (Optimizer): ... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/nn/lr_scheduler.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.