Training API¶
Complete training pipeline for VAE models with checkpointing and monitoring.
Overview¶
The training module provides high-level functions for:
- Complete VAE training workflow
- Automatic checkpointing
- Training history visualization
- Early stopping
- Learning rate scheduling
Main Training Function¶
train_vae¶
The main training function that orchestrates the entire VAE training process.
train_vae ¶
train_vae(
X_train: ndarray,
X_test: ndarray,
y_train: Optional[ndarray] = None,
y_test: Optional[ndarray] = None,
config: Optional[VAEConfig] = None,
save_dir: Optional[Path] = None,
resume_from: Optional[Path] = None,
force_cpu: bool = False,
) -> Tuple[nn.Module, Dict[str, list]]
Train a VAE model with full checkpointing support.
Args: X_train: Training data (samples × features) - numpy array or pandas DataFrame X_test: Test data (samples × features) - numpy array or pandas DataFrame y_train: Optional training labels for CVAE y_test: Optional test labels for CVAE config: Training configuration save_dir: Directory to save checkpoints resume_from: Optional checkpoint path to resume training force_cpu: Force CPU usage even if CUDA is available (for compatibility)
Returns: Tuple of (trained_model, training_history)
Source code in renalprog/modeling/train.py
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 | |
Key Features¶
Automatic Checkpointing¶
The training function automatically saves:
- Model state dict
- Optimizer state
- Training history
- Configuration parameters
Checkpoints are saved when: - Validation loss improves (best model) - At regular intervals (every checkpoint_every epochs) - After training completes (final model)
Early Stopping¶
Training stops automatically if validation loss doesn't improve for early_stopping_patience epochs. This prevents overfitting and saves computation time.
Learning Rate Scheduling¶
When use_scheduler=True, the learning rate is reduced when validation loss plateaus:
Cyclical KL Annealing¶
The KL divergence weight β is gradually increased using cyclical annealing to prevent posterior collapse:
frange_cycle_linear ¶
frange_cycle_linear(
start: float,
stop: float,
n_epoch: int,
n_cycle: int = 4,
ratio: float = 0.5,
) -> np.ndarray
Generate a linear cyclical schedule for beta hyperparameter.
This creates a cyclical annealing schedule where beta increases linearly from start to stop over a portion of each cycle (controlled by ratio), then stays constant at stop for the remainder of the cycle.
Args: start: Initial value of beta (typically 0.0) stop: Final/maximum value of beta (typically 1.0) n_epoch: Total number of epochs n_cycle: Number of cycles (default: 4) ratio: Ratio of cycle spent increasing beta (default: 0.5) - 0.5 means half cycle increasing, half constant - 1.0 means entire cycle increasing
Returns: Array of beta values for each epoch
Example: >>> # 3 cycles over 300 epochs, beta increases from 0 to 1 over first half of each cycle >>> beta_schedule = frange_cycle_linear(0.0, 1.0, 300, n_cycle=3, ratio=0.5) >>> # Epoch 0-50: beta increases 0.0 -> 1.0 >>> # Epoch 50-100: beta stays at 1.0 >>> # Epoch 100-150: beta increases 0.0 -> 1.0 >>> # Epoch 150-200: beta stays at 1.0 >>> # Epoch 200-250: beta increases 0.0 -> 1.0 >>> # Epoch 250-300: beta stays at 1.0
Source code in renalprog/modeling/train.py
Training History¶
The training function returns a dictionary with:
| Key | Description |
|---|---|
train_loss | Training loss per epoch |
val_loss | Validation loss per epoch |
train_recon | Training reconstruction loss per epoch |
val_recon | Validation reconstruction loss per epoch |
train_kl | Training KL divergence per epoch |
val_kl | Validation KL divergence per epoch |
learning_rates | Learning rate per epoch |
Complete Example¶
import pandas as pd
from pathlib import Path
from renalprog.modeling.train import train_vae
from renalprog.plots import plot_training_history
from renalprog.utils import set_seed, configure_logging
# Configure
configure_logging()
set_seed(42)
# Load data
train_expr = pd.read_csv("data/interim/split/train_expression.tsv", sep="\t", index_col=0)
test_expr = pd.read_csv("data/interim/split/test_expression.tsv", sep="\t", index_col=0)
# Train VAE
history, best_model, checkpoints = train_vae(
train_data=train_expr.values,
val_data=test_expr.values,
input_dim=train_expr.shape[1],
mid_dim=1024,
features=128,
output_dir=Path("models/my_vae"),
n_epochs=100,
batch_size=32,
learning_rate=1e-3,
use_scheduler=True,
use_checkpoint=True,
checkpoint_every=10,
early_stopping_patience=20,
device='cuda'
)
# Plot results
plot_training_history(
history,
output_path=Path("reports/figures/training_history.png")
)
# Load best model for inference
best_model.eval()
import torch
with torch.no_grad():
reconstruction, mu, log_var, z = best_model(
torch.FloatTensor(test_expr.values).to(device)
)
print(f"Best validation loss: {min(history['val_loss']):.4f}")
print(f"Final learning rate: {history['learning_rates'][-1]:.6f}")
Checkpointing API¶
For manual checkpoint management:
checkpointing ¶
Model checkpointing utilities for saving and loading training state.
Classes¶
ModelCheckpointer ¶
ModelCheckpointer(
save_dir: Path,
monitor: str = "val_loss",
mode: str = "min",
save_freq: int = 0,
keep_last_n: int = 3,
)
Handles saving and loading model checkpoints during training.
Features: - Save best model based on validation metric - Save checkpoints every N epochs - Save final model after training - Save training history and configuration - Resume training from checkpoint
Attributes: save_dir: Directory to save checkpoints monitor: Metric to monitor ('loss', 'val_loss', etc.) mode: 'min' for loss, 'max' for accuracy save_freq: Save checkpoint every N epochs (0 = only best) keep_last_n: Keep only last N checkpoints (0 = keep all)
Initialize checkpointer.
Args: save_dir: Directory to save checkpoints monitor: Metric name to monitor mode: 'min' to minimize metric, 'max' to maximize save_freq: Save every N epochs (0 = only save best) keep_last_n: Keep only N most recent checkpoints (0 = all)
Source code in renalprog/modeling/checkpointing.py
Functions¶
get_best_checkpoint_path ¶
Get path to best model checkpoint.
Returns: Path to best model, or None if not saved yet
Source code in renalprog/modeling/checkpointing.py
get_final_checkpoint_path ¶
Get path to final model checkpoint.
Returns: Path to final model, or None if not saved yet
Source code in renalprog/modeling/checkpointing.py
load_checkpoint ¶
load_checkpoint(
checkpoint_path: Path,
model: Module,
optimizer: Optional[Optimizer] = None,
device: str = "cpu",
) -> Dict[str, Any]
Load a checkpoint and restore model state.
Args: checkpoint_path: Path to checkpoint file model: Model to load state into optimizer: Optional optimizer to restore state device: Device to map checkpoint to
Returns: Dictionary with checkpoint information (epoch, metrics, config)
Source code in renalprog/modeling/checkpointing.py
save_checkpoint ¶
save_checkpoint(
epoch: int,
model: Module,
optimizer: Optimizer,
metrics: Dict[str, float],
config: Any,
is_best: bool = False,
is_final: bool = False,
) -> None
Save a training checkpoint.
Args: epoch: Current epoch number model: PyTorch model to save optimizer: Optimizer state to save metrics: Dictionary of current metrics config: Training configuration object is_best: Whether this is the best model so far is_final: Whether this is the final model
Source code in renalprog/modeling/checkpointing.py
should_save_checkpoint ¶
Determine if checkpoint should be saved this epoch.
Args: epoch: Current epoch number
Returns: True if checkpoint should be saved
Source code in renalprog/modeling/checkpointing.py
update_best ¶
Check if current metric is the best and update if so.
Args: epoch: Current epoch number metric_value: Current metric value
Returns: True if this is a new best, False otherwise
Source code in renalprog/modeling/checkpointing.py
Functions¶
load_model_config ¶
Load model configuration from JSON file.
Args: config_path: Path to JSON config file
Returns: Dictionary with configuration
Source code in renalprog/modeling/checkpointing.py
save_model_config ¶
Save model configuration to JSON file.
Args: config: Configuration object save_path: Path to save JSON file
Source code in renalprog/modeling/checkpointing.py
save_checkpoint¶
Save model checkpoint with metadata.
save_model_config ¶
Save model configuration to JSON file.
Args: config: Configuration object save_path: Path to save JSON file
Source code in renalprog/modeling/checkpointing.py
load_checkpoint¶
Load model from checkpoint.
load_model_config ¶
Load model configuration from JSON file.
Args: config_path: Path to JSON config file
Returns: Dictionary with configuration
Source code in renalprog/modeling/checkpointing.py
See Also¶
- Models API - VAE architectures
- Prediction API - Using trained models
- Configuration - Training hyperparameters
- Complete Pipeline Tutorial