Training
The training helpers are optional convenience utilities for routine supervised training around a model you constructed yourself. Dataset splits, optimization schedules, and expected benchmark metrics remain explicit experiment choices.
Solver and backward choices belong to the model configuration. For example,
SolverConfig(backward_mode="unrolled") differentiates through finite solver
steps, while SolverConfig(backward_mode="implicit", backward_solver="gmres")
uses the package DEQ/SILVA adjoint path.
This path follows the DEQ implicit-gradient formulation
[4], with matrix-free GMRES
[13]; training and regularization
choices can also be compared with
[39] and
[6].
For supervised data \((x_i,y_i)\), the helper minimizes a batch objective
Two Usage Modes
Low-level PyTorch remains the most direct path:
model = SILVAGraphPresetNetwork(...)
optimizer = torch.optim.Adam(model.parameters(), lr=0.002)
for batch in train_loader:
logits = model(**batch.model_kwargs())
loss = torch.nn.functional.cross_entropy(logits, batch.y)
loss.backward()
optimizer.step()
The training engine wraps the same model and loaders:
from silva_networks import TrainConfig, fit_supervised
result = fit_supervised(
model,
train_loader,
val_loader,
config=TrainConfig(
task="classification",
epochs=50,
lr=0.002,
weight_decay=1e-5,
gradient_clipping=1.0,
checkpoint_path="runs/checkpoint.pt",
),
)
Supported batch forms are ordinary (x, y) pairs, mappings with x and y
fields, and GraphTensorBatch objects.
Sequence batches use (input, target). Multi-input models such as optical flow
use (*model_inputs, target), for example (image1, image2, target_flow).
Mappings provide the equivalent named-argument route with y, target, or
labels reserved for the supervision tensor.
For objectives that need auxiliary fields or model states, pass step_fn:
def flow_step(model, batch):
image1, image2, target, valid = batch
prediction = model(image1, image2)
loss = silva_endpoint_error(prediction, target, valid)
return loss, prediction, target
result = fit_supervised(model, loader, config=config, step_fn=flow_step)
The callback receives the device-moved batch and must return scalar loss,
prediction, and target tensors. The same callback is accepted by evaluate,
which keeps paper-specific losses outside the general engine.
Scale-Aware Training
TrainConfig supports microbatch accumulation and autocast without changing
the task loss:
config = TrainConfig(
task="regression",
epochs=100,
optimizer="adamw",
gradient_accumulation_steps=4,
mixed_precision="bfloat16",
checkpoint_path="runs/checkpoint.pt",
resume=True,
)
For per-device batch (B), accumulation count (K), and process count (P),
the effective batch is (BKP). A final partial accumulation group is rescaled
to preserve the batch-mean gradient. Distributed wrappers use no_sync() for
intermediate microbatches, and distributed samplers receive the current epoch.
The checkpoint also stores gradient-scaler state when CUDA float16 is active.
Sharded and distributed loader construction is documented in Scaling Data. The complete model/data/training route is in Full-Scale SILVA.
Classification is not restricted to matrix logits. The default
class_dim=-1 supports ordinary (batch, classes) and sequence
(batch, length, classes) outputs. Set class_dim=1 for dense image logits
with shape (batch, classes, height, width). metric_mode selects whether
validation metrics are minimized or maximized; auto maximizes accuracy and
custom metrics and minimizes losses and regression errors.
Pass a custom optimizer, scheduler, loss, metric, and epoch hook directly to
fit_supervised. For tasks with paper-specific multi-term objectives, such as
indexed DEQ-Flow corrections, an ordinary PyTorch loop remains the full-control
route around the same package model.
Training metrics and equilibrium diagnostics answer different questions.
Record loss or accuracy from fit_supervised, and request structured model
results in a custom step_fn when residuals, convergence flags, or backward
linear-solve diagnostics must be retained. The reporting checklist and method
sources are in Citation-Aware Reporting
and Paper and References.
Small supervised training utilities for package-built SILVA experiments.
The helpers in this module are intentionally generic. They do not encode private paper configurations, dataset splits, or expected metrics. They provide the repeatable training chores around a user-specified PyTorch model and data loader: seeding, device movement, loss/metric evaluation, gradient clipping, checkpoint resume, and a compact history object.
EpochMetrics
dataclass
One row in a supervised training history.
Source code in src/silva_networks/training.py
EvaluationResult
dataclass
Aggregate loss and metric values from one evaluation pass.
Source code in src/silva_networks/training.py
TrainConfig
dataclass
Configuration for fit_supervised.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
task
|
TaskName
|
Supervised task family. |
'classification'
|
epochs
|
int
|
Number of epochs to train. |
10
|
lr
|
float
|
Optimizer learning rate. |
0.001
|
weight_decay
|
float
|
Optimizer weight decay. |
0.0
|
optimizer
|
OptimizerName
|
Optimizer family. |
'adam'
|
momentum
|
float
|
SGD momentum. |
0.9
|
loss
|
LossName
|
Loss function. |
'auto'
|
metric
|
MetricName
|
Validation metric. |
'auto'
|
metric_mode
|
MetricMode
|
Whether a larger or smaller validation metric is better.
|
'auto'
|
class_dim
|
int
|
Class-logit axis for classification. The default final axis
handles |
-1
|
gradient_clipping
|
float | None
|
Optional global norm clipping threshold. |
None
|
gradient_accumulation_steps
|
int
|
Number of microbatches per optimizer step. |
1
|
mixed_precision
|
PrecisionName
|
Autocast precision. |
'none'
|
scheduler
|
SchedulerName
|
Learning-rate scheduler family. |
'none'
|
scheduler_step_size
|
int
|
Epoch period for step scheduling. |
10
|
scheduler_gamma
|
float
|
Multiplicative step-scheduler factor. |
0.5
|
device
|
str | device | None
|
PyTorch device string, |
'auto'
|
seed
|
int | None
|
Optional deterministic seed applied before training. |
None
|
deterministic
|
bool
|
Whether to request deterministic PyTorch algorithms. |
False
|
checkpoint_path
|
str | Path | None
|
Optional path for checkpoint save/resume. |
None
|
resume
|
bool
|
Whether to resume from |
False
|
Source code in src/silva_networks/training.py
TrainResult
dataclass
Result returned by fit_supervised.
Source code in src/silva_networks/training.py
evaluate
evaluate(model, data_loader, *, task='classification', loss='auto', metric='auto', loss_fn=None, metric_fn=None, step_fn=None, class_dim=-1, device='auto', mixed_precision='none')
Evaluate a supervised model on an iterable of batches.
Source code in src/silva_networks/training.py
fit_supervised
fit_supervised(model, train_loader, val_loader=None, *, config=None, loss_fn=None, optimizer=None, scheduler=None, metric_fn=None, epoch_hook=None, step_fn=None)
Train a user-constructed PyTorch model on supervised batches.
Batches may be ordinary (x, y) pairs, (*model_inputs, target) tuples,
dictionaries with x/y keys, or GraphTensorBatch objects. Dictionary
and graph batches are passed to models as keyword arguments, which keeps
graph, molecular, flow, and custom SILVA models usable without
package-specific experiment configs.
Source code in src/silva_networks/training.py
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 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 | |
seed_everything
Seed Python, NumPy, PyTorch CPU, and available PyTorch accelerators.
Source code in src/silva_networks/training.py
Where to Go Next
| Question | Page |
|---|---|
| Can I execute fitting, evaluation, checkpointing, and resume? | Training Helpers Validation Notebook |
| What evidence should a trained experiment report? | Reconstructing Paper Experiments |
| Which measured outputs are published? | Results |
| How do I scale data and execution? | Full-Scale SILVA |