engine
orchard.trainer.engine
¶
Core Training and Validation Engines.
Stateless, single-epoch execution kernels consumed by ModelTrainer.
Each function accepts fully-resolved objects (model, loader, criterion,
device) and returns plain Python values — no side-effects on global state.
Features:
- AMP Integration:
torch.autocast+GradScalerfor mixed precision, with automatic device-type resolution (CUDA/CPU). - Gradient Clipping: Per-batch
clip_grad_norm_applied after unscaling when AMP is active, preventing gradient explosions. - MixUp Augmentation: Beta-distribution blending (
mixup_data) with seeded NumPy generator for reproducible regularization. - Divergence Guard:
train_one_epochraisesRuntimeErroron NaN/Inf loss to prevent checkpointing corrupted weights.
Key Functions:
compute_auc: Macro-averaged ROC-AUC with graceful fallback.train_one_epoch: Single training pass with AMP, MixUp, and tqdm progress.validate_epoch: No-grad evaluation returning loss, accuracy, macro AUC, and macro F1.mixup_data: Convex sample blending for data augmentation.
compute_auc(y_true, y_score)
¶
Compute macro-averaged ROC-AUC with graceful fallback.
Handles binary (positive class probability) and multiclass (OvR)
cases. Returns NaN on failure so callers can distinguish
"computation impossible" from "genuinely zero AUC".
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y_true
|
NDArray[Any]
|
Ground truth class indices, shape |
required |
y_score
|
NDArray[Any]
|
Probability distributions, shape |
required |
Returns:
| Type | Description |
|---|---|
float
|
ROC-AUC score, or |
Source code in orchard/trainer/engine.py
train_one_epoch(model, loader, criterion, optimizer, device, mixup_fn=None, scaler=None, grad_clip=0.0, epoch=0, total_epochs=1, use_tqdm=True)
¶
Performs a single full pass over the training dataset.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
Module
|
Neural network architecture to train |
required |
loader
|
DataLoader[Any]
|
Training data provider |
required |
criterion
|
Module
|
Loss function |
required |
optimizer
|
Optimizer
|
Gradient descent optimizer |
required |
device
|
device
|
Hardware target (CUDA/MPS/CPU) |
required |
mixup_fn
|
Callable[..., Any] | None
|
Function to apply MixUp data blending (optional) |
None
|
scaler
|
GradScaler | None
|
PyTorch GradScaler for mixed precision training (optional) |
None
|
grad_clip
|
float | None
|
Max norm for gradient clipping (0 disables) |
0.0
|
epoch
|
int
|
Current epoch index for progress bar |
0
|
total_epochs
|
int
|
Total number of epochs (for progress bar) |
1
|
use_tqdm
|
bool
|
Show progress bar during training |
True
|
Returns:
| Type | Description |
|---|---|
float
|
Average training loss for the epoch |
Source code in orchard/trainer/engine.py
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 | |
validate_epoch(model, val_loader, criterion, device)
¶
Evaluates model performance on held-out validation set.
Computes validation loss, accuracy, and ROC-AUC score under no_grad context. AUC calculated using One-vs-Rest (OvR) strategy with macro-averaging for robust performance estimation on potentially imbalanced datasets.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
Module
|
Neural network model to evaluate |
required |
val_loader
|
DataLoader[Any]
|
Validation data provider |
required |
criterion
|
Module
|
Loss function (e.g., CrossEntropyLoss) |
required |
device
|
device
|
Hardware target (CUDA/MPS/CPU) |
required |
Returns:
| Type | Description |
|---|---|
Mapping[str, float]
|
Validation metrics dict with keys: |
Mapping[str, float]
|
|
Mapping[str, float]
|
|
Mapping[str, float]
|
|
Mapping[str, float]
|
|
Source code in orchard/trainer/engine.py
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 | |
mixup_data(x, y, alpha=1.0, rng=None)
¶
Applies MixUp augmentation by blending two random samples.
MixUp generates convex combinations of training pairs to improve generalization and calibration.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Tensor
|
Input data batch (images) |
required |
y
|
Tensor
|
Target labels batch |
required |
alpha
|
float
|
Beta distribution parameter (0 disables MixUp) |
1.0
|
rng
|
Generator | None
|
NumPy random generator for reproducibility (seeded from config) |
None
|
Returns:
| Type | Description |
|---|---|
tuple[Tensor, Tensor, Tensor, float]
|
4-tuple of (mixed_x, y_a, y_b, lam). |