torch_geometric.graphgym

工作流和注册模块

load_ckpt

加载给定时期的模型检查点。

save_ckpt

在给定的时期保存模型检查点。

remove_ckpt

移除给定时期的模型检查点。

clean_ckpt

移除除最后一个模型检查点之外的所有内容。

parse_args

解析命令行参数。

cfg

set_cfg

此函数设置默认配置值。

load_cfg

从文件系统和命令行加载配置。

dump_cfg

将配置转储到在cfg.out_dir中指定的输出目录。

set_run_dir

为每个随机种子实验运行创建目录。

set_out_dir

创建完整实验运行的目录。

get_fname

从文件名路径中提取文件名。

init_weights

执行权重初始化。

create_loader

创建数据加载器对象。

set_printing

设置打印选项。

create_logger

为实验创建日志记录器。

compute_loss

计算损失和预测分数。

create_model

为图机器学习创建模型。

create_optimizer

创建一个配置驱动的优化器。

create_scheduler

创建一个配置驱动的学习率调度器。

train

使用PyTorch Lightning训练GraphGym模型。

register_base

用于在GraphGym中注册模块的基础函数。

register_act

在GraphGym中注册一个激活函数。

register_node_encoder

在GraphGym中注册一个节点特征编码器。

register_edge_encoder

在GraphGym中注册一个边缘特征编码器。

register_stage

在GraphGym中注册一个定制的GNN阶段。

register_head

在GraphGym中注册一个GNN预测头。

register_layer

在GraphGym中注册一个GNN层。

register_pooling

在GraphGym中注册一个GNN全局池化/读出层。

register_network

在GraphGym中注册一个GNN模型。

register_config

在GraphGym中注册一个配置组。

register_dataset

在GraphGym中注册一个数据集。

register_loader

在GraphGym中注册一个数据加载器。

register_optimizer

在GraphGym中注册一个优化器。

register_scheduler

在GraphGym中注册一个学习率调度器。

register_loss

在GraphGym中注册一个损失函数。

register_train

在GraphGym中注册一个训练函数。

register_metric

在GraphGym中注册一个度量函数。

load_ckpt(model: Module, optimizer: Optional[Optimizer] = None, scheduler: Optional[Any] = None, epoch: int = -1) int[source]

加载给定时期的模型检查点。

Return type:

int

save_ckpt(model: Module, optimizer: Optional[Optimizer] = None, scheduler: Optional[Any] = None, epoch: int = 0)[source]

在给定的时期保存模型检查点。

remove_ckpt(epoch: int = -1)[source]

移除给定时期的模型检查点。

clean_ckpt()[source]

移除除最后一个模型检查点之外的所有内容。

parse_args() Namespace[source]

解析命令行参数。

Return type:

Namespace

set_cfg(cfg)[source]

此函数设置默认配置值。

  1. 请注意,对于实验,只会使用部分参数 未使用的剩余参数不会影响任何内容。 因此,请随意在graphgym.contrib.config中注册任何参数

  2. 我们支持最多两级配置,例如cfg.dataset.name

Returns:

实验使用的配置。

load_cfg(cfg, args)[source]

从文件系统和命令行加载配置。

Parameters:
  • cfg (CfgNode) – 配置节点

  • args (ArgumentParser) – 命令参数解析器

dump_cfg(cfg)[source]

将配置转储到在 cfg.out_dir中指定的输出目录。

Parameters:

cfg (CfgNode) – 配置节点

set_run_dir(out_dir)[source]

为每个随机种子实验运行创建目录。

Parameters:

out_dir (str) – 输出目录,在 cfg.out_dir 中指定

set_out_dir(out_dir, fname)[source]

创建完整实验运行的目录。

Parameters:
  • out_dir (str) – 输出目录,在 cfg.out_dir 中指定

  • fname (str) – yaml格式配置文件的文件名

get_fname(fname)[source]

从文件名路径中提取文件名。

Parameters:

fname (str) – yaml格式配置文件的文件名

init_weights(m)[source]

执行权重初始化。

Parameters:

m (nn.Module) – PyTorch 模块

create_loader()[source]

创建数据加载器对象。

返回:PyTorch 数据加载器列表

set_printing()[source]

设置打印选项。

create_logger()[source]

为实验创建日志记录器。

compute_loss(pred, true)[source]

计算损失和预测分数。

