neuralogic.nn.trainer packageο
Submodulesο
neuralogic.nn.trainer.callbacks moduleο
- class CheckpointCallback(directory: str | Path, filename: str = 'best.pkl')[source]ο
Bases:
TrainerCallbackSave the model whenever validation loss improves.
- Parameters:
directory (str or Path) β Directory to save checkpoints into (created if missing).
filename (str) β Filename for the checkpoint file (default
"best.pkl").
- on_epoch_end(trainer: Trainer, epoch: int, logs: dict[str, Any]) None[source]ο
Called after every epoch.
- Parameters:
trainer (Trainer) β The trainer instance (access
trainer.model, etc.).epoch (int) β 0-indexed epoch number that just finished.
logs (dict) β Dictionary with keys
"train_loss","val_loss"(if available),"lr", and per-metric keys like"train_accuracy","val_mae", etc.
- property path: Pathο
- class EarlyStoppingCallback(patience: int, min_delta: float = 0.0)[source]ο
Bases:
TrainerCallbackStop training when validation loss stops improving.
- Parameters:
patience (int) β Number of epochs with no improvement after which training stops.
min_delta (float) β Minimum absolute change to qualify as an improvement.
- on_epoch_end(trainer: Trainer, epoch: int, logs: dict[str, Any]) None[source]ο
Called after every epoch.
- Parameters:
trainer (Trainer) β The trainer instance (access
trainer.model, etc.).epoch (int) β 0-indexed epoch number that just finished.
logs (dict) β Dictionary with keys
"train_loss","val_loss"(if available),"lr", and per-metric keys like"train_accuracy","val_mae", etc.
- class ProgressCallback(epochs: int)[source]ο
Bases:
TrainerCallbackShow a tqdm progress bar during training.
- Parameters:
epochs (int) β Total number of epochs (used for progress bar length).
- on_epoch_end(trainer: Trainer, epoch: int, logs: dict[str, Any]) None[source]ο
Called after every epoch.
- Parameters:
trainer (Trainer) β The trainer instance (access
trainer.model, etc.).epoch (int) β 0-indexed epoch number that just finished.
logs (dict) β Dictionary with keys
"train_loss","val_loss"(if available),"lr", and per-metric keys like"train_accuracy","val_mae", etc.
- class TrainerCallback[source]ο
Bases:
objectBase class for training callbacks.
Override any of the hooks. The trainer calls them in the order they were passed to
Trainer.fit().- on_epoch_end(trainer: Trainer, epoch: int, logs: dict[str, Any]) None[source]ο
Called after every epoch.
- Parameters:
trainer (Trainer) β The trainer instance (access
trainer.model, etc.).epoch (int) β 0-indexed epoch number that just finished.
logs (dict) β Dictionary with keys
"train_loss","val_loss"(if available),"lr", and per-metric keys like"train_accuracy","val_mae", etc.
neuralogic.nn.trainer.helpers moduleο
neuralogic.nn.trainer.history moduleο
- class TrainerHistory(train_losses: list[float] = <factory>, val_losses: list[float] = <factory>, train_metrics: dict[str, list[float]]=<factory>, val_metrics: dict[str, list[float]]=<factory>, learning_rates: list[float] = <factory>, best_epoch: int = 0, best_val_loss: float = inf, stopped_early: bool = False)[source]ο
Bases:
objectTraining history collected during a
Trainer.fit()run.- train_lossesο
Mean training loss per epoch.
- Type:
list[float]
- val_lossesο
Mean validation loss per epoch (empty if no validation set).
- Type:
list[float]
- train_metricsο
Per-epoch extra metrics on the training set (each key maps to a list of epoch-level means).
- Type:
dict[str, list[float]]
- val_metricsο
Per-epoch extra metrics on the validation set.
- Type:
dict[str, list[float]]
- learning_ratesο
Learning rate at each epoch.
- Type:
list[float]
- best_epochο
Epoch (0-indexed) that achieved the lowest validation loss.
- Type:
int
- best_val_lossο
Lowest validation loss observed.
- Type:
float
- stopped_earlyο
Trueif early stopping fired.- Type:
bool
- best_epoch: int = 0ο
- best_val_loss: float = infο
- learning_rates: list[float]ο
- stopped_early: bool = Falseο
- train_losses: list[float]ο
- train_metrics: dict[str, list[float]]ο
- val_losses: list[float]ο
- val_metrics: dict[str, list[float]]ο
neuralogic.nn.trainer.metrics moduleο
- class Metric(value)[source]ο
Bases:
str,EnumEnum of available metric names.
Inherits
strso members can be used directly where a string is expected:>>> Metric.ACCURACY == "accuracy" True >>> trainer.fit(..., metrics=[Metric.ACCURACY, Metric.F1_MACRO])
- ACCURACY = 'accuracy'ο
- F1_MACRO = 'f1_macro'ο
- MAE = 'mae'ο
- MSE = 'mse'ο
- PRECISION_MACRO = 'precision_macro'ο
- R2 = 'r2'ο
- RECALL_MACRO = 'recall_macro'ο
- RMSE = 'rmse'ο
- compute_metrics(targets: list, outputs: list, names: Sequence[str | Metric]) dict[str, float][source]ο
Compute named metrics over a batch of (target, output) pairs.
Each metric receives the full batch and returns a single float.
- Parameters:
targets (list) β Per-sample target values (floats, lists, or 2D lists).
outputs (list) β Per-sample output values (same shapes as targets).
names (Sequence[str or Metric]) β Metric names to compute, e.g.
["accuracy"]or[Metric.MAE, Metric.R2].
- Returns:
Mapping from metric name to its value across the batch.
- Return type:
dict[str, float]
neuralogic.nn.trainer.trainer moduleο
- class Trainer(module: NeuralModule)[source]ο
Bases:
object- fit(train_dataset: Dataset | GroundedDataset | BuiltDataset, val_dataset: Dataset | GroundedDataset | BuiltDataset | None = None, *, epochs: int = 1, batch_size: int = 1, early_stopping_patience: int | None = None, min_delta: float = 0.0, checkpoint_dir: str | Path | None = None, metrics: Sequence[str | Metric] | None = None, silent: bool = False, callbacks: Sequence[TrainerCallback] | None = None) TrainerHistory[source]ο
Run the training loop.
- Parameters:
train_dataset β Training data. Raw
Datasetobjects are built automatically; pass aBuiltDatasetto skip repeated grounding.val_dataset β Optional validation data. When provided, validation loss (and any requested metrics) are computed after every epoch. Early stopping and checkpointing depend on validation loss.
epochs (int) β Number of epochs to train. Default 1.
batch_size (int) β Batch size when building raw datasets. Default 1.
early_stopping_patience (int or None) β Stop after this many epochs without validation-loss improvement. Requires
val_dataset. DefaultNone(no early stopping).min_delta (float) β Minimum absolute change in validation loss to count as improvement. Default 0.0.
checkpoint_dir (str, Path, or None) β Directory to save the best model (by validation loss). A file named
best.pklis written on every improvement. DefaultNone(no checkpointing).metrics (Sequence[str or Metric] or None) β Extra metrics to compute, e.g.
[Metric.ACCURACY]or["mae", "r2"]. Loss is always tracked. DefaultNone.silent (bool) β If
True, suppress the tqdm progress bar. DefaultFalse.callbacks (Sequence[TrainerCallback] or None) β Additional callbacks to invoke. Built-in callbacks (early stopping, checkpoint, progress) are appended automatically based on the other arguments.
- Returns:
Losses and metrics for every epoch.
- Return type:
- test(dataset: Dataset | GroundedDataset | BuiltDataset, *, batch_size: int = 1) list[source]ο
Evaluate the model on a dataset (no weight updates).
- Parameters:
dataset β Test data. Raw
Datasetobjects are built automatically.batch_size (int) β Batch size when building raw datasets. Default 1.
- Returns:
Model outputs for every sample.
- Return type:
list
Module contentsο
- class CheckpointCallback(directory: str | Path, filename: str = 'best.pkl')[source]ο
Bases:
TrainerCallbackSave the model whenever validation loss improves.
- Parameters:
directory (str or Path) β Directory to save checkpoints into (created if missing).
filename (str) β Filename for the checkpoint file (default
"best.pkl").
- on_epoch_end(trainer: Trainer, epoch: int, logs: dict[str, Any]) None[source]ο
Called after every epoch.
- Parameters:
trainer (Trainer) β The trainer instance (access
trainer.model, etc.).epoch (int) β 0-indexed epoch number that just finished.
logs (dict) β Dictionary with keys
"train_loss","val_loss"(if available),"lr", and per-metric keys like"train_accuracy","val_mae", etc.
- property path: Pathο
- class EarlyStoppingCallback(patience: int, min_delta: float = 0.0)[source]ο
Bases:
TrainerCallbackStop training when validation loss stops improving.
- Parameters:
patience (int) β Number of epochs with no improvement after which training stops.
min_delta (float) β Minimum absolute change to qualify as an improvement.
- on_epoch_end(trainer: Trainer, epoch: int, logs: dict[str, Any]) None[source]ο
Called after every epoch.
- Parameters:
trainer (Trainer) β The trainer instance (access
trainer.model, etc.).epoch (int) β 0-indexed epoch number that just finished.
logs (dict) β Dictionary with keys
"train_loss","val_loss"(if available),"lr", and per-metric keys like"train_accuracy","val_mae", etc.
- class Metric(value)[source]ο
Bases:
str,EnumEnum of available metric names.
Inherits
strso members can be used directly where a string is expected:>>> Metric.ACCURACY == "accuracy" True >>> trainer.fit(..., metrics=[Metric.ACCURACY, Metric.F1_MACRO])
- ACCURACY = 'accuracy'ο
- F1_MACRO = 'f1_macro'ο
- MAE = 'mae'ο
- MSE = 'mse'ο
- PRECISION_MACRO = 'precision_macro'ο
- R2 = 'r2'ο
- RECALL_MACRO = 'recall_macro'ο
- RMSE = 'rmse'ο
- class ProgressCallback(epochs: int)[source]ο
Bases:
TrainerCallbackShow a tqdm progress bar during training.
- Parameters:
epochs (int) β Total number of epochs (used for progress bar length).
- on_epoch_end(trainer: Trainer, epoch: int, logs: dict[str, Any]) None[source]ο
Called after every epoch.
- Parameters:
trainer (Trainer) β The trainer instance (access
trainer.model, etc.).epoch (int) β 0-indexed epoch number that just finished.
logs (dict) β Dictionary with keys
"train_loss","val_loss"(if available),"lr", and per-metric keys like"train_accuracy","val_mae", etc.
- class Trainer(module: NeuralModule)[source]ο
Bases:
object- fit(train_dataset: Dataset | GroundedDataset | BuiltDataset, val_dataset: Dataset | GroundedDataset | BuiltDataset | None = None, *, epochs: int = 1, batch_size: int = 1, early_stopping_patience: int | None = None, min_delta: float = 0.0, checkpoint_dir: str | Path | None = None, metrics: Sequence[str | Metric] | None = None, silent: bool = False, callbacks: Sequence[TrainerCallback] | None = None) TrainerHistory[source]ο
Run the training loop.
- Parameters:
train_dataset β Training data. Raw
Datasetobjects are built automatically; pass aBuiltDatasetto skip repeated grounding.val_dataset β Optional validation data. When provided, validation loss (and any requested metrics) are computed after every epoch. Early stopping and checkpointing depend on validation loss.
epochs (int) β Number of epochs to train. Default 1.
batch_size (int) β Batch size when building raw datasets. Default 1.
early_stopping_patience (int or None) β Stop after this many epochs without validation-loss improvement. Requires
val_dataset. DefaultNone(no early stopping).min_delta (float) β Minimum absolute change in validation loss to count as improvement. Default 0.0.
checkpoint_dir (str, Path, or None) β Directory to save the best model (by validation loss). A file named
best.pklis written on every improvement. DefaultNone(no checkpointing).metrics (Sequence[str or Metric] or None) β Extra metrics to compute, e.g.
[Metric.ACCURACY]or["mae", "r2"]. Loss is always tracked. DefaultNone.silent (bool) β If
True, suppress the tqdm progress bar. DefaultFalse.callbacks (Sequence[TrainerCallback] or None) β Additional callbacks to invoke. Built-in callbacks (early stopping, checkpoint, progress) are appended automatically based on the other arguments.
- Returns:
Losses and metrics for every epoch.
- Return type:
- test(dataset: Dataset | GroundedDataset | BuiltDataset, *, batch_size: int = 1) list[source]ο
Evaluate the model on a dataset (no weight updates).
- Parameters:
dataset β Test data. Raw
Datasetobjects are built automatically.batch_size (int) β Batch size when building raw datasets. Default 1.
- Returns:
Model outputs for every sample.
- Return type:
list
- class TrainerCallback[source]ο
Bases:
objectBase class for training callbacks.
Override any of the hooks. The trainer calls them in the order they were passed to
Trainer.fit().- on_epoch_end(trainer: Trainer, epoch: int, logs: dict[str, Any]) None[source]ο
Called after every epoch.
- Parameters:
trainer (Trainer) β The trainer instance (access
trainer.model, etc.).epoch (int) β 0-indexed epoch number that just finished.
logs (dict) β Dictionary with keys
"train_loss","val_loss"(if available),"lr", and per-metric keys like"train_accuracy","val_mae", etc.
- class TrainerHistory(train_losses: list[float] = <factory>, val_losses: list[float] = <factory>, train_metrics: dict[str, list[float]]=<factory>, val_metrics: dict[str, list[float]]=<factory>, learning_rates: list[float] = <factory>, best_epoch: int = 0, best_val_loss: float = inf, stopped_early: bool = False)[source]ο
Bases:
objectTraining history collected during a
Trainer.fit()run.- train_lossesο
Mean training loss per epoch.
- Type:
list[float]
- val_lossesο
Mean validation loss per epoch (empty if no validation set).
- Type:
list[float]
- train_metricsο
Per-epoch extra metrics on the training set (each key maps to a list of epoch-level means).
- Type:
dict[str, list[float]]
- val_metricsο
Per-epoch extra metrics on the validation set.
- Type:
dict[str, list[float]]
- learning_ratesο
Learning rate at each epoch.
- Type:
list[float]
- best_epochο
Epoch (0-indexed) that achieved the lowest validation loss.
- Type:
int
- best_val_lossο
Lowest validation loss observed.
- Type:
float
- stopped_earlyο
Trueif early stopping fired.- Type:
bool
- best_epoch: int = 0ο
- best_val_loss: float = infο
- learning_rates: list[float]ο
- stopped_early: bool = Falseο
- train_losses: list[float]ο
- train_metrics: dict[str, list[float]]ο
- val_losses: list[float]ο
- val_metrics: dict[str, list[float]]ο
- compute_metrics(targets: list, outputs: list, names: Sequence[str | Metric]) dict[str, float][source]ο
Compute named metrics over a batch of (target, output) pairs.
Each metric receives the full batch and returns a single float.
- Parameters:
targets (list) β Per-sample target values (floats, lists, or 2D lists).
outputs (list) β Per-sample output values (same shapes as targets).
names (Sequence[str or Metric]) β Metric names to compute, e.g.
["accuracy"]or[Metric.MAE, Metric.R2].
- Returns:
Mapping from metric name to its value across the batch.
- Return type:
dict[str, float]