Training with Lightning¶
timber.lightning wraps the Hugging Face models in PyTorch Lightning modules. The wrappers
add the training loop, the optimiser and schedule, the metrics, and the loading and export of weights. The model
itself stays a plain transformers model, so you can always take it out with module.model.
The modules¶
| Class | Wraps | Use it to |
|---|---|---|
TimberPretrainingModule |
TimberForPretraining |
learn the representation with the pretraining objectives |
TimberFinetuningModule |
TimberForPrediction |
train a head, optionally with pretraining decoders |
Both take the model configuration, the optimisation settings and, when training from scratch, the initial channel embeddings:
from timber.lightning import TimberFinetuningModule, TimberPretrainingModule
module = TimberPretrainingModule(
config, # TimberConfig: the architecture
training={"learning_rate": 1e-4, "max_epochs": 30}, # TimberTrainingConfig fields
channel_embedding_init=None, # or an array of shape (num_channels, channel_embedding_dim)
)
Optimisation¶
TimberTrainingConfig holds the optimisation settings. It is not saved with the model; it is kept in the Lightning
checkpoint.
| Field | Default | Meaning |
|---|---|---|
learning_rate |
1e-4 | AdamW learning rate of the backbone. |
weight_decay |
1e-2 | AdamW weight decay; biases and norm weights are not decayed. |
head_learning_rate |
None |
Learning rate of the head, if different. |
latents_learning_rate |
None |
Learning rate of the latents, if different. |
warmup_ratio |
0.1 | Fraction of the steps with a linear warm-up, then a cosine decay. |
max_epochs |
30 | Number of epochs. |
grad_norm_log_interval |
50 | How often the gradient norm is logged, in steps. |
compile |
False |
Compile the attention layers with torch.compile. |
Gradient clipping is set on the trainer (gradient_clip_val). Lightning refuses to clip the gradients of a fused
optimiser under mixed precision, so the optimiser is not fused when clipping is on.
Training¶
from lightning.pytorch import Trainer
from timber.device import default_precision
trainer = Trainer(max_epochs=30, precision=default_precision(), gradient_clip_val=5.0)
trainer.fit(module, datamodule=datamodule)
The default precision is bf16-mixed on CUDA and MPS and 32-true on CPU. Losses and metrics are computed in
float32.
Finetuning¶
TimberFinetuningModule can start from a pretrained backbone, from a Hugging Face folder or a Hub id, or from a
Lightning checkpoint of these modules:
module = TimberFinetuningModule(finetune_config, training={"learning_rate": 2e-5, "head_learning_rate": 2e-4})
module.load_pretrained("my-timber") # a Hugging Face folder or Hub id
module.freeze_parameters(["timber.tokenizer", "timber.contextualizer", "timber.encoder.blocks.0"])
load_pretrained(source, discard=(...))loads the weights that match.discardlists the prefixes not to load, such as the pretraining decoders, which a finetuning model does not have.freeze_parameters(patterns)freezes the parameters whose names start with a pattern. Frozen modules are kept ineval()mode during training, so their dropout is off and they run without autograd when the whole front end is frozen.
Saving¶
module.export_pretrained("my-timber") # config.json and model.safetensors
The folder loads back with TimberModel.from_pretrained("my-timber") (or TimberForPrediction, TimberForPretraining
for the other tasks), and with AutoModel.from_pretrained after import timber.
Reference¶
timber.lightning.base ¶
Shared Lightning logic: training/validation steps, optimiser groups, schedule, pretrained loading.
The Lightning modules are thin wrappers around the Hugging Face models of
modeling_timber (self.model). Their checkpoints store the model
configuration and the TimberTrainingConfig as hyper-parameters, so
load_from_checkpoint rebuilds them, and TimberLightningModule.export_pretrained
writes a Hugging Face folder.
TimberTrainingConfig
dataclass
¶
Optimisation settings (saved in the Lightning checkpoint, not in config.json).
Attributes:
| Name | Type | Description |
|---|---|---|
learning_rate |
float
|
Learning rate of the backbone and the decoders. |
weight_decay |
float
|
AdamW weight decay (biases and norm weights are not decayed). |
head_learning_rate |
float | None
|
Learning rate of the finetuning head ( |
head_weight_decay |
float | None
|
Weight decay of the head ( |
latents_learning_rate |
float | None
|
Learning rate of the encoder latents and CLS token, which then get no
weight decay. |
warmup_ratio |
float
|
Fraction of the steps with a linear warm-up, followed by a cosine decay. |
max_epochs |
int
|
Number of epochs (passed to the Lightning |
grad_norm_log_interval |
int
|
Log the gradient norms every N optimiser steps ( |
compile |
bool
|
|
from_dict
classmethod
¶
from_dict(
values: dict | TimberTrainingConfig | None,
) -> TimberTrainingConfig
Build a config from a mapping; unknown keys raise.
TimberLightningModule ¶
Bases: LightningModule
Base class of the TIMBER Lightning modules.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_config
|
TimberConfig | dict
|
|
required |
training
|
TimberTrainingConfig | dict | None
|
|
None
|
channel_embedding_init
|
Any
|
Optional initial channel embedding (array or |
None
|
forward_batch ¶
forward_batch(batch: tuple, stage: str)
Run the model on a batch and return its output.
training_step ¶
training_step(batch: tuple, batch_idx: int) -> torch.Tensor
One optimisation step: logs the losses and returns the total loss.
validation_step ¶
validation_step(
batch: tuple, batch_idx: int
) -> torch.Tensor
One validation step: logs the losses and the metrics.
test_step ¶
test_step(batch: tuple, batch_idx: int) -> torch.Tensor
One test step: logs the losses and the metrics.
unpack
staticmethod
¶
unpack(
batch: tuple,
) -> tuple[
torch.Tensor, SamplePositions, torch.Tensor | None
]
Split a batch into the signal, the positions and the labels.
on_train_epoch_start ¶
on_train_epoch_start() -> None
Give the epoch to the sampler (also when it is wrapped in a BatchSampler).
on_before_optimizer_step ¶
on_before_optimizer_step(optimizer: Optimizer) -> None
Log the gradient norm every grad_norm_log_interval steps.
parameter_roles ¶
parameter_roles() -> dict[
str, list[tuple[str, torch.nn.Parameter]]
]
Trainable parameters by role: backbone (incl. decoders), latents, head.
parameter_groups ¶
parameter_groups() -> list[dict]
Optimiser parameter groups: backbone, head and latents, with their learning rates.
configure_optimizers ¶
configure_optimizers() -> dict
AdamW with a linear warm-up then a cosine decay (warmup_ratio).
load_pretrained ¶
load_pretrained(
source: str | Path,
discard: Sequence[str] = (),
strict: bool = False,
) -> dict[str, list[str]]
Load pretrained weights into self.model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
str | Path
|
A Hugging Face folder or Hub id, or a checkpoint of these Lightning modules. |
required |
discard
|
Sequence[str]
|
Parameter-name prefixes (of |
()
|
strict
|
bool
|
Fail on missing or unexpected keys. |
False
|
Returns:
| Type | Description |
|---|---|
dict[str, list[str]]
|
|
freeze_parameters ¶
freeze_parameters(patterns: Sequence[str]) -> list[str]
Freeze the parameters of self.model whose names start with one of patterns.
Patterns are module prefixes, e.g. timber.tokenizer, timber.contextualizer,
timber.encoder.blocks.0. The frozen modules also stay in eval mode during training (no
dropout), see train. Returns the names of the frozen parameters.
frozen_modules ¶
frozen_modules() -> list[torch.nn.Module]
The modules of self.model frozen by freeze_parameters.
train ¶
train(mode: bool = True)
Set the training mode, keeping the frozen modules in eval mode (fixed features, no dropout).
export_pretrained ¶
export_pretrained(
output_dir: str | Path, **kwargs: Any
) -> None
Save self.model as a Hugging Face folder (config.json + model.safetensors).
cosine_schedule_with_warmup ¶
cosine_schedule_with_warmup(
optimizer: Optimizer,
warmup_steps: int,
total_steps: int,
) -> LambdaLR
Linear warm-up then half-cosine decay to 0 (same as transformers.get_cosine_schedule_with_warmup).
load_pretrained_state_dict ¶
load_pretrained_state_dict(
source: str | Path,
) -> dict[str, torch.Tensor]
State dict in the layout of the new models (timber.*, objectives.*, head.*).
timber.lightning.pretraining ¶
Lightning module for pretraining (TimberForPretraining).
TimberPretrainingModule ¶
Bases: TimberLightningModule
Pretraining with the objectives of config.decoders (TACO forecasting, reconstruction).
Logs {train,val}/loss and {train,val}/loss_<objective> (weighted terms).
forward_batch ¶
forward_batch(
batch: tuple, stage: str
) -> TimberPretrainingOutput
Run the pretraining model on a batch (see TimberLightningModule.forward_batch).
timber.lightning.finetuning ¶
Lightning module for finetuning (TimberForPrediction).
TimberFinetuningModule ¶
Bases: TimberLightningModule
Finetuning of a regression or classification head (optionally with decoders, e.g. TACO).
Behaviour kept from the original implementation:
- validation and test use late fusion (entity-level predictions), whatever
fusion_stage; - default learning rates: head
5 x, latents and CLS token/ 5(no weight decay); - epoch metrics
{train,val}_mae,_mse,_pearson(mean over outputs) for regression and{train,val}_auc,_accuracyfor classification.
forward_batch ¶
forward_batch(
batch: tuple, stage: str
) -> TimberPredictionOutput
Run the finetuning model on a batch (see TimberLightningModule.forward_batch).
on_train_epoch_end ¶
on_train_epoch_end() -> None
Compute and log the training metrics of the epoch.
on_validation_epoch_end ¶
on_validation_epoch_end() -> None
Compute and log the validation metrics of the epoch.