One YAML. One command. Full research pipeline.
Config-driven experiment pipeline with dual logging, real-time TUI monitor, and AI agent skills.
| Problem | Solution |
|---|---|
| Config errors discovered after hours of GPU time | preflight runs 1-batch forward+backward in seconds |
| Rewriting training loops for every project | Callback-based loop — extend without modifying the core |
| "Which logging do I use?" | Choose wandb or tui per config — CSV always saved |
| Can't see training progress without W&B | Rust TUI monitor renders loss curves in real-time from CSV |
| Manual hyperparameter tuning | Optuna + PFL pruner prunes unpromising trials early |
| HPO is a black box after it finishes | hpo-report shows parameter importance, boundary warnings, per-trial seed spread, and caveats |
| The best HPO value is optimistic (winner's curse) | hpo-finalize re-trains the top trials on fresh seeds (or K-fold CV), selects on val, tests only the selected trial |
| A seed-fragile config wins the study | seed_aggregate: mean_std or worst scores trials by their worse seeds; hpo-finalize flags unstable candidates |
| Validation loss reused for selection and reporting | Three-way (train, val, test) split; evaluate --split test for the final number |
| Silent overfitting or exploding gradients | Auto-detected by callbacks, logged to W&B/TUI/CSV |
| "It worked on my machine" | Full provenance: Python / PyTorch / CUDA / GPU / git hash |
git clone https://github.com/Axect/pytorch_template.git && cd pytorch_template
# Install (uv recommended)
uv venv && source .venv/bin/activate
uv pip install -U torch wandb rich beaupy numpy optuna matplotlib \
scienceplots typer tqdm pyyaml pytorch-optimizer pytorch-scheduler \
scikit-learn # scikit-learn: Optuna's fANOVA parameter importance (hpo-report)
# Check your environment
python -m cli doctor
# Validate → Preview → Train → Analyze → Evaluate on the held-out test split
python -m cli preflight configs/run_template.yaml
python -m cli preview configs/run_template.yaml
python -m cli train configs/run_template.yaml --device cuda:0
python -m cli analyze
python -m cli evaluate --split testproject: MyProject
device: cuda:0
wandb: false # W&B logging on/off (terminal + CSV always on)
net: model.MLP # any importlib-resolvable path
optimizer: pytorch_optimizer.SPlus # template default (alternative: torch.optim.AdamW)
scheduler: pytorch_scheduler.ExpHyperbolicLRScheduler # (alternative: CosineAnnealingLR)
criterion: torch.nn.MSELoss
data: recipes.regression.data.load_data # plug in any load_data() here
metrics: [mae, r2] # extra val metrics, logged as val_mae, val_r2
seeds: [89, 231, 928, 814, 269] # multi-seed reproducibility
epochs: 50
batch_size: 256
net_config:
nodes: 64
layers: 4
optimizer_config:
lr: 3.e-1
eps: 1.e-10
scheduler_config:
total_steps: 50
upper_bound: 400 # fixed schedule geometry, not tuned
min_lr: 1.e-5All module paths are resolved via importlib. Three layers of validation run before a single GPU cycle is consumed:
- Structural — format checks, non-empty seeds, positive epochs/batch_size
- Runtime — CUDA availability, all import paths resolve
- Semantic —
upper_bound >= total_stepsfor hyperbolic schedulers,T_max == epochsfor cosine, lr positivity, unique seeds
The wandb field (bool) controls whether runs also go to Weights & Biases; terminal output, metrics.csv and latest_model.pt are always written:
wandb: |
Display | W&B | CSV | latest_model.pt |
|---|---|---|---|---|
true |
W&B dashboard + every-epoch terminal output | Yes | Always | Always |
false |
Every-epoch terminal output (agent-friendly) | No | Always | Always |
CSV and latest model are always saved, regardless of logging mode. This means:
- Agents can read
metrics.csvandlatest_model.ptmid-training - The TUI monitor can render loss curves from any run
- No data is lost even without W&B
The training loop emits events; behaviors are independent, priority-ordered callbacks:
| Callback | Priority | Purpose |
|---|---|---|
NaNDetectionCallback |
5 | Detect NaN/Inf loss, signal stop |
OptimizerModeCallback |
10 | SPlus / ScheduleFree train/eval toggle |
GradientMonitorCallback |
12 | Track gradient norms, warn on explosion |
LossPredictionCallback |
70 | Predict final loss via shifted exponential fit |
OverfitDetectionCallback |
75 | Detect train/val divergence |
WandbLoggingCallback |
80 | Log to W&B (when wandb: true) |
TUILoggingCallback |
80 | Terminal logging (always active) |
CSVLoggingCallback |
81 | Write metrics.csv every epoch (always active) |
PrunerCallback |
85 | Report to Optuna pruner |
EarlyStoppingCallback |
90 | Patience-based stopping |
BestWeightsCallback |
93 | Keep the best-epoch weights by monitor in best_weights.pt (when restore_best_weights or HPO objective: best) |
CheckpointCallback |
95 | Periodic + best-model checkpoints |
LatestModelCallback |
96 | Save full-state latest_model.pt every epoch (always active, enables --resume) |
Add your own by subclassing TrainingCallback — zero changes to the training loop:
class GradientClipCallback(TrainingCallback):
priority = 15 # runs right after GradientMonitorCallback
def on_train_step_end(self, trainer, **kwargs):
torch.nn.utils.clip_grad_norm_(trainer.model.parameters(), 1.0)The LossPredictionCallback fits a shifted exponential decay model to the validation loss history:
L(t) = a · exp(-b · t) + c
and evaluates it at the last epoch of the run (t = epochs - 1), logged as predicted_final_loss. The fit is a least-squares fit to the raw tail of the curve (the last max(10, ceil(2n/3)) of the n epochs so far), which:
- Solves
(a, c)in closed form for each rateband searchesbon a log grid in[1/epochs, 2]with golden-section refinement - Recovers a noise-free exponential tail exactly (the earlier EMA + 3-anchor fit overestimated the final loss early in training)
- Works with positive and negative losses, and with increasing (overfitting) curves
- Returns raw loss values (same units as input)
The prediction is for reporting only. On real HPO studies it was an unbiased estimate of the final loss, but pruning on extrapolated values still cut true top trials, so the pruner compares same-epoch values instead (below).
A Rust-based terminal UI reads metrics.csv and renders live charts:
Features:
- Loss curves (train/val) with Braille sub-pixel rendering
- Learning rate schedule and gradient norm history
- Predicted final loss overlay
- Log scale toggle:
log₁₀for positive data,symlog₁₀for mixed-sign - Status bar with current metrics and time since last update
- 1.2 MB static binary — no runtime dependencies
Usage:
# Build once (requires Rust toolchain)
cd tools/monitor && cargo build --release && cd ../..
# Run alongside training (in a separate terminal)
python -m cli monitor # auto-detect latest run
python -m cli monitor runs/MyProject/group/42/metrics.csv # specific file
# Or run the binary directly
./tools/monitor/target/release/training-monitor runs/MyProject/group/42/| Key | Action |
|---|---|
q / Esc |
Quit |
l |
Toggle log scale |
← / → |
Switch metric tabs (when custom metrics are logged) |
The same binary supports real-time HPO monitoring by reading the Optuna SQLite database:
python -m cli monitor --hpo # auto-detects .db fileFour tabs: Overview (trial scatter + best convergence), Parameters (per-parameter scatter grid), Best Trial (training curves of current best), Trials (interactive table — select a row and press Enter to view its curves).
| Key | Action |
|---|---|
+ / - |
Y-axis zoom in/out |
↑ / ↓ |
Y-axis pan (or row selection in Trials tab) |
r |
Reset Y axis to auto |
x |
Toggle X-axis log (Parameters tab) |
See Chapter 4: HPO — Monitoring in Real-time for details.
Catches problems in seconds — not after hours of GPU time:
Pre-flight Check
┌─────────────────────────┬────────┬──────────────────────────────────┐
│ Check │ Status │ Detail │
├─────────────────────────┼────────┼──────────────────────────────────┤
│ Import paths & device │ PASS │ │
│ Semantic validation │ PASS │ │
│ Object instantiation │ PASS │ │
│ Data loading │ PASS │ train=8000, val=1000, test=1000 │
│ Forward pass │ PASS │ output=(256, 1), loss=0.512341 │
│ Shape check │ PASS │ │
│ Gradient check │ PASS │ grad norm=0.034821 │
│ Optimizer step │ PASS │ │
│ Scheduler step │ PASS │ │
│ GPU memory │ PASS │ peak=42.3 MB (1 batch) │
└─────────────────────────┴────────┴──────────────────────────────────┘
All pre-flight checks passed.
Use --json for machine-readable output (used by AI agent skills for automated parsing). If the data function returns only (train, val), preflight WARNs that there is no held-out test split.
# Run HPO
python -m cli train configs/my_run.yaml --optimize-config configs/my_opt.yaml
# Analyze results
python -m cli hpo-report --opt-config configs/my_opt.yaml
# Re-train the top 3 trials on 5 fresh seeds; select on val, report test
python -m cli hpo-finalize configs/my_run.yaml configs/my_opt.yaml --top-k 3 --n-seeds 5The PFL pruner (pruner.PFLPruner) prunes a trial only when it is worse, at the same epoch of the same seed, than every one of the top-k completed trials, and only at epochs that pass a rank check: over the completed trials, the Spearman correlation between the value at that epoch and the final value must be at least rank_rho_min (default 0.8). How early the ranking settles varies by problem (at epoch 5 the correlation was 0.15, 0.85 and 0.22 on three real HPO studies), so the rank check replaces a fixed warmup fraction; n_warmup_epochs is only a hard minimum. In offline replays of those studies, pruning on the predicted final loss cut all 3 true top-3 trials in one setting, while the same-epoch rule cut none and was never worse across 7 settings. The default TPE sampler runs with multivariate, group, and constant_liar enabled.
Study: my_study (MyProject_Opt.db)
Trials: 50 total, 38 completed, 11 pruned, 1 failed
Best Trial #23
Value: 0.003241
Parameter Importance
┌─────────────────────────┬──────────────────────────────────────┐
│ Parameter │ Importance │
├─────────────────────────┼──────────────────────────────────────┤
│ optimizer_config_lr │ 0.8741 ██████████████████████████ │
│ net_config_layers │ 0.1259 ████ │
└─────────────────────────┴──────────────────────────────────────┘
Boundary Warnings:
optimizer_config_lr=0.912 at UPPER boundary [1e-3, 1e+0]
A boundary warning means the optimizer would benefit from a wider search range; for log: true parameters the 5% margin is measured in log space. The top-k table also lists each trial's seed standard deviation, and a Caveats list flags importances that could not be computed (with the error, e.g. scikit-learn missing; previously they were silently empty), unstable importances (fewer than 30 completed trials), and a best-vs-runner-up gap under 2 standard errors.
The study's best value is the best over many noisy trials on the same seeds and validation split, so it is optimistic. hpo-finalize re-trains the top-k completed trials with seeds the study never used (project <project>_Final), scores each on validation with the study's metric and seed aggregation (--cv-folds K uses K-fold cross-validation over train+val instead), and selects the best score. Only the selected trial is evaluated on the test split (mean ± 95% CI), so the test split cannot influence the choice. The table also shows each candidate's optimism (positive = the HPO value was optimistic) and worst-seed spread, with seed-fragile candidates flagged UNSTABLE. The report is written to runs/<project>_Final/finalize_<study>.json.
The HPO objective can be any logged metric: set metric: val_r2 with direction: maximize in the optimize config (the run config must list r2 in metrics:), and seed_aggregate: mean | mean_std | worst to control how seeds combine into the trial value.
This template ships with built-in agent skills that guide the full experiment lifecycle across Claude Code, Codex, and Forge:
You: "Set up HPO for my FluxNet model, version 0.3"
Agent: Creates configs/SolarFlux_v0.3/fluxnet_run.yaml
Creates configs/SolarFlux_v0.3/fluxnet_opt.yaml
Runs preflight to catch any config issues
Launches HPO with SPlus + ExpHyperbolicLR defaults
Runs hpo-report to analyze results
Runs hpo-finalize to re-check the top trials on fresh seeds
Extracts the selected params → fluxnet_best.yaml
Launches final multi-seed training
Reports the held-out test loss with evaluate
The skill encodes domain knowledge: correct lr ranges for SPlus (1e-3 to 1e+0; 1e-2 to 1e+0 for MLPs like the template's), why total_steps must not be synced to HPO epochs for hyperbolic schedulers, when to use the AdamW + cosine alternative (fixed-horizon runs, small regression problems), and how to interpret boundary warnings.
See
skills/pytorch-train/for details.
If you have a project based on an older version of this template, the pytorch-migrate skill can detect your current version and apply incremental updates automatically.
Install skills globally (once per agent):
python -m cli update-skills --agent claude # install to ~/.claude/skills
python -m cli update-skills --agent codex # install to ~/.codex/skills
python -m cli update-skills --agent forge # install to ~/forge/skills
python -m cli update-skills --agent claude --copy # copy instead of symlinkUse in any project:
cd ~/my-project # any pytorch_template-based project
# In your agent:
/pytorch-migrateThe skill detects which features are missing (v1 through v6) and applies only the needed migrations, preserving your custom models, data loaders, and callbacks.
Custom Model
# my_model.py
class MyTransformer(nn.Module):
def __init__(self, hparams: dict, device: str = "cpu"):
super().__init__()
self.d_model = hparams["d_model"]net: my_model.MyTransformer
net_config:
d_model: 256
nhead: 8Custom Loss Function
criterion: my_losses.FocalLoss
criterion_config:
gamma: 2.0
alpha: 0.25Custom Data
Create a module with a load_data() function that returns (train_dataset, val_dataset, test_dataset):
# recipes/myproject/data.py
def load_data():
return train_dataset, val_dataset, test_datasetThe validation split drives early stopping, checkpoints, pruning, and HPO selection. The test split is used only by evaluate and hpo-finalize. A function returning (train_dataset, val_dataset) still works, but then there is no unbiased final estimate.
data: recipes.myproject.data.load_dataSee recipes/regression/ and recipes/classification/ for complete examples.
Custom Metrics
metrics: [mse, mae, r2, my_module.MyMetric] # built-ins: mse, mae, r2, accuracyEach metric is computed once per epoch on the whole validation set and logged as val_<name> in metrics.csv and W&B. evaluate and analyze report the same metrics. Any of them can drive training and HPO: monitor: val_r2 (early stopping, with mode: max), checkpoint_config.monitor, and the optimize config's metric (with direction: maximize). Each metric class declares greater_is_better; contradicting modes or directions are rejected. The registry can also be used directly:
from metrics import MetricRegistry
registry = MetricRegistry(["mse", "mae", "r2", "my_module.MyMetric"])
results = registry.compute(y_pred, y_true)pytorch_template/
├── cli.py # CLI: train, preflight, validate, preview, doctor, analyze, evaluate, hpo-report, hpo-finalize, monitor
├── config.py # RunConfig (frozen, 3-tier validation) + OptimizeConfig
├── util.py # Trainer, run(), predict_final_loss(), evaluate_group(), finalize_study()
├── callbacks.py # 13 built-in callbacks + CallbackRunner
├── checkpoint.py # CheckpointManager + SeedManifest
├── provenance.py # Environment capture + config hashing
├── pruner.py # PFL pruner for Optuna
├── metrics.py # Metric registry (MSE, MAE, R2, accuracy)
├── model.py # Built-in MLP
├── configs/ # YAML config templates
├── recipes/ # Example recipes (regression, classification)
├── tools/monitor/ # Rust TUI monitor (ratatui)
├── tests/ # Unit tests
├── docs/ # Human Skill Guide
└── skills/ # Agent skills (pytorch-train, pytorch-migrate)
runs/{project}/{group}/{seed}/
├── model.pt # Final model state_dict (last epoch; best epoch by monitor with restore_best_weights or objective: best)
├── latest_model.pt # Full-state checkpoint, refreshed every epoch (always-on; resume entry point)
├── best_weights.pt # Best-epoch weights by monitor (only with restore_best_weights or objective: best)
├── metrics.csv # Real-time CSV log (all metrics)
├── env_snapshot.yaml # Environment metadata
├── run_metadata.yaml # Training metadata
├── best.pt # Best-by-val_loss full checkpoint (if checkpoint_config.enabled)
└── checkpoint_epoch_*.pt # Periodic snapshots, last K kept (if checkpoint_config.enabled)
| Command | Description |
|---|---|
train <config> [--device DEV] [--optimize-config OPT] [--resume] |
Train or run HPO; --resume continues each seed from latest_model.pt |
preflight <config> [--device DEV] [--json] |
1-batch forward+backward check |
validate <config> |
Structural + runtime config validation |
preview <config> |
Show model architecture and param count |
doctor |
Check Python, PyTorch, CUDA, wandb, packages |
hpo-report [--db DB] [--opt-config OPT] [--top-k K] [--json] |
HPO analysis: param importance, boundary warnings, per-trial seed std, caveats |
hpo-finalize <config> <opt-config> [--top-k K] [--n-seeds N] [--seeds a,b] [--cv-folds K] [--device DEV] [--json] |
Re-train the top-k HPO trials on fresh seeds or K-fold CV; select on val, test only the selected trial (± 95% CI) |
evaluate [--project P] [--group G] [--split train|val|test] [--device DEV] [--json] |
Evaluate every seed of a group on a split (default test): loss + metrics, mean ± std, 95% CI |
analyze [--project P] [--group G] [--seed S] |
Validation loss + metrics of one trained seed (config's criterion) |
monitor [PATH] [--interval MS] [--list] |
Launch real-time TUI monitor (or list available runs) |
update-skills [--agent AGENT] [--copy] [--uninstall] |
Install/update agent skills for Claude, Codex, or Forge |
All commands are invoked via python -m cli <command>.
| AI Agent Skill | Human Guide | |
|---|---|---|
| Location | skills/pytorch-train/ |
docs/ |
| Teaches | Config rules, param ranges, CLI commands | Design decisions, trade-offs, workflow intuition |
Read the Human Skill Guide — 5 chapters covering the full pipeline.
- pytorch-optimizer — optimizers including SPlus
- pytorch-scheduler — schedulers including ExpHyperbolicLR
- Optuna — hyperparameter optimization framework
- ratatui — Rust TUI framework for the training monitor