Parameters:
  • pred (torch.tensor) – 未归一化的预测

  • true (torch.tensor) – 真实标签

返回:损失,归一化预测分数

create_model(to_device=True, dim_in=None, dim_out=None) GraphGymModule[source]

为图机器学习创建模型。

Parameters:
  • to_device (bool, optional) – 是否将模型转移到指定的设备。(默认: True)

  • dim_in (int, 可选) – 模型的输入维度

  • dim_out (int, optional) – 模型的输出维度

Return type:

GraphGymModule

create_optimizer(params: Iterator[Parameter], cfg: Any) Any[source]

创建一个配置驱动的优化器。

Return type:

Any

create_scheduler(optimizer: Optimizer, cfg: Any) Any[source]

创建一个配置驱动的学习率调度器。

Return type:

Any

train(model: GraphGymModule, datamodule: GraphGymDataModule, logger: bool = True, trainer_config: Optional[Dict[str, Any]] = None)[source]

使用PyTorch Lightning训练GraphGym模型。

Parameters:
  • model (GraphGymModule) – GraphGym模型。

  • datamodule (GraphGymDataModule) – GraphGym 数据模块。

  • logger (bool, optional) – 是否在训练期间启用日志记录。 (默认: True)

  • trainer_config (dict, optional) – 额外的训练器配置。

register_base(mapping: Dict[str, Any], key: str, module: Optional[Any] = None) Union[None, Callable][source]

用于在GraphGym中注册模块的基础函数。

Parameters:
  • mapping (dict) – 字典用于注册模块。 托管所有已注册的模块

  • key (str) – 模块的名称。

  • 模块 (任意, 可选) – 该模块。如果设置为 None,将返回一个装饰器来注册一个模块。

Return type:

Optional[Callable]

register_act(key: str, module: Optional[Any] = None)[source]

在GraphGym中注册一个激活函数。

register_node_encoder(key: str, module: Optional[Any] = None)[source]

在GraphGym中注册一个节点特征编码器。

register_edge_encoder(key: str, module: Optional[Any] = None)[source]

在GraphGym中注册一个边缘特征编码器。

register_stage(key: str, module: Optional[Any] = None)[source]

在GraphGym中注册一个定制的GNN阶段。

register_head(key: str, module: Optional[Any] = None)[source]

在GraphGym中注册一个GNN预测头。

register_layer(key: str, module: Optional[Any] = None)[source]

在GraphGym中注册一个GNN层。

register_pooling(key: str, module: Optional[Any] = None)[source]

在GraphGym中注册一个GNN全局池化/读出层。

register_network(key: str, module: Optional[Any] = None)[source]

在GraphGym中注册一个GNN模型。

register_config(key: str, module: Optional[Any] = None)[source]

在GraphGym中注册一个配置组。

register_dataset(key: str, module: Optional[Any] = None)[source]

在GraphGym中注册一个数据集。

register_loader(key: str, module: Optional[Any] = None)[source]

在GraphGym中注册一个数据加载器。

register_optimizer(key: str, module: Optional[Any] = None)[source]

在GraphGym中注册一个优化器。

register_scheduler(key: str, module: Optional[Any] = None)[source]

在GraphGym中注册一个学习率调度器。

register_loss(key: str, module: Optional[Any] = None)[source]

在GraphGym中注册一个损失函数。

register_train(key: str, module: Optional[Any] = None)[source]

在GraphGym中注册一个训练函数。

register_metric(key: str, module: Optional[Any] = None)[source]

在GraphGym中注册一个度量函数。

模型模块

IntegerFeatureEncoder

提供整数节点特征的编码器。

AtomEncoder

OGB分子数据集中使用的原子编码器。

BondEncoder

OGB分子数据集中使用的键编码器。

GNNLayer

创建一个GNN层,给定指定的输入和输出维度以及cfg中的基础配置。

GNNPreMP

在消息传递之前创建一个NN层,给定指定的输入和输出维度以及cfg中的基础配置。

GNNStackStage

堆叠多个GNN层。

FeatureEncoder

根据指定的输入维度和cfg中的基础配置,对节点和边的特征进行编码。

GNN

一个通用的图神经网络(GNN)模型。

GNNNodeHead

用于节点级预测任务的GNN预测头。

GNNEdgeHead

用于边级别/链接级别预测任务的GNN预测头。

GNNGraphHead

