Training¶
hqnn_forge.training ¶
hqnn_forge.training¶
A minimal, model-agnostic train/validate loop with early stopping.
Exported symbols
train_model Mini-batch training with per-epoch validation and early stopping. TrainingHistory Per-epoch record returned by train_model. EpochRecord One epoch of that record. SPSA Gradient-free optimiser: two loss evaluations per step, for shot-based training.
SPSA ¶
Bases: Optimizer
SPSA: two loss evaluations per step, independent of the parameter count.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
params
|
Iterable[Tensor] | Iterable[dict[str, Any]]
|
Parameters or parameter groups, as for any |
required |
lr
|
float
|
|
0.1
|
perturbation
|
float
|
|
0.1
|
alpha
|
float
|
Decay exponents of the two sequences; the defaults 0.602 and 0.101 are Spall's practical choices (asymptotically optimal: 1 and 1/6). |
0.602
|
gamma
|
float
|
Decay exponents of the two sequences; the defaults 0.602 and 0.101 are Spall's practical choices (asymptotically optimal: 1 and 1/6). |
0.602
|
stability
|
float
|
|
0.0
|
generator
|
Generator | None
|
Source of the |
None
|
gradient_optimizer
|
Optimizer | None
|
An optimiser over parameters that act after the circuit (see The
classical head above), disjoint from |
None
|
model
|
Module | None
|
The model the parameters belong to. When given, the shot sampling of
its devices is synchronised between the two evaluations of a step
(see Common random numbers). Default |
None
|
Attributes:
| Name | Type | Description |
|---|---|---|
gradient_free |
bool
|
True: |
generator
instance-attribute
¶
generator = generator if generator is not None else torch.Generator().manual_seed(torch.initial_seed())
gradient_estimate ¶
gradient_estimate(closure: Closure) -> list[torch.Tensor]
One SPSA gradient estimate at the current parameters, without a step.
In the order of the parameters that require grad, group by group.
Uses two loss evaluations and one draw from generator.
step ¶
step(closure: Closure | None = None) -> float
One SPSA step. Returns the mean of the two loss evaluations, an estimate of the loss at the parameters the step started from.
Raises:
| Type | Description |
|---|---|
ValueError
|
Without a |
EpochRecord
dataclass
¶
Statistics for one epoch.
TrainingHistory
dataclass
¶
What train_model did.
Attributes:
| Name | Type | Description |
|---|---|---|
epochs |
list[EpochRecord]
|
One |
monitor |
str
|
The monitored quantity. |
best_epoch |
int | None
|
1-based epoch with the best monitored value, or |
best_value |
float | None
|
The monitored value at |
best_threshold |
float | None
|
Decision threshold at |
stopped_early |
bool
|
|
temperature |
float | None
|
The |
restored_best |
bool
|
|
train_model ¶
train_model(model: Module, loss_fn: LossFn, optimizer: Optimizer, X_train: Tensor, y_train: Tensor, X_val: Tensor | None = None, y_val: Tensor | None = None, *, max_epochs: int = 100, batch_size: int = 256, monitor: str = 'mcc', patience: int | None = 10, min_delta: float = 0.0, restore_best: bool = True, generator: Generator | None = None, on_epoch_end: Callable[[EpochRecord], None] | None = None) -> TrainingHistory
Train model with mini-batches, validating and early-stopping per epoch.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
Module
|
Any module mapping |
required |
loss_fn
|
LossFn
|
|
required |
optimizer
|
Optimizer
|
Optimiser already bound to the parameters to train. A gradient-free
one ( |
required |
X_train
|
Tensor
|
Training split. For a multiclass model every label of |
required |
y_train
|
Tensor
|
Training split. For a multiclass model every label of |
required |
X_val
|
Tensor | None
|
Validation split. Without it the loop runs |
None
|
y_val
|
Tensor | None
|
Validation split. Without it the loop runs |
None
|
max_epochs
|
int
|
Upper bound on the number of epochs. Default: 100. |
100
|
batch_size
|
int
|
Mini-batch size. The last batch may be smaller, but for
|
256
|
monitor
|
str
|
|
'mcc'
|
patience
|
int | None
|
Stop after this many consecutive epochs without an improvement larger
than |
10
|
min_delta
|
float
|
Minimum change that counts as an improvement. Default: 0.0. |
0.0
|
restore_best
|
bool
|
Load the weights of the best epoch before returning. Default: True. |
True
|
generator
|
Generator | None
|
Generator for the per-epoch shuffle, for reproducible batch order. |
None
|
on_epoch_end
|
Callable[[EpochRecord], None] | None
|
Called with each |
None
|
Returns:
| Type | Description |
|---|---|
TrainingHistory
|
|
Notes
Training runs under train_mode: a
submodule the caller put in eval mode -- a frozen batch-norm layer, say --
stays in eval mode, with its statistics untouched, unless the whole model
arrived in eval mode, which is then trained in train mode throughout.
Validation runs in eval mode through eval_mode. Every epoch starts
from the modes training began with, so an on_epoch_end callback that
puts the model in eval mode does not carry over into the next epoch. On
return every submodule has the mode it had on entry.