Learner¶
Learner and TbpttLearner — pure-PyTorch training loop.
Learner ¶
Learner(model: Module, dls: DataLoaders, loss_func: Callable, metrics: list[Callable] | None = None, lr: float = 0.003, opt_func: type = torch.optim.Adam, transforms: list | None = None, augmentations: list | None = None, aux_losses: list | None = None, n_skip: int = 0, grad_clip: float | None = None, plot_fn: Callable | None = None, device: device | None = None, show_bar: bool = True)
Pure-PyTorch training loop for time-series models.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
Module
|
the model to train |
required |
dls
|
DataLoaders
|
train/valid/test DataLoaders |
required |
loss_func
|
Callable
|
primary loss function |
required |
metrics
|
list[Callable] | None
|
list of metric functions |
None
|
lr
|
float
|
default learning rate |
0.003
|
opt_func
|
type
|
optimizer class |
Adam
|
transforms
|
list | None
|
list of |
None
|
augmentations
|
list | None
|
list of |
None
|
aux_losses
|
list | None
|
list of |
None
|
n_skip
|
int
|
number of initial time steps to skip in loss computation |
0
|
grad_clip
|
float | None
|
maximum gradient norm (None disables clipping) |
None
|
plot_fn
|
Callable | None
|
plotting function for show_batch/show_results |
None
|
device
|
device | None
|
target device (auto-detected if None) |
None
|
show_bar
|
bool
|
whether to show tqdm progress bars |
True
|
Source code in tsfast/training/learner.py
no_bar ¶
Suppress tqdm progress bars (useful for Ray Tune).
setup ¶
Create optimizer, move model to device, setup composables.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lr
|
float | None
|
learning rate (uses self.lr if None) |
None
|
scheduler_fn
|
Callable | None
|
factory |
None
|
n_epoch
|
int | None
|
total epochs — required when scheduler_fn is provided |
None
|
Enables manual training loops without calling fit().
Source code in tsfast/training/learner.py
save_model ¶
save ¶
Save entire learner state for training resume.
Pickles everything except dls (DataLoaders cannot be serialized).
If pickling fails (e.g. lambda loss functions), use
save_checkpoint / load_checkpoint instead.
Source code in tsfast/training/learner.py
load
classmethod
¶
Load a saved learner to resume training.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
checkpoint file saved by |
required |
dls
|
DataLoaders
|
DataLoaders (must match the original training data layout) |
required |
Source code in tsfast/training/learner.py
save_checkpoint ¶
Save model weights, optimizer state, and training history.
Fallback for learners with unpicklable components (e.g. lambda losses).
Use load_checkpoint to restore into a manually constructed Learner.
Source code in tsfast/training/learner.py
load_checkpoint ¶
Load model weights, optimizer state, and training history.
Restores state saved by save_checkpoint into this Learner.
Source code in tsfast/training/learner.py
prepare_batch ¶
Device transfer + transforms + augmentations (if training).
Source code in tsfast/training/learner.py
compute_loss ¶
Primary loss with n_skip + auxiliary losses.
Source code in tsfast/training/learner.py
backward_step ¶
Backward + grad_clip + optimizer step + zero_grad.
Source code in tsfast/training/learner.py
training_step ¶
Forward + compute_loss + NaN check + backward_step.
Returns:
| Type | Description |
|---|---|
float
|
loss value, or NaN if loss was NaN (step is skipped) |
Source code in tsfast/training/learner.py
train_one_epoch ¶
Run one training epoch.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pbar
|
optional tqdm progress bar |
None
|
|
epoch
|
int
|
current epoch index (0-based) |
0
|
n_epoch
|
int
|
total number of epochs |
1
|
Returns:
| Type | Description |
|---|---|
float
|
mean training loss for the epoch |
Source code in tsfast/training/learner.py
validate ¶
Run validation and compute loss + metrics on concatenated predictions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dl
|
DataLoader to evaluate (defaults to validation set) |
None
|
|
chunk_sz
|
int | None
|
forwarded to :meth: |
None
|
Returns:
| Type | Description |
|---|---|
tuple[float, dict[str, float]]
|
(val_loss, {metric_name: value}) |
Source code in tsfast/training/learner.py
fit ¶
Train for n_epoch epochs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_epoch
|
int
|
number of epochs |
required |
lr
|
float | None
|
learning rate (uses self.lr if None) |
None
|
scheduler_fn
|
Callable | None
|
factory |
None
|
Source code in tsfast/training/learner.py
fit_flat_cos ¶
Convenience: flat LR then cosine decay.
log_epoch ¶
Log epoch results. Override for custom logging.
Source code in tsfast/training/learner.py
get_preds ¶
Batch-concatenated predictions and targets.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dl
|
DataLoader to evaluate (defaults to validation set) |
None
|
|
with_inputs
|
bool
|
if True, also return concatenated inputs |
False
|
chunk_sz
|
int | None
|
when set, split each batch's sequence into chunks of this size along the time axis and forward them sequentially, carrying model state across chunks (for RNNs). Keeps GPU memory bounded for very long sequences. |
None
|
Source code in tsfast/training/learner.py
get_worst ¶
Inputs, targets, and predictions for the samples with highest loss.
Returns:
| Type | Description |
|---|---|
tuple[Tensor, Tensor, Tensor]
|
(inputs, targets, predictions) sliced to the |
Source code in tsfast/training/learner.py
show_batch ¶
Plot a batch of input/target pairs.
Source code in tsfast/training/learner.py
show_results ¶
Plot predictions vs targets.
Source code in tsfast/training/learner.py
show_worst ¶
Plot samples with highest per-sample loss.
Source code in tsfast/training/learner.py
TbpttLearner ¶
Bases: Learner
Learner with truncated backpropagation through time (TBPTT).
Full sequences are loaded from the DataLoader, then split into
sub-sequences of sub_seq_len. Hidden state is carried across
sub-sequences within a batch but reset between batches.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sub_seq_len
|
int
|
length of each sub-sequence chunk |
required |
Source code in tsfast/training/learner.py
training_step ¶
TBPTT training step: chunk input, forward/backward per chunk with carried state.
Source code in tsfast/training/learner.py
get_preds ¶
Defaults chunk_sz to sub_seq_len so validation reuses CUDA graph shapes.