用于图级预测任务的GNN预测头。

GeneralLayer

层的通用包装器。

GeneralMultiLayer

一个用于堆叠多个神经网络层的通用包装类。

Linear

一个基本的线性层。

BatchNorm1dNode

一个用于节点级特征的批量归一化层。

BatchNorm1dEdge

用于边缘级别特征的批量归一化层。

MLP

一个基本的MLP模型。

GCNConv

一个图卷积网络(GCN)层。

SAGEConv

一个GraphSAGE层。

GATConv

图注意力网络(GAT)层。

GINConv

图同构网络(GIN)层。

SplineConv

一个SplineCNN层。

GeneralConv

一个通用的GNN层。

GeneralEdgeConv

一个支持边特征的通用GNN层。

GeneralSampleEdgeConv

一个支持边缘特征和边缘采样的通用GNN层。

global_add_pool

通过跨节点维度添加节点特征,返回批处理级别的图级输出。

global_mean_pool

通过平均节点维度上的节点特征,返回批次级别的图级输出。

global_max_pool

通过跨节点维度的通道方向最大值返回批次级别的图级输出。

class IntegerFeatureEncoder(emb_dim: int, num_classes: int)[source]

提供整数节点特征的编码器。

Parameters:
  • emb_dim (int) – 输出的嵌入维度。

  • num_classes (int) – 类别/整数的数量。

示例

>>> encoder = IntegerFeatureEncoder(emb_dim=16, num_classes=10)
>>> batch = torch.randint(0, 10, (10, 2))
>>> encoder(batch).size()
torch.Size([10, 16])
class AtomEncoder(emb_dim, *args, **kwargs)[source]

OGB分子数据集中使用的原子编码器。

Parameters:

emb_dim (int) – 输出的嵌入维度。

示例

>>> encoder = AtomEncoder(emb_dim=16)
>>> batch = torch.randint(0, 10, (10, 3))
>>> encoder(batch).size()
torch.Size([10, 16])
class BondEncoder(emb_dim: int)[source]

OGB分子数据集中使用的键编码器。

Parameters:

emb_dim (int) – 输出的嵌入维度。

示例

>>> encoder = BondEncoder(emb_dim=16)
>>> batch = torch.randint(0, 10, (10, 3))
>>> encoder(batch).size()
torch.Size([10, 16])
GNNLayer(dim_in: int, dim_out: int, has_act: bool = True) GeneralLayer[source]

创建一个GNN层,给定指定的输入和输出维度以及cfg中的基础配置。

Parameters:
  • dim_in (int) – 输入维度

  • dim_out (int) – 输出维度。

  • has_act (bool, optional) – 是否在层之后应用激活函数。(默认: True)

Return type:

GeneralLayer

GNNPreMP(dim_in: int, dim_out: int, num_layers: int) GeneralMultiLayer[source]

创建一个在消息传递之前使用的NN层,给定指定的输入和输出维度以及cfg中的基础配置。

Parameters:
  • dim_in (int) – 输入维度

  • dim_out (int) – 输出维度。

  • num_layers (int) – The number of layers.

Return type:

GeneralMultiLayer

class GNNStackStage(dim_in, dim_out, num_layers)[source]

堆叠多个GNN层。

Parameters:
  • dim_in (int) – 输入维度

  • dim_out (int) – 输出维度。

  • num_layers (int) – The number of layers.

class FeatureEncoder(dim_in: int)[source]

对节点和边特征进行编码,给定指定的输入维度和cfg中的基础配置。

Parameters:

dim_in (int) – 输入特征的维度。

class GNN(dim_in: int, dim_out: int, **kwargs)[source]

一个通用的图神经网络(GNN)模型。

GNN模型由三个主要组件组成:

  1. 一个编码器,用于将输入特征转换为固定大小的嵌入空间。

  2. 用于节点之间信息交换的处理或消息传递阶段。

  3. 一个头部用于生成最终的输出特征/预测。

每个组件的配置由cfg中的基础配置决定。

Parameters:
  • dim_in (int) – 输入特征的维度。

  • dim_out (int) – 输出特征的维度。

  • **kwargs (optional) – Additional keyword arguments.

class GNNNodeHead(dim_in: int, dim_out: int)[source]

用于节点级预测任务的GNN预测头。

Parameters:
  • dim_in (int) – 输入特征的维度。

  • dim_out (int) – 输出特征的维度。

