API Reference
Main model class
The main model class GNNModel is there to tie together the Graph neural network backbone and a multilayer perceptron classifier model that can be configured for various tasks.
GNNModel
Bases: Module, Configurable
Complete GNN model architecture with encoder, pooling, and downstream tasks.
This model combines: - An encoder network (typically GNN layers) to process graph structure - Optional pooling layers to aggregate node features into graph-level representations - Multiple downstream task heads for classification, regression, etc. - Optional graph features network for processing additional graph-level features
The model supports multi-task learning with selective task activation.
Source code in src/QuantumGrav/gnn_model.py
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 | |
__init__(encoder_type, downstream_tasks, encoder_args=None, encoder_kwargs=None, pooling_layers=None, aggregate_pooling_type=None, aggregate_pooling_args=None, aggregate_pooling_kwargs=None, latent_model_type=None, latent_model_args=None, latent_model_kwargs=None, graph_features_net_type=None, graph_features_net_args=None, graph_features_net_kwargs=None, aggregate_graph_features_type=None, aggregate_graph_features_args=None, aggregate_graph_features_kwargs=None, active_tasks=None)
Initialize GNNModel with encoder, pooling, and downstream task components.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
encoder_type
|
type
|
Class type or torch Module instance for the encoder network (e.g., GNN backbone). |
required |
encoder_args
|
Sequence[Any]
|
Positional arguments to pass to encoder_type constructor. |
None
|
encoder_kwargs
|
Dict[str, Any]
|
Keyword arguments to pass to encoder_type constructor. |
None
|
downstream_tasks
|
Sequence[Sequence[type, Sequence[Any], Dict[str, Any]]]
|
List of downstream tasks, where each task is specified as [task_type, task_args, task_kwargs]. |
required |
pooling_layers
|
Sequence[Sequence[type, Sequence[Any], Dict[str, Any]]] | None
|
List of pooling layers, where each layer is specified as [pooling_type, pooling_args, pooling_kwargs]. Defaults to None. |
None
|
aggregate_pooling_type
|
type | Callable | None
|
Type, Module instance or function for aggregating multiple pooling outputs. Required if pooling_layers is provided. Defaults to None. |
None
|
aggregate_pooling_args
|
Sequence[Any] | None
|
Positional arguments for aggregate_pooling_type. Defaults to None. |
None
|
aggregate_pooling_kwargs
|
Dict[str, Any] | None
|
Keyword arguments for aggregate_pooling_type. Defaults to None. |
None
|
latent_model_type
|
type | Module | None
|
Latent model type. Either this or pooling_layers can be used, not both. |
None
|
latent_model_args
|
Sequence[Any] | None
|
Latent model args. |
None
|
latent_model_kwargs
|
Dict[str, Any] | None
|
Latent model kwargs. |
None
|
graph_features_net_type
|
type | None
|
Network type for processing additional graph-level features. Defaults to None. |
None
|
graph_features_net_args
|
Sequence[Any] | None
|
Positional arguments for graph_features_net_type. Defaults to None. |
None
|
graph_features_net_kwargs
|
Dict[str, Any] | None
|
Keyword arguments for graph_features_net_type. Defaults to None. |
None
|
aggregate_graph_features_type
|
type | Callable | None
|
Type, Module instance or function for combining embeddings with graph features. Required if graph_features_net_type is provided. Defaults to None. |
None
|
aggregate_graph_features_args
|
Sequence[Any] | None
|
Positional arguments for aggregate_graph_features_type. Defaults to None. |
None
|
aggregate_graph_features_kwargs
|
Dict[str, Any] | None
|
Keyword arguments for aggregate_graph_features_type. Defaults to None. |
None
|
active_tasks
|
Dict[int, bool] | None
|
Dictionary mapping task indices to active status. If None, all tasks are active by default. Defaults to None. |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If downstream_tasks is empty (at least one task required). |
ValueError
|
If pooling_layers provided without aggregate_pooling_type or vice versa. |
ValueError
|
If pooling_layers is empty when provided. |
ValueError
|
If graph_features_net_type provided without aggregate_graph_features_type or vice versa. |
ValueError
|
If pooling_layers and latent_type are given at the same time. |
Source code in src/QuantumGrav/gnn_model.py
175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 | |
compute_downstream_tasks(x, args=None, kwargs=None)
Compute the outputs of the downstream tasks. Only the active tasks will be computed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Tensor
|
Input embeddings tensor |
required |
args
|
Sequence[Tuple | Sequence] | None
|
Arguments for downstream tasks. Defaults to None. |
None
|
kwargs
|
Sequence[Dict[str, Any]] | None
|
Keyword arguments for downstream tasks. Defaults to None. |
None
|
Returns:
| Type | Description |
|---|---|
Dict[int, Tensor | Collection[Tensor]]
|
Dict[int, torch.Tensor | Collection[torch.Tensor]]: Outputs of the downstream tasks. |
Source code in src/QuantumGrav/gnn_model.py
forward(x, edge_index, batch, graph_features=None, latent_args=None, latent_kwargs=None, downstream_task_args=None, downstream_task_kwargs=None, embedding_kwargs=None)
Forward run of the gnn model with optional graph features. First execute the graph-neural network backbone, then process the graph features, and finally apply the downstream tasks.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Tensor
|
Input node features. |
required |
edge_index
|
Tensor
|
Graph connectivity information. |
required |
batch
|
Tensor
|
Batch vector for pooling. |
required |
graph_features
|
Tensor | None
|
Additional graph features. Defaults to None. |
None
|
downstream_task_args
|
Sequence[Tuple | Sequence[Any]] | None
|
Arguments for downstream tasks. Defaults to None. |
None
|
downstream_task_kwargs
|
Sequence[Dict[str, Any]] | None
|
Keyword arguments for downstream tasks. Defaults to None. |
None
|
embedding_kwargs
|
dict[Any, Any] | None
|
Additional arguments for the GCN. Defaults to None. |
None
|
Returns:
| Type | Description |
|---|---|
Dict[int, Tensor]
|
Dict[int, torch.Tensor]: Raw output of downstream tasks. |
Source code in src/QuantumGrav/gnn_model.py
from_config(config)
classmethod
Create a GNNModel instance from a configuration dictionary.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
dict
|
Configuration dictionary with keys matching init parameters. Must include: encoder_type, encoder_args, encoder_kwargs, downstream_tasks. Optional: pooling_layers, aggregate_pooling_type, graph_features_net_type, etc. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
GNNModel |
GNNModel
|
An initialized GNNModel instance. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If model creation fails (wraps underlying exceptions). |
ValidationError
|
If config is invalid. |
Source code in src/QuantumGrav/gnn_model.py
get_embeddings(x, edge_index, batch=None, gcn_kwargs=None, latent_args=None, latent_kwargs=None)
Get embeddings from the GCN model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Tensor
|
Input node features. |
required |
edge_index
|
Tensor
|
Graph connectivity information. |
required |
batch
|
Tensor
|
Batch vector for pooling. |
None
|
gcn_kwargs
|
dict
|
Additional arguments for the GCN. Defaults to None. |
None
|
Returns:
| Type | Description |
|---|---|
Tensor
|
torch.Tensor: Embedding vector for the graph features. |
Source code in src/QuantumGrav/gnn_model.py
load(path, config=None, args=None, kwargs=None, device=torch.device('cpu'))
classmethod
Load a GNNModel from a file saved with the save() method that's defined by the provided config. It is assumed that the config used to save the model is the same as the one provided here or defines the same model architecture. Therefore, configs should always be saved alongside the model weights.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Path to the saved model file. |
required |
config
|
Dict[str, Any] | None
|
Config for building the model |
None
|
args
|
Sequence[Any] | None
|
Arguments for building the model if config is not supplied |
None
|
kwargs
|
Dict[str, Any] | None
|
Keyword argumetns for building the model if config is not supplied |
None
|
device
|
device
|
Device to load the model onto. Defaults to torch.device("cpu"). |
device('cpu')
|
Returns:
| Name | Type | Description |
|---|---|---|
GNNModel |
GNNModel
|
Fully initialized model instance with loaded weights. |
Source code in src/QuantumGrav/gnn_model.py
save(path)
Save the model state dictionary to file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
File path where the model will be saved. |
required |
set_task_active(key)
Set a downstream task as active.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
int
|
key (name) of the downstream task to activate. |
required |
Source code in src/QuantumGrav/gnn_model.py
set_task_inactive(key)
Set a downstream task as inactive.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
int
|
key (name) of the downstream task to deactivate. |
required |
Source code in src/QuantumGrav/gnn_model.py
ModuleWrapper
Bases: Module
Wrapper to make pooling functions compatible with ModuleList and ModuleDict
Source code in src/QuantumGrav/gnn_model.py
instantiate_type(object_or_type, args, kwargs)
Helper to instantiate a type from args, kwargs or use it directly. When a function is passed, it will be wrapped in a ModuleWrapper instance
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
object_or_type
|
type | Module
|
type or object to check and instantiate |
required |
args
|
Sequence[Any] | None
|
args to build the object |
required |
kwargs
|
Dict[str, Any] | None
|
kwargs to build the object |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
When the type is not a subclass or instance of both torch.nn.Module and QG.base.Configurable |
Returns:
| Type | Description |
|---|---|
|
newly instantiated object of type 'object_or_type' or the passed object |
Source code in src/QuantumGrav/gnn_model.py
Graph Neural network submodels
The submodel classes in this section comprise the graph neural network backbone of a QuantumGrav model.
Graph model block
This submodel is the main part of the graph neural network backbone, composed of a set of GNN layers from pytorch-geometric with dropout and BatchNorm.
GNNBlock
Bases: Module, Configurable
Graph Neural Network Block. Consists of a GNN layer, a normalizer, an activation function, and a residual connection. The gnn-layer is applied first, followed by the normalizer and activation function. The result is then projected from the input dimensions to the output dimensions using a linear layer and added to the original input (residual connection). Finally, dropout is applied for regularization.
Source code in src/QuantumGrav/models/gnn_block.py
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 | |
__init__(in_dim, out_dim, dropout=0.3, with_skip=True, gnn_layer_type=torch_geometric.nn.conv.GCNConv, gnn_layer_args=None, gnn_layer_kwargs=None, normalizer_type=torch.nn.Identity, norm_args=None, norm_kwargs=None, activation_type=torch.nn.ReLU, activation_args=None, activation_kwargs=None, skip_args=None, skip_kwargs=None)
Create a GNNBlock instance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
in_dim
|
int
|
The dimensions of the input features. |
required |
out_dim
|
int
|
The dimensions of the output features. |
required |
dropout
|
float
|
The dropout probability. Defaults to 0.3. |
0.3
|
with_skip
|
bool
|
Whether to use a skip connection. Defaults to True. |
True
|
gnn_layer_type
|
Module
|
The type of GNN-layer to use. Defaults to torch_geometric.nn.conv.GCNConv. |
GCNConv
|
gnn_layer_args
|
list[Any]
|
Additional arguments for the GNN layer. Defaults to None. |
None
|
gnn_layer_kwargs
|
Dict[str, Any]
|
Additional keyword arguments for the GNN layer. Defaults to None. |
None
|
normalizer
|
Module
|
The normalizer layer to use. Defaults to torch.nn.Identity. |
required |
norm_args
|
list[Any]
|
Additional arguments for the normalizer layer. Defaults to None. |
None
|
norm_kwargs
|
Dict[str, Any]
|
Additional keyword arguments for the normalizer layer. Defaults to None. |
None
|
activation
|
Module
|
The activation function to use. Defaults to torch.nn.ReLU. |
required |
activation_args
|
list[Any]
|
Additional arguments for the activation function. Defaults to None. |
None
|
activation_kwargs
|
Dict[str, Any]
|
Additional keyword arguments for the activation function. Defaults to None. |
None
|
skip_args
|
list[Any]
|
Additional arguments for the projection layer. Defaults to None. |
None
|
skip_kwargs
|
Dict[str, Any]
|
Additional keyword arguments for the projection layer. Defaults to None. |
None
|
Source code in src/QuantumGrav/models/gnn_block.py
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 | |
forward(x, edge_index, **kwargs)
Forward pass for the GNNBlock. First apply the graph convolution layer, then normalize and apply the activation function. Finally, apply a residual connection and dropout. Args: x (torch.Tensor): The input node features. edge_index (torch.Tensor): The graph connectivity information. edge_weight (torch.Tensor, optional): The edge weights. Defaults to None. kwargs (dict[Any, Any], optional): Additional keyword arguments for the GNN layer. Defaults to None.
Returns:
| Type | Description |
|---|---|
Tensor
|
torch.Tensor: The output node features. |
Source code in src/QuantumGrav/models/gnn_block.py
from_config(config)
classmethod
Create a GNNBlock from a configuration dictionary. When the config does not have 'dropout', it defaults to 0.3.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
dict[str, Any]
|
Configuration dictionary containing the parameters for the GNNBlock. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
GNNBlock |
GNNBlock
|
An instance of GNNBlock initialized with the provided configuration. |
Source code in src/QuantumGrav/models/gnn_block.py
load(path, device=torch.device('cpu'))
classmethod
Load a mode instance from file
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Path to the file to load. |
required |
device
|
device
|
device to put the model to. Defaults to torch.device("cpu") |
device('cpu')
|
Returns: GNNBlock: A GNNBlock instance initialized from the data loaded from the file.
Source code in src/QuantumGrav/models/gnn_block.py
save(path)
Save the model's state to file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
path to save the model to. |
required |
Source code in src/QuantumGrav/models/gnn_block.py
to_config()
Convert the GNNBlock instance to a configuration dictionary.
Source code in src/QuantumGrav/models/gnn_block.py
Base class for models composed of linear layers
LinearSequential
Bases: Module, Configurable
This class implements a neural network block consisting of a backbone (a sequence of linear layers with activation functions) and multiple output layers for classification tasks. It supports multi-objective classification by allowing multiple output layers, each corresponding to a different classification task, but can also be used for any other type of sequential processing that involves linear layers.
Source code in src/QuantumGrav/models/linear_sequential.py
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 | |
__init__(dims, activations, linear_kwargs=None, activation_kwargs=None)
Create a LinearSequential object containing a sequence of MLPs of type torch_geometric.nn.dense.Linear, interspersed with activation functions. All layers are of type Linear with an activation function in between (the backbone) and a set of linear output layers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_dim
|
int
|
input dimension of the LinearSequential object |
required |
output_dim
|
int
|
output dimension for the output layer, i.e., the classification task |
required |
hidden_dims
|
list[int]
|
list of hidden dimensions for the backbone |
required |
activation
|
type[Module]
|
activation function to use. Defaults to torch.nn.ReLU. |
required |
backbone_kwargs
|
list[dict]
|
additional arguments for the backbone layers. Defaults to None. |
required |
output_kwargs
|
dict
|
additional keyword arguments for the output layers. Defaults to None. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If hidden_dims contains non-positive integers. |
ValueError
|
If output_dim is a non-positive integer. |
Source code in src/QuantumGrav/models/linear_sequential.py
forward(x)
Forward pass through the LinearSequential object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Tensor
|
Input tensor. |
required |
Returns:
| Type | Description |
|---|---|
list[Tensor]
|
list[torch.Tensor]: List of output tensors from each classifier layer. |
Source code in src/QuantumGrav/models/linear_sequential.py
from_config(config)
classmethod
Create a LinearSequential from a configuration dictionary.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
Dict[str, Any]
|
Configuration dictionary containing parameters for the LinearSequential. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
LinearSequential |
LinearSequential
|
An instance of LinearSequential initialized with the provided configuration. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the specified activation function is not registered. |
Source code in src/QuantumGrav/models/linear_sequential.py
load(path, device=torch.device('cpu'))
classmethod
Load a LinearSequential instance from file
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
path to the file to load the model from |
required |
device
|
device
|
device to put the model to. Defaults to torch.device("cpu") |
device('cpu')
|
Returns: LinearSequential: An instance of LinearSequential initialized from the loaded data.
Source code in src/QuantumGrav/models/linear_sequential.py
save(path)
Save the model's state to file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
path to save the model to. |
required |
Source code in src/QuantumGrav/models/linear_sequential.py
to_config()
Build a config file from the current model
Returns:
| Type | Description |
|---|---|
Dict[str, Any]
|
Dict[str, Any]: Model config |
Source code in src/QuantumGrav/models/linear_sequential.py
Model evaluation
This module provides base classes that take the output of applying the model to a validation or training dataset, and derive useful quantities to evaluate the model quality. These do not do anything useful by default. Rather, you must derive your own class from them that implemements your desired evaluation, e.g., using an F1 score.
DefaultEvaluator
Default evaluator for model evaluation - testing and validation during training
Source code in src/QuantumGrav/evaluate.py
__init__(device, criterion, apply_model=None)
Default evaluator for model evaluation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
device
|
str | device | int
|
The device to run the evaluation on. |
required |
criterion
|
Callable
|
The loss function to use for evaluation. |
required |
apply_model
|
Callable
|
A function to apply the model to the data. |
None
|
Source code in src/QuantumGrav/evaluate.py
evaluate(model, data_loader)
Evaluate the model on the given data loader.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
Module
|
Model to evaluate. |
required |
data_loader
|
DataLoader
|
Data loader for evaluation. |
required |
Returns:
| Type | Description |
|---|---|
list[Any]
|
list[Any]: A list of evaluation results. |
Source code in src/QuantumGrav/evaluate.py
report(data)
Report the evaluation results.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
list | Series | Tensor | ndarray
|
The evaluation results. |
required |
Source code in src/QuantumGrav/evaluate.py
DefaultTester
Bases: DefaultEvaluator
Default tester for model testing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
DefaultEvaluator
|
Class
|
Inherits from DefaultEvaluator and provides functionality for validating models |
required |
using a specified criterion and optional model application function.
Source code in src/QuantumGrav/evaluate.py
__init__(device, criterion, apply_model=None)
Default tester for model testing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
device
|
(str | device | int,)
|
The device to run the testing on. |
required |
criterion
|
Callable
|
The loss function to use for testing. |
required |
apply_model
|
Callable
|
A function to apply the model to the data. |
None
|
Source code in src/QuantumGrav/evaluate.py
test(model, data_loader)
Test the model on the given data loader.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
Module
|
Model to test. |
required |
data_loader
|
DataLoader
|
Data loader for testing. |
required |
Returns:
| Type | Description |
|---|---|
list[Any]
|
list[Any]: A list of testing results. |
Source code in src/QuantumGrav/evaluate.py
DefaultValidator
Bases: DefaultEvaluator
Default validator for model validation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
DefaultEvaluator
|
Class
|
Inherits from DefaultEvaluator and provides functionality for validating models |
required |
using a specified criterion and optional model application function.
Source code in src/QuantumGrav/evaluate.py
__init__(device, criterion, apply_model=None)
Default validator for model validation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
device
|
(str | device | int,)
|
The device to run the validation on. |
required |
criterion
|
Callable
|
The loss function to use for validation. |
required |
apply_model
|
Callable | None
|
A function to apply the model to the data. Defaults to None. |
None
|
Source code in src/QuantumGrav/evaluate.py
validate(model, data_loader)
Validate the model on the given data loader.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
Module
|
Model to validate. |
required |
data_loader
|
DataLoader
|
Data loader for validation. |
required |
Returns: list[Any]: A list of validation results.
Source code in src/QuantumGrav/evaluate.py
Datasets
The package supports three kinds of datasets with a common baseclass QGDatasetBase. For the basics of how those work, check out the pytorch-geometric documentation of dataset
These are:
- QGDataset: A dataset that relies on an on-disk storage of the processed data. It lazily loads csets from disk when needed.
- QGDatasetInMemory: A dataset that holds the entire processed dataset in memory at once.
- QGDatasetOnthefly: This dataset does not hold anything on disk or in memory, but creates the data on demand from some supplied Julia code.
Dataset base class
QGDatasetBase
Mixin class that provides common functionality for the dataset classes. Works only for file-based datasets. Provides methods for processing data.
Source code in src/QuantumGrav/dataset_base.py
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 | |
processed_dir
property
Get the path to the processed directory.
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The path to the processed directory, or None if it doesn't exist. |
processed_file_names
property
Get a list of processed files in the processed directory.
Returns:
| Type | Description |
|---|---|
list[str]
|
list[str]: A list of processed file paths, excluding JSON files. |
raw_file_names
property
Get the raw file paths from the input list.
Returns:
| Type | Description |
|---|---|
list[str]
|
list[str]: A list of raw file paths. |
__init__(input, output, reader=None, float_type=torch.float32, int_type=torch.int64, validate_data=True, n_processes=1, chunksize=1000, preprocess=False)
Initialize a QGDatasetBase instance. This class is designed to provide some common functionality that can be used by downstream datasets built on top of torch dataset classes. It is not to be instantiated directly, but rather used as a mixin for other dataset classes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input (list[str | Path]
|
The list of input files for the dataset, or a callable that generates a set of input files. |
required | |
output
|
str | Path
|
The output directory where processed data will be stored. |
required |
reader
|
Callable[[Group, dtype, dtype, bool], list[Data]] | None
|
A function to load data from a file. Defaults to None. |
None
|
float_type
|
dtype
|
The data type to use for floating point values. Defaults to torch.float32. |
float32
|
int_type
|
dtype
|
The data type to use for integer values. Defaults to torch.int64. |
int64
|
validate_data
|
bool
|
Whether to validate the data after loading. Defaults to True. |
True
|
n_processes
|
int
|
The number of processes to use for parallel processing of read data. Defaults to 1. |
1
|
chunksize
|
int
|
The size of the chunks to process in parallel. Defaults to 1000. |
1000
|
preprocess
|
bool
|
(bool, optional): Whether datapreprocessing should happen and the results be stored on disk. Defaults to False. |
False
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If one of the input data files does not exist |
ValueError
|
If the metadata retrieval function is invalid. |
FileNotFoundError
|
If an input file does not exist. |
Source code in src/QuantumGrav/dataset_base.py
process_chunk(store, start, pre_transform=None, pre_filter=None)
Process a chunk of data from the raw file. This method is intended to be used in the data loading pipeline to read a chunk of data, apply transformations, and filter the read data, and thus should not be called directly.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
store
|
LocalStore
|
local zarr storage |
required |
start
|
int
|
start index |
required |
pre_transform
|
Callable[[Data], Data] | None
|
Transformation that adds additional features to the data. Defaults to None. |
None
|
pre_filter
|
Callable[[Data], bool] | None
|
A function that filters the data. Defaults to None. |
None
|
Returns:
| Type | Description |
|---|---|
Sequence[Data]
|
list[Data]: The processed data or None if the chunk is empty. |
Source code in src/QuantumGrav/dataset_base.py
Dataset loading data from disk
QGDataset
Bases: QGDatasetBase, Dataset
A dataset class for QuantumGrav data that is designed to handle large datasets stored on disk. This class provides methods for loading, processing, and writing data that are common to both in-memory and on-disk datasets.
Source code in src/QuantumGrav/dataset_ondisk.py
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 | |
__del__()
__getitem__(idx)
summary
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
idx
|
int | Sequence[int]
|
description |
required |
Returns:
| Type | Description |
|---|---|
Data | Sequence[Data] | Collection[Any]
|
Data | Sequence[Data] | Collection[Any]: description |
Source code in src/QuantumGrav/dataset_ondisk.py
__init__(input, output, reader=None, float_type=torch.float32, int_type=torch.int64, validate_data=True, chunksize=1000, n_processes=1, transform=None, pre_transform=None, pre_filter=None)
Create a new QGDataset instance. This class is designed to handle the loading, processing, and writing of QuantumGrav datasets that are stored on disk. When there is no pre_transform and no pre_filter is given, the system will not create a processed directory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input
|
list[str | Path] | Callable[[Any], dict]
|
List of input zarr file paths. |
required |
output
|
str | Path
|
Output directory where processed data will be stored. |
required |
reader
|
Callable[[Group, int], list[Data]] | None
|
Function to read data from the zarr file. Defaults to None. |
None
|
float_type
|
dtype
|
Data type for float tensors. Defaults to torch.float32. |
float32
|
int_type
|
dtype
|
Data type for int tensors. Defaults to torch.int64. |
int64
|
validate_data
|
bool
|
Whether to validate the data. Defaults to True. |
True
|
chunksize
|
int
|
Size of data chunks to process at once. Defaults to 1000. |
1000
|
n_processes
|
int
|
Number of processes to use for data loading. Defaults to 1. |
1
|
transform
|
Callable[[Data], Data] | None
|
Function to transform the data. Defaults to None. |
None
|
pre_transform
|
Callable[[Data], Data] | None
|
Function to pre-transform the data. Defaults to None. |
None
|
pre_filter
|
Callable[[Data], bool] | None
|
Function to pre-filter the data. Defaults to None. |
None
|
Source code in src/QuantumGrav/dataset_ondisk.py
close()
get(idx)
Get a single data sample by index.
Source code in src/QuantumGrav/dataset_ondisk.py
len()
Get the number of samples in the dataset.
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
The number of samples in the dataset. |
map_index(idx)
Map a global index to a specific file and local index within that file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
idx
|
int
|
The global index to map. |
required |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If the index cannot be mapped to any file. |
Returns:
| Type | Description |
|---|---|
Tuple[str | Path, int]
|
Tuple[str | Path, int]: The file and local index corresponding to the global index. |
Source code in src/QuantumGrav/dataset_ondisk.py
process()
Process the dataset from the read rawdata into its final form.
Source code in src/QuantumGrav/dataset_ondisk.py
write_data(data, idx)
Write the processed data to disk using torch.save. This is a default implementation that can be overridden by subclasses, and is intended to be used in the data loading pipeline. Thus, is not intended to be called directly.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
list[Data]
|
The list of Data objects to write to disk. |
required |
idx
|
int
|
The index to use for naming the files. |
required |
Source code in src/QuantumGrav/dataset_ondisk.py
Julia-Python integration
This class provides a bridge to some user-supplied Julia code and converts its output into something Python can work with.
JuliaWorker
This class runs a given Julia callable object from a given Julia code file. It additionally imports the QuantumGrav julia module and installs given dependencies if provided. After creation, the wrapped julia callable can be called via the call method of this calls. Warning: This class requires the juliacall package to be installed in the Python environment. Warning: This class is in early development and may change in the future, be slow, or otherwise not ready for high performance production use.
Source code in src/QuantumGrav/julia_worker.py
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 | |
__call__(*args, **kwargs)
Calls the wrapped Julia generator with the given arguments.
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If the Julia module is not initialized. |
Args: args: Positional arguments to pass to the Julia generator. *kwargs: Keyword arguments to pass to the Julia generator. Returns: Any: The raw data generated by the Julia generator.
Source code in src/QuantumGrav/julia_worker.py
__init__(jl_kwargs=None, jl_code_path=None, jl_constructor_name=None, jl_base_module_path=None, jl_dependencies=None)
Initializes the JuliaWorker with the given parameters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
jl_kwargs
|
dict[str, Any] | None
|
Keyword arguments to pass to the Julia callable object constructor. Defaults to None. |
None
|
jl_code_path
|
str | Path | None
|
Path to the Julia code file in which the callable object is defined. Defaults to None. |
None
|
jl_constructor_name
|
str | None
|
Name of the Julia constructor function. Defaults to None. |
None
|
jl_base_module_path
|
str | Path | None
|
Path to the base Julia module 'QuantumGrav.jl'. If not given, tries to load it via a default |
None
|
jl_dependencies
|
list[str] | None
|
List of Julia package dependencies. Defaults to None. Will be installed via |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If the Julia function name is not provided. |
ValueError
|
If the Julia code path is not provided. |
FileNotFoundError
|
If the Julia code path does not exist. |
NotImplementedError
|
If the base module path is not provided. |
RuntimeError
|
If there is an error loading the base module. |
RuntimeError
|
If there is an error loading Julia dependencies. |
RuntimeError
|
If there is an error loading the Julia code. |
Source code in src/QuantumGrav/julia_worker.py
Model training
This consists of two classes, one which provides the basic training functionality - Trainer, and a class derived from this, TrainerDDP, which provides functionality for distributed data parallel training.
Trainer
This class provides wrapper functions for setting up a model and for training and evaluating it. The basic concept is that everything is defined in a yaml file and handed to this class together with evaluator classes. After construction, the train and test functions will take care of the training and testing of the model.
Trainer
Bases: Configurable
Trainer class for training and evaluating GNN models.
Source code in src/QuantumGrav/train.py
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 | |
__init__(config)
Initialize the trainer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
dict[str, Any]
|
The configuration dictionary. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the configuration is invalid. |
Source code in src/QuantumGrav/train.py
326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 | |
from_config(config)
classmethod
Create a Trainer instance from a configuration dictionary.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
Dict[str, Any]
|
The configuration dictionary. |
required |
Source code in src/QuantumGrav/train.py
initialize_lr_scheduler()
Initialize the learning rate scheduler for training.
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If the optimizer is not initialized. |
Returns:
| Type | Description |
|---|---|
_LRScheduler | None
|
torch.optim.lr_scheduler._LRScheduler: The initialized learning rate scheduler. |
Source code in src/QuantumGrav/train.py
initialize_model()
Initialize the model for training.
Returns:
| Name | Type | Description |
|---|---|---|
Any |
Any
|
The initialized model. |
Source code in src/QuantumGrav/train.py
initialize_optimizer()
Initialize the optimizer for training.
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If the model is not initialized. |
Returns:
| Type | Description |
|---|---|
Optimizer | None
|
torch.optim.Optimizer: The initialized optimizer. |
Source code in src/QuantumGrav/train.py
load_checkpoint(name_addition='')
Load model checkpoint to the device given
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name_addition
|
str
|
An optional string to append to the checkpoint filename. |
''
|
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If the model is not initialized. |
Source code in src/QuantumGrav/train.py
prepare_dataloaders(dataset=None, split=[0.8, 0.1, 0.1], train_dataset=None, val_dataset=None, test_dataset=None, training_sampler=None)
Prepare the data loaders for training, validation, and testing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dataset
|
Dataset
|
The dataset to prepare. |
None
|
split
|
list[float]
|
The split ratios for training, validation, and test sets. Defaults to [0.8, 0.1, 0.1]. |
[0.8, 0.1, 0.1]
|
training_sampler
|
Sampler
|
The sampler for the training data loader. Defaults to None. |
None
|
Returns:
| Type | Description |
|---|---|
Tuple[DataLoader, DataLoader, DataLoader]
|
Tuple[DataLoader, DataLoader, DataLoader]: The data loaders for training, validation, and testing. |
Source code in src/QuantumGrav/train.py
prepare_dataset(dataset=None, split=[0.8, 0.1, 0.1], train_dataset=None, val_dataset=None, test_dataset=None)
Set up the split for training, validation, and testing datasets.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dataset
|
Dataset | None
|
Dataset to be split. Only one of dataset, train_dataset, val_dataset, test_dataset should be provided. Defaults to None. |
None
|
split
|
list[float]
|
split ratios for train, validation, and test datasets. Defaults to [0.8, 0.1, 0.1]. |
[0.8, 0.1, 0.1]
|
train_dataset
|
Subset | None
|
Training subset of the dataset. Only one of dataset, train_dataset, val_dataset, test_dataset should be provided. Defaults to None. |
None
|
val_dataset
|
Subset | None
|
Validation subset of the dataset. Only one of dataset, train_dataset, val_dataset, test_dataset should be provided. Defaults to None. |
None
|
test_dataset
|
Subset | None
|
Testing subset of the dataset. Only one of dataset, train_dataset, val_dataset, test_dataset should be provided. Defaults to None. |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If providing train, val, or test datasets, the full dataset must not be provided. |
ValueError
|
If split ratios are not summing up to 1 |
ValueError
|
If train size is 0 |
ValueError
|
If validation size is 0 |
ValueError
|
If test size is 0 |
Returns:
| Type | Description |
|---|---|
Tuple[Dataset, Dataset, Dataset]
|
Tuple[Dataset, Dataset, Dataset]: train, validation, and test datasets. |
Source code in src/QuantumGrav/train.py
528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 | |
run_test(test_loader, model_name_addition='current_best.pt')
Run testing phase.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
test_loader
|
DataLoader
|
The data loader for the test set. |
required |
model_name_addition
|
str
|
An optional string to append to the checkpoint filename. |
'current_best.pt'
|
Raises: RuntimeError: If the model is not initialized. RuntimeError: If the test data is not available.
Returns:
| Type | Description |
|---|---|
Collection[Any]
|
Collection[Any]: A collection of test results that can be scalars, tensors, lists, dictionaries or any other data type that the tester might return. |
Source code in src/QuantumGrav/train.py
run_training(train_loader, val_loader, trial=None)
Run the training process.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
train_loader
|
DataLoader
|
The data loader for the training set. |
required |
val_loader
|
DataLoader
|
The data loader for the validation set. |
required |
trial
|
Trial | None
|
An Optuna trial for hyperparameter tuning. Defaults to None. |
None
|
Returns:
| Type | Description |
|---|---|
Tuple[Tensor | Collection[Any], Tensor | Collection[Any]]
|
Tuple[torch.Tensor | Collection[Any], torch.Tensor | Collection[Any]]: The training and validation results. |
Source code in src/QuantumGrav/train.py
save_checkpoint(name_addition='')
Save model checkpoint.
Raises:
| Type | Description |
|---|---|
ValueError
|
If the model is not initialized. |
ValueError
|
If the model configuration does not contain 'name'. |
ValueError
|
If the training configuration does not contain 'checkpoint_path'. |
Source code in src/QuantumGrav/train.py
Distributed data parallel Trainer class
This is based on this part of the pytorch documentation and is untested at the time of writing.
TrainerDDP
Bases: Trainer
Distributed Data Parallel (DDP) Trainer for training GNN models across multiple processes.
Source code in src/QuantumGrav/train_ddp.py
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 | |
__init__(rank, config)
Initialize the distributed data parallel (DDP) trainer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rank
|
int
|
The rank of the current process. |
required |
config
|
dict[str, Any]
|
The configuration dictionary. |
required |
criterion
|
Callable
|
The loss function. |
required |
apply_model
|
Callable | None
|
The function to apply the model. Defaults to None. |
required |
early_stopping
|
Callable[[list[dict[str, Any]]], bool] | None
|
The early stopping function. Defaults to None. |
required |
validator
|
DefaultValidator | None
|
The validator for model evaluation. Defaults to None. |
required |
tester
|
DefaultTester | None
|
The tester for model testing. Defaults to None. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the configuration is invalid. |
Source code in src/QuantumGrav/train_ddp.py
initialize_model()
Initialize the model for training.
Returns:
| Name | Type | Description |
|---|---|---|
DDP |
DistributedDataParallel
|
The initialized model. |
Source code in src/QuantumGrav/train_ddp.py
prepare_dataloaders(dataset=None, split=[0.8, 0.1, 0.1], train_dataset=None, val_dataset=None, test_dataset=None, training_sampler=None)
Prepare dataloader for distributed training.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dataset
|
Dataset | None
|
Dataset to use. Defaults to None. |
None
|
split
|
list[float]
|
Splits into train, validation and test datasets. Defaults to [0.8, 0.1, 0.1]. |
[0.8, 0.1, 0.1]
|
train_dataset
|
Subset | None
|
Training dataset. Only used when Dataset is None. Defaults to None. |
None
|
val_dataset
|
Subset | None
|
Validation dataset. Only used when Dataset is None.. Defaults to None. |
None
|
test_dataset
|
Subset | None
|
Test dataset. Only used when Dataset is None.. Defaults to None. |
None
|
training_sampler
|
Sampler | None
|
Ignored here. Defaults to None. |
None
|
Returns:
| Type | Description |
|---|---|
Tuple[DataLoader, DataLoader, DataLoader]
|
Tuple[ DataLoader, DataLoader, DataLoader, ]: Train, validation and test dataloaders |
Source code in src/QuantumGrav/train_ddp.py
168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 | |
run_training(train_loader, val_loader, trial=None)
Run the training loop for the distributed model. This will synchronize for validation. No testing is performed in this function. The model will only be checkpointed and early stopped on the 'rank' 0 process.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
train_loader
|
DataLoader
|
The training data loader. |
required |
val_loader
|
DataLoader
|
The validation data loader. |
required |
trial
|
Trial | None
|
An Optuna trial for hyperparameter optimization. Defaults to None. |
None
|
Returns:
| Type | Description |
|---|---|
Tuple[Tensor | Collection[Any], Tensor | Collection[Any]]
|
Tuple[torch.Tensor | Collection[Any], torch.Tensor | Collection[Any]]: The training and validation results. |
Source code in src/QuantumGrav/train_ddp.py
298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 | |
save_checkpoint(name_addition='')
Save model checkpoint.
Raises:
| Type | Description |
|---|---|
ValueError
|
If the model is not initialized. |
ValueError
|
If the model configuration does not contain 'name'. |
ValueError
|
If the training configuration does not contain 'checkpoint_path'. |
Source code in src/QuantumGrav/train_ddp.py
cleanup_ddp()
Clean up the distributed process group.
initialize_ddp(rank, worldsize, master_addr='localhost', master_port='12345', backend='nccl')
Initialize the distributed process group. This assumes one process per GPU.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rank
|
int
|
The rank of the current process. |
required |
worldsize
|
int
|
The total number of processes. |
required |
master_addr
|
str
|
The address of the master process. Defaults to "localhost". This needs to be the ip of the master node if you are running on a cluster. |
'localhost'
|
master_port
|
str
|
The port of the master process. Defaults to "12345". Choose a high port if you are running multiple jobs on the same machine to avoid conflicts. If running on a cluster, this should be the port that the master node is listening on. |
'12345'
|
backend
|
str
|
The backend to use for distributed training. Defaults to "nccl". |
'nccl'
|
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If the environment variables MASTER_ADDR and MASTER_PORT are already set. |
Source code in src/QuantumGrav/train_ddp.py
Utilities
General utilities that are used throughout this package.
assign_at_path(cfg, path, value)
Assign a value to a key in a nested dictionary 'dict'. The path to follow through this nested structure is given by 'path'.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cfg
|
dict
|
The configuration dictionary to modify. |
required |
path
|
Sequence[Any]
|
The path to the key to modify as a list of nodes to traverse. |
required |
value
|
Any
|
The value to assign to the key. |
required |
Source code in src/QuantumGrav/utils.py
get_at_path(cfg, path, default=None)
Get the value at a key in a nested dictionary. The path to follow through this nested structure is given by 'path'.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cfg
|
dict
|
The configuration dictionary to modify. |
required |
path
|
Sequence[Any]
|
The path to the key to get as a list of nodes to traverse. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
Any |
Any
|
The value at the specified key, or None if not found. |
Source code in src/QuantumGrav/utils.py
import_and_get(importpath)
Import a module and get an object from it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
importpath
|
str
|
The import path of the object to get. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
Any |
Any
|
The name as imported from the module. |
Raises:
| Type | Description |
|---|---|
KeyError
|
When the module indicated by the path is not found |
KeyError
|
When the object name indidcated by the path is not found in the module |