Trainer Module
bnode_core.ode.trainer
Neural ODE and Balanced Neural ODE Training Module.
This module provides the main training pipeline for Neural ODE (NODE) and Balanced Neural ODE (BNODE) models. It handles model initialization, multi-phase training, validation, testing, and MLflow experiment tracking.
Architecture Support
The trainer automatically detects and supports two model architectures:
- Neural ODE (NODE): Direct neural differential equation models.
- Balanced Neural ODE (BNODE): Latent-space ODE models with encoder-decoder architecture for improved training stability and representation learning.
Training Pipeline Overview
The training process follows these stages:
-
Model Instantiation
- Automatically detects NODE vs BNODE from config
- Initializes normalization layers using dataset statistics
- Sets up device (CPU/CUDA) based on availability and config
-
Pre-training (Optional, NODE only)
- Can be enabled in config:
nn_model.training.pre_train=true - Trains on state derivatives (
state_der) if present in dataset - Uses collocation method for initial parameter estimation
- Not supported for BNODE models (No latent states gradients available, but you can mock this behavior by using a short main training phase with states_grad_loss)
- Can be enabled in config:
-
Multi-Phase Main Training
- Configured as a list in
nn_model.training.main_training - Each phase can have different hyperparameters:
- Solver type (euler, rk4, dopri5, etc.)
- Learning rate, batch size, sequence length
- Early stopping patience and threshold
- See
resources/config/nn_model/bnode_pytest.yamlfor an example
- Configured as a list in
-
Final Testing
- Evaluates model on all dataset splits (train/val/test)
- Optionally saves predictions and internal variables to dataset
- Logs final metrics to MLflow
Key Training Features
Compatibility with NODE and BNODE
- Trainer auto-detects model type from config
- Both models provide a consistent training interface with
e.g. the
model_and_loss_evaluationmethod.
Adaptive Batch Processing
Each epoch processes a specified number of batches (not entire dataset).
Configured via nn_model.training.main_training[i].batches_per_epoch.
NaN Recovery
- If NaN loss detected, automatically reloads last checkpoint
- Reduces gradient clipping norm to stabilize training
- Note: LR scheduling might be a better long-term solution
Reparameterization Control (BNODE)
- Training uses active reparameterization (variational inference)
- When evaluating (validation/test, or at final test for all datasets), reparameterization is disabled. Also for deterministic mode.
- Ensures consistent evaluation metrics
Progressive Sequence Length Increase
- When switching phases, sequence length gradually increases
- Initial test with final sequence length to assess extrapolation
- Training sequence length increases gradually (controlled by
seq_len_increase_in_batches) - Validation/test always use full sequence length to monitor extrapolation performance
- Early abort if stable extrapolation achieved:
loss_train < 2 * loss_validationfor N consecutive epochs (seq_len_increase_abort_after_n_stable_epochs)
MLflow Integration
- Logs metrics at end of each phase:
{metric}_{context}_job{phase}_final - Final test metrics logged as:
{metric}_final - All Hydra outputs and trained models saved as artifacts
- Experiment tracking with run name, parameters, and tags
Typical Usage Examples
As other modules of the bnode_core package, we use Hydra for configuration management.
Basic training with default config:
uv run trainer nn_model=latent_ode_base dataset_name=myDataset
Training with custom model configuration:
uv run trainer nn_model=myCustomModel dataset_name=myDataset \
mlflow_experiment_name=my_experiment \
nn_model.network.lat_states_dim=1024 \
Hyperparameter sweep (multi-run mode):
uv run trainer \
nn_model=latent_ode_base \
dataset_name=myDataset \
nn_model.training.beta_start_override=0.1,0.01,0.001 \
-m
Override specific training parameters:
uv run trainer \
nn_model=latent_ode_base \
dataset_name=myDataset \
nn_model.training.lr_start_override=1e-4 \
nn_model.training.batch_size_override=512 \
use_cuda=false
View available configuration options (from Hydra):
uv run trainer --help
Configuration
For detailed configuration options, see:
- Config Documentation: Consult the Config section of the documentation
- Config Files: examples in
resources/config/nn_model/directory - Config Schema:
bnode_core.configmodule for all available parameters - Search Tip: Use Ctrl+F in config files to find specific parameter behavior
Command Line Interface
The trainer is registered as a UV script in pyproject.toml, enabling direct
execution via uv run trainer. All Hydra config parameters can be overridden
via command line using dot notation.
Notes
- CUDA is automatically used if available (override with
use_cuda=false) - Model checkpoints saved after each phase:
model_phase_{i}.pt - Failed artifact logging tracked in
could_not_log_artifacts.txt - Supports mixed precision training (AMP) when enabled
- Early stopping based on validation loss with configurable patience
See Also
bnode_core.config : Configuration schemas and validation bnode_core.ode.node.node_architecture : Neural ODE model implementation bnode_core.ode.bnode.bnode_architecture : Balanced Neural ODE model implementation bnode_core.nn.nn_utils.load_data : Dataset loading utilities
initialize_model(cfg: train_test_config_class, train_dataset: TimeSeriesDataset, hdf5_dataset: hdf5_dataset_class, initialize_normalization=True, model_type: str = None)
Initialize and configure NODE or BNODE model with dataset statistics.
Automatically detects model type from config and initializes normalization layers using training dataset statistics. Handles device placement (CPU/CUDA) and copies model architecture file to Hydra output directory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cfg
|
train_test_config_class
|
Validated Hydra configuration. |
required |
train_dataset
|
TimeSeriesDataset
|
Training dataset for normalization. |
required |
hdf5_dataset
|
Dataset
|
HDF5 dataset handle for statistics. |
required |
initialize_normalization
|
bool
|
Whether to initialize normalization layers from dataset statistics. Defaults to True. |
True
|
model_type
|
str
|
Force specific model type ('node' or 'bnode'). If None, auto-detects from config. Defaults to None. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
model |
Module
|
Initialized model (NeuralODE or BalancedNeuralODE) moved to appropriate device. |
Side Effects
- Modifies cfg.use_cuda based on availability
- Copies model architecture source file to Hydra output directory
- Logs device and parameter count information
Notes
- CUDA is used if available and cfg.use_cuda=True
- Normalization uses training set statistics only
- Model type detection based on network class in config
Source code in src/bnode_core/ode/trainer.py
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 | |
train_all_phases(cfg: train_test_config_class)
Execute complete multi-phase training pipeline with MLflow tracking.
Main orchestration function that coordinates:
- Dataset loading
- Model initialization
- Optional pre-training (NODE only)
- Multi-phase main training
- Final testing and evaluation
- MLflow artifact logging
The function processes a job list consisting of optional pre-training, multiple main training phases, and final testing. Each phase can have different hyperparameters and training strategies.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cfg
|
train_test_config_class
|
Validated Hydra configuration containing: - dataset_path, dataset_name: Dataset location and identifier - nn_model.training.pre_train: Enable pre-training (NODE only) - nn_model.training.main_training: List of training phase configs - nn_model.training.test: Enable final testing - use_cuda: Device preference - mlflow_experiment_name: MLflow experiment name |
required |
Side Effects
- Creates/updates model checkpoints: model_phase_{i}.pt
- Logs metrics, parameters, and artifacts to MLflow
- Saves predictions to dataset if configured
- Copies Hydra outputs to MLflow artifacts
- Creates could_not_log_artifacts.txt on logging failures
Training Flow
- Load HDF5 dataset and log to MLflow
- Build job list (pre-train, main phases, test)
- For each job:
- Initialize/reload dataloaders if needed
- Initialize/load model if needed
- Execute training or testing
- Save checkpoint and log metrics
- Copy all outputs to MLflow artifacts
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If CUDA memory errors occur repeatedly |
FileNotFoundError
|
If dataset or checkpoint files missing |
Notes
- Decorated with @log_hydra_to_mlflow for automatic config logging
- Memory errors trigger dataloader recreation with adjusted settings
- NaN losses trigger checkpoint reload and gradient clipping adjustment
- Progressive sequence length increase during phase transitions
See Also
train_one_phase : Single training phase execution initialize_model : Model instantiation and initialization
Source code in src/bnode_core/ode/trainer.py
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 | |
main()
Entry point for (B)NODE training via Hydra CLI.
Initializes Hydra configuration system and launches train_all_phases with validated config. Auto-detects config directory and uses 'train_test_ode' as the default config name.
This function is registered as 'trainer' in pyproject.toml, enabling command-line execution via::
uv run trainer [config_overrides]
Examples:
See module docstring for usage examples.
Side Effects
- Registers config store with Hydra
- Auto-detects config directory from filepaths
- Launches Hydra-decorated train_all_phases