Inference API
The FastAPI service wraps the graph neural network to expose prediction endpoints.
Inference Service
project_name.api.InferenceService
Handles model loading and predictions.
Source code in src/project_name/api.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 | |
predict
predict(node_features: list[list[float]], edge_index: list[list[int]]) -> list[float]
Generate prediction.
Source code in src/project_name/api.py
67 68 69 70 71 72 73 74 75 76 77 78 | |
Request/Response Schemas
project_name.api.PredictionRequest
Bases: BaseModel
Input for prediction.
Source code in src/project_name/api.py
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 | |
validate_node_features
validate_node_features(v: list[list[float]]) -> list[list[float]]
Validate node features have correct number of features.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
v |
list[list[float]]
|
Node features matrix. |
required |
Returns:
| Type | Description |
|---|---|
list[list[float]]
|
Validated node features. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If node features don't have correct number of dimensions. |
Source code in src/project_name/api.py
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | |
project_name.api.PredictionResponse
Bases: BaseModel
Prediction output.
Source code in src/project_name/api.py
46 47 48 49 | |
Routes
project_name.api.health_check
health_check()
Health check.
Source code in src/project_name/api.py
121 122 123 124 | |
project_name.api.predict
predict(request: PredictionRequest, background_tasks: BackgroundTasks)
Generate prediction.
Source code in src/project_name/api.py
127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 | |
Modules
api
project_name.api
InferenceService
Handles model loading and predictions.
Source code in src/project_name/api.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 | |
predict
predict(node_features: list[list[float]], edge_index: list[list[int]]) -> list[float]
Generate prediction.
Source code in src/project_name/api.py
67 68 69 70 71 72 73 74 75 76 77 78 | |
PredictionRequest
Bases: BaseModel
Input for prediction.
Source code in src/project_name/api.py
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 | |
validate_node_features
validate_node_features(v: list[list[float]]) -> list[list[float]]
Validate node features have correct number of features.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
v |
list[list[float]]
|
Node features matrix. |
required |
Returns:
| Type | Description |
|---|---|
list[list[float]]
|
Validated node features. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If node features don't have correct number of dimensions. |
Source code in src/project_name/api.py
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | |
PredictionResponse
Bases: BaseModel
Prediction output.
Source code in src/project_name/api.py
46 47 48 49 | |
health_check
health_check()
Health check.
Source code in src/project_name/api.py
121 122 123 124 | |
lifespan
async
lifespan(app: FastAPI)
Load model on startup.
Source code in src/project_name/api.py
87 88 89 90 91 92 93 94 95 96 | |
predict
predict(request: PredictionRequest, background_tasks: BackgroundTasks)
Generate prediction.
Source code in src/project_name/api.py
127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 | |
save_prediction_to_gcp
save_prediction_to_gcp(node_features: list[list[float]], edge_index: list[list[int]], outputs: list[float])
Save the prediction results to GCP bucket.
Source code in src/project_name/api.py
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 | |
compare_promote
project_name.compare_promote
data
project_name.data
QM9Dataset
Bases: Dataset
QM9 dataset wrapper from torch_geometric.
Source code in src/project_name/data.py
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 | |
__getitem__
__getitem__(index: int)
Return a given sample from the dataset.
Source code in src/project_name/data.py
39 40 41 | |
__init__
__init__(data_path: Path) -> None
Initialize the QM9 dataset.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data_path |
Path
|
Path to the data directory where QM9 will be stored. |
required |
Source code in src/project_name/data.py
10 11 12 13 14 15 16 17 | |
__len__
__len__() -> int
Return the length of the dataset.
Source code in src/project_name/data.py
35 36 37 | |
preprocess
preprocess(output_folder: Path) -> None
Preprocess the raw data and save it to the output folder.
Source code in src/project_name/data.py
43 44 | |
download_model
project_name.download_model
evaluate
project_name.evaluate
evaluate
evaluate(model: GraphNeuralNetwork, loader: DataLoader, device: torch.device, target_indices: Sequence[int]) -> float
Evaluate model on a dataloader.
Computes mean MSE loss per graph over the entire loader, matching train_epoch.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model |
GraphNeuralNetwork
|
Trained GNN model. |
required |
loader |
DataLoader
|
DataLoader for validation/test set. |
required |
device |
device
|
Torch device. |
required |
target_indices |
Sequence[int]
|
Indices of target properties in batch.y. |
required |
Returns:
| Type | Description |
|---|---|
float
|
Mean MSE loss per graph. |
Source code in src/project_name/evaluate.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 | |
evaluate_with_metrics
evaluate_with_metrics(model: GraphNeuralNetwork, loader: DataLoader, device: torch.device, target_indices: Sequence[int]) -> dict[str, float]
Evaluate model on a dataloader with multiple metrics.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model |
GraphNeuralNetwork
|
Trained GNN model. |
required |
loader |
DataLoader
|
DataLoader for validation/test set. |
required |
device |
device
|
Torch device. |
required |
target_indices |
Sequence[int]
|
Indices of target properties in batch.y. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, float]
|
Dictionary with metrics: mse, rmse, mae, r2. |
Source code in src/project_name/evaluate.py
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 | |
get_device
get_device() -> torch.device
Get the best available device for computation.
Source code in src/project_name/evaluate.py
122 123 124 125 126 127 128 | |
main
main(cfg: DictConfig) -> None
Load best model and evaluate on test set with comprehensive metrics.
Source code in src/project_name/evaluate.py
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 | |
model
project_name.model
GraphNeuralNetwork
Bases: Module
Graph Neural Network for molecular property regression.
Source code in src/project_name/model.py
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 | |
__init__
__init__(num_node_features: int = 11, num_edge_features: int = 4, hidden_dim: int = 128, num_layers: int = 3, output_dim: int = 1, dropout: float = 0.1) -> None
Initialize the GNN model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
num_node_features |
int
|
Number of node (atom) features. |
11
|
num_edge_features |
int
|
Number of edge (bond) features. |
4
|
hidden_dim |
int
|
Number of hidden channels. |
128
|
num_layers |
int
|
Number of GraphConv layers. |
3
|
output_dim |
int
|
Output dimension (1 for single property regression). |
1
|
dropout |
float
|
Dropout rate for regularization. |
0.1
|
Source code in src/project_name/model.py
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 | |
forward
forward(data) -> torch.Tensor
Forward pass through the model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data |
PyTorch Geometric Data object with x, edge_index, and batch attributes. |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
Predicted property values. |
Source code in src/project_name/model.py
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 | |
profiling
project_name.profiling
Profiling utilities for training and evaluation.
TrainingProfiler
Manages profiling across entire training session.
Source code in src/project_name/profiling.py
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 | |
__init__
__init__(enabled: bool = False, output_dir: Optional[Path] = None, warmup_steps: int = 1, active_steps: int = 10, repeat_steps: int = 1) -> None
Initialize the training profiler.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
enabled |
bool
|
Whether to enable profiling. |
False
|
output_dir |
Optional[Path]
|
Directory to save profiling results. |
None
|
Source code in src/project_name/profiling.py
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 | |
finalize
finalize() -> None
Finalize profiling and export trace.
Source code in src/project_name/profiling.py
57 58 59 60 61 | |
step
step() -> None
Record a step (epoch) in the profiler.
Source code in src/project_name/profiling.py
52 53 54 55 | |
timing_checkpoint
timing_checkpoint(name: str, enabled: bool = True) -> Generator
Context manager for simple timing measurements.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name |
str
|
Name for this checkpoint. |
required |
enabled |
bool
|
Whether to enable timing. |
True
|
Yields:
| Type | Description |
|---|---|
Generator
|
Dictionary with timing results. |
Source code in src/project_name/profiling.py
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 | |
prune
project_name.prune
apply_unstructured_pruning
apply_unstructured_pruning(model: torch.nn.Module, amount: float) -> dict[str, Any]
Apply unstructured L1 pruning to FC layers only, then make it permanent.
Source code in src/project_name/prune.py
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 | |
evaluate_mse
evaluate_mse(model: torch.nn.Module, loader: DataLoader, device: torch.device, target_indices: Sequence[int]) -> float
Mean MSE per graph (matches your train/eval convention).
Source code in src/project_name/prune.py
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 | |
measure_inference_latency
measure_inference_latency(model: torch.nn.Module, loader: DataLoader, device: torch.device, *, warmup_batches: int = 10, timed_batches: int = 50) -> dict[str, float]
Measures average latency per batch (ms) over a fixed number of batches.
Notes: - Uses torch.inference_mode() via @torch.no_grad() + model.eval() - Syncs CUDA for accurate timing
Source code in src/project_name/prune.py
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 | |
quantize
project_name.quantize
measure_inference_latency
measure_inference_latency(model: torch.nn.Module, loader: DataLoader, device: torch.device, *, warmup_batches: int = 10, timed_batches: int = 50) -> dict[str, float]
Average latency per batch in ms. Note: for quantized CPU models this is the typical use case.
Source code in src/project_name/quantize.py
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 | |
quantize_full_model
quantize_full_model(model: torch.nn.Module, scheme: str) -> torch.nn.Module
Apply weight-only INT8 quantization to all linear layers in the model, including those nested inside GraphConv blocks. Uses torchao when available and falls back to the torch.ao dynamic quantization API otherwise.
scheme
- "torchao_int8_weight_only" (default)
- "torch_ao_dynamic" (fallback-style dynamic quantization)
Source code in src/project_name/quantize.py
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 | |
train
project_name.train
train
train(cfg: DictConfig) -> None
Train the GNN model on QM9 dataset.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cfg |
DictConfig
|
Hydra configuration object containing all parameters. |
required |
Source code in src/project_name/train.py
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 | |
train_epoch
train_epoch(model: GraphNeuralNetwork, loader: DataLoader, optimizer: Optimizer, device: torch.device, target_indices: list[int]) -> float
Train for one epoch.
Source code in src/project_name/train.py
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 | |
utils
project_name.utils
Utility functions for data loading and environment detection.
get_data_path
get_data_path(config_path: str | Path, gcs_bucket: str | None = None) -> Path
Get the appropriate data path based on the environment.
In cloud environments (GCP/Vertex AI), data is mounted to /gcs/
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config_path |
str | Path
|
The data path from config (e.g., 'data' or 'data/processed'). |
required |
gcs_bucket |
str | None
|
Optional GCS bucket name. If provided and running in cloud,
will use /gcs/ |
None
|
Returns:
| Type | Description |
|---|---|
Path
|
Path object pointing to the correct data location. |
Source code in src/project_name/utils.py
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | |