LightningModule#
- class braintools.trainer.LightningModule(*args, **kwargs)#
Base class for all training modules.
This class provides a PyTorch Lightning-like interface for defining models that work with the Trainer class. Users should subclass this and implement at minimum
training_stepandconfigure_optimizers.- Parameters:
None
Examples
Basic usage:
>>> import braintools >>> import brainstate >>> import jax.numpy as jnp >>> >>> class MyModel(braintools.trainer.LightningModule): ... def __init__(self, input_size, hidden_size, output_size): ... super().__init__() ... self.linear1 = brainstate.nn.Linear(input_size, hidden_size) ... self.linear2 = brainstate.nn.Linear(hidden_size, output_size) ... ... def __call__(self, x): ... x = jax.nn.relu(self.linear1(x)) ... return self.linear2(x) ... ... def training_step(self, batch, batch_idx): ... x, y = batch['x'], batch['y'] ... logits = self(x) ... loss = jnp.mean((logits - y) ** 2) ... self.log('train_loss', loss) ... return {'loss': loss} ... ... def configure_optimizers(self): ... return braintools.optim.Adam(lr=1e-3)
See also
TrainerThe training orchestration class.
- configure_optimizers()[source]#
Configure optimizer(s) and learning rate scheduler(s).
Override this method to define your optimization setup.
- Return type:
Optimizer|Tuple[Optimizer,LRScheduler] |Tuple[List[Optimizer],List[LRScheduler]] |Dict[str,Any]- Returns:
Optimizer – A single optimizer.
Tuple[Optimizer, LRScheduler] – An optimizer and a learning rate scheduler.
Tuple[List[Optimizer], List[LRScheduler]] – Multiple optimizers and schedulers.
Dict[str, Any] – A dictionary with ‘optimizer’ and optionally ‘lr_scheduler’ keys.
Examples
Simple optimizer:
>>> def configure_optimizers(self): ... return braintools.optim.Adam(lr=1e-3)
Optimizer with scheduler:
>>> def configure_optimizers(self): ... optimizer = braintools.optim.Adam(lr=1e-2) ... scheduler = braintools.optim.StepLR(base_lr=1e-2, step_size=10) ... return optimizer, scheduler
Multiple optimizers (e.g., for GANs):
>>> def configure_optimizers(self): ... opt_g = braintools.optim.Adam(lr=1e-4) ... opt_d = braintools.optim.Adam(lr=4e-4) ... return [opt_g, opt_d], []
- freeze(names=None)[source]#
Freeze parameters so they are not updated during training.
brainstate.ParamStatehas norequires_gradflag, so freezing is recorded by name on the module. TheTrainerreads these names when it sets up training and excludes the corresponding states from both gradient computation and optimizer updates. Call this beforetrainer.fit(model).- Parameters:
names (
str|List[str] |None) – Parameter name(s) to freeze. IfNone(default), all parameters are frozen. Names correspond to the keys ofmodel.states(brainstate.ParamState).
See also
unfreezeReverse the effect of this method.
Examples
>>> model.freeze() # freeze everything >>> model.unfreeze('decoder.bias') # then re-enable one parameter
- log(name, value, prog_bar=False, logger=True, on_step=True, on_epoch=False, reduce_fx='mean', sync_dist=False)[source]#
Log a single metric.
- Parameters:
name (
str) – Name of the metric.value (
Any) – Value to log. Should be a scalar or JAX array.prog_bar (
bool) – Whether to show this metric in the progress bar.logger (
bool) – Whether to log to the logger(s).on_step (
bool) – Whether to log at each step.on_epoch (
bool) – Whether to log at epoch end (accumulated).reduce_fx (
str) – Reduction function for epoch-level metrics (‘mean’, ‘sum’, ‘min’, ‘max’).sync_dist (
bool) – Whether to synchronize across devices in distributed training.
Examples
>>> self.log('train_loss', loss, prog_bar=True) >>> self.log('val_acc', accuracy, on_step=False, on_epoch=True)
- log_dict(metrics, prog_bar=False, logger=True, on_step=True, on_epoch=False, reduce_fx='mean', sync_dist=False)[source]#
Log multiple metrics at once.
- Parameters:
metrics (
Dict[str,Any]) – Dictionary of metric names to values.prog_bar (
bool) – Whether to show these metrics in the progress bar.logger (
bool) – Whether to log to the logger(s).on_step (
bool) – Whether to log at each step.on_epoch (
bool) – Whether to log at epoch end (accumulated).reduce_fx (
str) – Reduction function for epoch-level metrics.sync_dist (
bool) – Whether to synchronize across devices in distributed training.
Examples
>>> self.log_dict({'val_loss': loss, 'val_acc': acc}, prog_bar=True)
- on_validation_batch_end(outputs, batch, batch_idx)[source]#
Called at the end of each validation batch.
- on_validation_batch_start(batch, batch_idx)[source]#
Called at the beginning of each validation batch.
- predict_step(batch, batch_idx)[source]#
Compute predictions for a single batch.
Override this method to define your prediction logic.
- test_step(batch, batch_idx)[source]#
Compute test metrics for a single batch.
Override this method to define your test logic.
- training_step(batch, batch_idx)[source]#
Compute the training loss for a single batch.
Override this method to define your training logic.
- Parameters:
- Returns:
A dictionary with at least a ‘loss’ key, or a TrainOutput instance. The loss will be used for gradient computation.
- Return type:
Dict[str,Any] |TrainOutput
Examples
>>> def training_step(self, batch, batch_idx): ... x, y = batch['x'], batch['y'] ... logits = self(x) ... loss = cross_entropy(logits, y) ... self.log('train_loss', loss, prog_bar=True) ... return {'loss': loss}
- unfreeze(names=None)[source]#
Unfreeze parameters so they are trained again.
- Parameters:
names (
str|List[str] |None) – Parameter name(s) to unfreeze. IfNone(default), all parameters are unfrozen.
See also
freezeMark parameters as non-trainable.
- validation_step(batch, batch_idx)[source]#
Compute validation metrics for a single batch.
Override this method to define your validation logic.
- Parameters:
- Returns:
A dictionary of metrics, an EvalOutput instance, or None.
- Return type:
Dict[str,Any] |EvalOutput|None
Examples
>>> def validation_step(self, batch, batch_idx): ... x, y = batch['x'], batch['y'] ... logits = self(x) ... loss = cross_entropy(logits, y) ... acc = (logits.argmax(-1) == y).mean() ... self.log_dict({'val_loss': loss, 'val_acc': acc}) ... return {'val_loss': loss, 'val_acc': acc}