class GNNEdgeHead(dim_in: int, dim_out: int)[source]

用于边级别/链接级别预测任务的GNN预测头。

Parameters:
  • dim_in (int) – 输入特征的维度。

  • dim_out (int) – 输出特征的维度。

class GNNGraphHead(dim_in: int, dim_out: int)[source]

用于图级预测任务的GNN预测头。 使用后消息传递层(由cfg.gnn.post_mp指定)通过MLP转换池化的图级嵌入。

Parameters:
  • dim_in (int) – The input feature dimension.

  • dim_out (int) – 输出特征的维度。

class GeneralLayer(name, layer_config: LayerConfig, **kwargs)[source]

层的通用包装器。

Parameters:
  • name (str) – 该层的注册名称。

  • layer_config (LayerConfig) – 层的配置。

  • **kwargs (optional) – Additional keyword arguments.

class GeneralMultiLayer(name, layer_config: LayerConfig, **kwargs)[source]

一个用于堆叠多个神经网络层的通用包装类。

Parameters:
  • name (str) – 该层的注册名称。

  • layer_config (LayerConfig) – 层的配置。

  • **kwargs (optional) – Additional keyword arguments.

class Linear(layer_config: LayerConfig, **kwargs)[source]

一个基本的线性层。

Parameters:
  • layer_config (LayerConfig) – 层的配置。

  • **kwargs (optional) – Additional keyword arguments.

class BatchNorm1dNode(layer_config: LayerConfig)[source]

一个用于节点级特征的批量归一化层。

Parameters:

layer_config (LayerConfig) – 层的配置。

class BatchNorm1dEdge(layer_config: LayerConfig)[source]

用于边缘级别特征的批量归一化层。

Parameters:

layer_config (LayerConfig) – 层的配置。

class MLP(layer_config: LayerConfig, **kwargs)[source]

一个基本的MLP模型。

Parameters:
  • layer_config (LayerConfig) – 层的配置。

  • **kwargs (optional) – Additional keyword arguments.

class GCNConv(layer_config: LayerConfig, **kwargs)[source]

一个图卷积网络(GCN)层。

class SAGEConv(layer_config: LayerConfig, **kwargs)[source]

一个GraphSAGE层。

class GATConv(layer_config: LayerConfig, **kwargs)[source]

图注意力网络(GAT)层。

class GINConv(layer_config: LayerConfig, **kwargs)[source]

图同构网络(GIN)层。

class SplineConv(layer_config: LayerConfig, **kwargs)[source]

一个SplineCNN层。

class GeneralConv(layer_config: LayerConfig, **kwargs)[source]

一个通用的GNN层。

class GeneralEdgeConv(layer_config: LayerConfig, **kwargs)[source]

一个支持边特征的通用GNN层。

class GeneralSampleEdgeConv(layer_config: LayerConfig, **kwargs)[source]

一个支持边缘特征和边缘采样的通用GNN层。

global_add_pool(x: Tensor, batch: Optional[Tensor], size: Optional[int] = None) Tensor[source]

通过跨节点维度添加节点特征,返回批处理级别的图级输出。

For a single graph \(\mathcal{G}_i\), its output is computed by

\[\mathbf{r}_i = \sum_{n=1}^{N_i} \mathbf{x}_n.\]

Functional method of the SumAggregation module.

Parameters:
  • x (torch.Tensor) – Node feature matrix \(\mathbf{X} \in \mathbb{R}^{(N_1 + \ldots + N_B) \times F}\).

  • batch (torch.Tensor, optional) – The batch vector \(\mathbf{b} \in {\{ 0, \ldots, B-1\}}^N\), which assigns each node to a specific example.

  • size (int, optional) – The number of examples \(B\). Automatically calculated if not given. (default: None)

Return type:

Tensor

global_mean_pool(x: Tensor, batch: Optional[Tensor], size: Optional[int] = None) Tensor[source]

通过平均节点维度上的节点特征,返回批处理级别的图级输出。

For a single graph \(\mathcal{G}_i\), its output is computed by

\[\mathbf{r}_i = \frac{1}{N_i} \sum_{n=1}^{N_i} \mathbf{x}_n.\]

Functional method of the MeanAggregation module.

Parameters:
  • x (torch.Tensor) – Node feature matrix \(\mathbf{X} \in \mathbb{R}^{(N_1 + \ldots + N_B) \times F}\).

  • batch (torch.Tensor, optional) – The batch vector \(\mathbf{b} \in {\{ 0, \ldots, B-1\}}^N\), which assigns each node to a specific example.

  • size (int, optional) – The number of examples \(B\). Automatically calculated if not given. (default: None)

Return type:

Tensor

global_max_pool(x: Tensor, batch: Optional[Tensor], size: Optional[int] = None) Tensor[source]

通过跨节点维度的通道方向最大值返回批次级别的图级输出。

For a single graph \(\mathcal{G}_i\), its output is computed by

\[\mathbf{r}_i = \mathrm{max}_{n=1}^{N_i} \, \mathbf{x}_n.\]

Functional method of the MaxAggregation module.

Parameters:
  • x (torch.Tensor) – Node feature matrix \(\mathbf{X} \in \mathbb{R}^{(N_1 + \ldots + N_B) \times F}\).

  • batch (torch.Tensor, optional) – The batch vector \(\mathbf{b} \in {\{ 0, \ldots, B-1\}}^N\), which assigns each element to a specific example.

  • size (int, optional) – The number of examples \(B\). Automatically calculated if not given. (default: None)

Return type:

Tensor

实用模块

agg_runs

对单个实验的不同随机种子进行聚合。

agg_batch

通过网格搜索聚合多个实验的结果。

params_count

计算参数的数量。

match_baseline_cfg

匹配给定基线模型的计算预算。

get_current_gpu_usage

获取当前GPU内存使用情况。

auto_select_device

为当前实验自动选择设备。

is_eval_epoch

确定是否应在当前时期评估模型。

is_ckpt_epoch

确定是否应在当前时期评估模型。

dict_to_json

字典转储到JSON文件中。

dict_list_to_json

将一系列字典转储到JSON文件中。

dict_to_tb

向Tensorboard写入器添加统计信息字典。

makedirs_rm_exist

创建一个目录,删除任何现有数据。

dummy_context

默认的上下文管理器,不执行任何操作。

agg_runs(dir, metric_best='auto')[source]

对单个实验的不同随机种子进行聚合。

Parameters:
  • dir (str) – 结果的目录,包含1个实验

  • metric_best (str, optional) – 用于选择最佳的指标

  • 选项 (验证性能。) – auto, accuracy, auc.

agg_batch(dir, metric_best='auto')[source]

通过网格搜索聚合多个实验的结果。

Parameters:
  • dir (str) – 结果目录,包含多个实验

  • metric_best (str, optional) – 用于选择最佳的指标

  • 选项 (验证性能。) – auto, accuracy, auc.

params_count(model)[source]

计算参数的数量。

Parameters:

model (nn.Module) – PyTorch 模型

match_baseline_cfg(cfg_dict, cfg_dict_baseline, verbose=True)[source]

匹配给定基线模型的计算预算。当前的配置字典将被修改并返回。

Parameters:
  • cfg_dict (dict) – 当前实验的配置

  • cfg_dict_baseline (dict) – 基线配置

  • verbose (str, optional) – 如果打印匹配的参数计数

get_current_gpu_usage()[source]

获取当前GPU内存使用情况。

auto_select_device()[source]

为当前实验自动选择设备。

is_eval_epoch(cur_epoch)[source]

确定是否应在当前时期评估模型。

is_ckpt_epoch(cur_epoch)[source]

确定是否应在当前时期评估模型。

dict_to_json(dict, fname)[source]

Dump a dictionary to a JSON file.

Parameters:
  • dict (dict) – Python 字典。

  • fname (str) – 输出文件名。

dict_list_to_json(dict_list, fname)[source]

Dump a list of dictionaries to a JSON file.

Parameters:
  • dict_list (list of dict) – 字典的列表。

  • fname (str) – 输出文件名。

dict_to_tb(dict, writer, epoch)[source]

向Tensorboard写入器添加统计信息字典。

Parameters:
  • dict (dict) – 实验的统计信息,键是属性名称,

  • values (这些值是属性) –

  • writer – Tensorboard 写入器对象

  • epoch (int) – 当前的epoch

makedirs_rm_exist(dir)[source]

创建一个目录,删除任何现有数据。

Parameters:

dir (str) – 要创建的目录。

class dummy_context[source]

默认的上下文管理器,不执行任何操作。