qewton.optim.trainer package

Module contents

Subpackages

Submodules

qewton.optim.trainer.base_trainer module

Base trainer implementation for optimization workflows.

This module defines the Trainer class, which controls the execution of one or multiple optimization phases, manages callbacks, handles hyperparameters, and tracks training state.

The main training is controlled via callbacks.

class qewton.optim.trainer.base_trainer.Trainer(optimization_phases: OptimizationPhase | list[OptimizationPhase], callbacks: Callback | list[Callback], hyperparameters: set[HyperParameter], device: str | Device = CPU(), save_path: str = 'train_results', progress_bar: ProgressBarCallback | None = None, enable_logging=True, log_interval=100)[source]

Bases: object

Coordinator for optimization training runs.

A Trainer manages a sequence of optimization phases, configures callbacks, applies hyperparameters, and advances the training loop. The training lifecycle is exposed through hooks that invoke registered callbacks at key events.

Parameters:
  • optimization_phases (OptimizationPhase | list[OptimizationPhase]) – One or more optimization phases defining the training workflow.

  • callbacks (Callback | list[Callback]) – One or more callback objects used to receive training events.

  • hyperparameters (set[HyperParameter]) – A set of global hyperparameters used during training.

  • device (str) – Target device string for training, e.g. “cpu” or “cuda”.

  • save_path (str) – Directory or file path where training results are stored.

  • progress_bar (ProgressBarCallback | None, optional) – Optional progress bar callback instance. If omitted, a default ProgressBarCallback is added.

  • enable_logging (bool) – Whether training logs should be recorded.

  • log_interval (int) – Interval in iterations for logging output.

set_trainable_parameters(parameters: _TrainableParameterBase)[source]

Attach the trainable parameter container used by optimization phases.

Parameters:

parameters (_TrainableParameterBase) – Container holding the parameters to update during training.

run(show_progress=True)[source]

Execute the full training loop across all configured phases.

Each optimization phase is initialized, stepped through for its configured number of iterations, and cleaned up. Registered callbacks are invoked at lifecycle events.

Parameters:

show_progress (bool) – If False, remove progress bar callbacks before starting training.

on_training_start()[source]

Notify callbacks that training is starting and prepare the training state.

on_optimization_phases_start()[source]

Notify callbacks that a new optimization phase is beginning.

training_step(idx: int)[source]

Execute a single training iteration and notify callbacks.

Parameters:

idx (int) – Local index of the current iteration within the current phase.

on_training_step_end()[source]

Finalize the current training iteration and update training state.

on_optimization_phases_end()[source]

Notify callbacks that the current optimization phase has finished.

on_training_end()[source]

Notify callbacks that training has completed and stop timers.

set_hyperparameter(param_dict: dict[str, Any])[source]

Update hyperparameter values from a dictionary.

Parameters:

param_dict (dict[str, Any]) – Mapping of hyperparameter names to new values.

set_device(device)[source]

Set the target device for training.

check_tuning_constraints_exist(constraints)[source]

Stub for checking tuning constraints compatibility.

populate_state_dict()[source]

Collect relevant loss and metric names into the state dict.

This method is intended to prepare the training state with the expected output names before training begins.

cleanup() → Callable[source]

Perform cleanup tasks after the last optimization phase completes.

qewton.optim.trainer.function_trainer module

class qewton.optim.trainer.function_trainer.FunctionBasedTrainer(optimization_phases: OptimizationPhase | list[OptimizationPhase], training_functions: list[Callable[[int, TrainerState], Any]], model_nodes: list[Node], hyperparameters: set[HyperParameter] | None = None, validation_functions: list[Callable[[int, TrainerState], Any]] | None = None, validation_interval: int = 100, callbacks: Callback | list[Callback] | None = None, device='cpu', save_path: str = 'train_results', enable_logging=True, log_interval=100, progress_bar: ProgressBarCallback | None = None)[source]

Bases: Trainer

A trainer that evaluates user defined functions to train a model.

Parameters:
  • optimization_phases (OptimizationPhase | list[OptimizationPhase]) – One or more optimization phases defining the training workflow.

  • training_functions (list[Callable[[int, TrainerState], Any]]) – A list of functions that should be evaluated during training. They should get the current iteration index and train state as an input and return exactly one value (the loss)

  • model_nodes (list[Node]) – List of all models that should be trained by this trainer.

  • hyperparameters (set[HyperParameter] | None, optional) – All HyperParameters that appear in the problem. Defaults to None.

  • validation_functions (list[Callable[[int, TrainerState], Any]] | None, optional) – Additional functions that are used to validate the trainings results. Defaults to None.

  • callbacks (Callback | list[Callback] | None, optional) – Additional callbacks that should be applied. Defaults to None.

  • validation_interval (int, optional) – The interval for validation. Defaults to 100.

  • device (str) – Target device string for training, e.g. “cpu” or “cuda”.

  • save_path (str) – Directory or file path where training results are stored.

  • progress_bar (ProgressBarCallback | None, optional) – Optional progress bar callback instance. If omitted, a default ProgressBarCallback is added.

  • enable_logging (bool) – Whether training logs should be recorded.

  • log_interval (int) – Interval in iterations for logging output.

on_training_start()[source]

Notify callbacks that training is starting and prepare the training state.

populate_state_dict()[source]

Collect all relevant loss and metric names into the state dict, to know at the start of training which values are to be expected.

check_tuning_constraints_exist(constraints: list[Callable[[int, TrainerState], Any]])[source]

Stub for checking tuning constraints compatibility.

qewton.optim.trainer.graph_trainer module

Trainer that trains models defined as graphs.

class qewton.optim.trainer.graph_trainer.GraphBasedTrainer(optimization_phases: OptimizationPhase | list[OptimizationPhase], graphs: list[Graph], training_objectives: list[Constraint], callbacks: Callback | list[Callback] | None = None, validation_interval: int = 100, device: str | Device = CPU(), save_path: str = 'train_results', progress_bar: ProgressBarCallback | None = None, enable_logging=True, log_interval=100)[source]

Bases: Trainer

Trainer that evaluates graphs to train the models inside them.

The trainer collects the constraints of all graphs. Each graph containing a training objective is evaluated in the training phase. Other constraints are assigned to training and/or validation according to their evaluated_in_mode and the phases for which the graph’s data nodes provide data. Constraints with the same name are renamed ("PDE", "PDE_2", …) in the order of training_objectives, then of creation, since losses are recorded by constraint name.

Parameters:
  • optimization_phases – One or more optimization phases defining the training workflow.

  • graphs – All graphs considered by this trainer.

  • training_objectives – The constraints whose losses are optimized. Their evaluated_in_mode must be TRAIN or ALWAYS.

  • callbacks – Additional callbacks.

  • validation_interval – The number of iterations between validation evaluations.

  • device – The device to train on, e.g. "cpu" or "cuda".

  • save_path – Directory or file path where training results are stored.

  • progress_bar – The progress bar callback. If None, a default ProgressBarCallback is used.

  • enable_logging (bool, optional) – Whether training logs are recorded. Defaults to True.

  • log_interval (int, optional) – The number of iterations between log outputs. Defaults to 100.

Raises:
  • AssertionError – If a training objective is not evaluated in the training phase.

  • ValueError – If a graph has constraints for a phase in which its data nodes provide no data.

graphs

All graphs of this trainer.

Type:

list of Graph

all_nodes

All nodes of all graphs.

Type:

set of Node

training_objectives

The optimized constraints.

Type:

list of Constraint

training_constraints

The constraints evaluated in the training phase.

Type:

set of Constraint

validation_constraints

The constraints evaluated in the validation phase.

Type:

set of Constraint

train_graphs

The graphs evaluated in the training phase.

Type:

set of Graph

validation_graphs

The graphs evaluated in the validation phase.

Type:

set of Graph

check_tuning_constraints_exist(constraints: list[Constraint])[source]

Check that the constraints are evaluated by this trainer.

Parameters:

constraints – The constraints to check.

Raises:

AssertionError – If a constraint is neither a training nor a validation constraint.

collect_graph_hyperparameters() → set[HyperParameter][source]

Collect the hyperparameters of all nodes.

Returns:

The hyperparameters of all nodes of all

graphs.

Return type:

set of HyperParameter

set_hyperparameter(param_dict: dict) → None[source]

Update hyperparameter values from a dictionary; a node whose hyperparameters change is built again at its next setup.

Parameters:

param_dict (dict[str, Any]) – Mapping of hyperparameter names to new values.

on_training_start()[source]

Prepare the graphs for training.

Sets up all graphs, moves all nodes to the training device and registers the trainable parameters of all nodes.

Raises:

ValueError – If no node has trainable parameters.

populate_state_dict()[source]

Register the loss names of all training and validation constraints in the train state, so the expected values are known at the start of training.

qewton.optim.trainer.training_controllers module

class qewton.optim.trainer.training_controllers.LogEntry(iteration: int, timestamp: float, losses: dict[EvaluationPhase, dict[str, float | None]])[source]

Bases: object

A record of training metrics captured at a logging interval.

iteration

Global iteration index when the log entry was created.

Type:

int

timestamp

Wall-clock time of the log entry.

Type:

float

losses

Snapshot of loss values for each evaluation phase.

Type:

dict[EvaluationPhase, dict[str, float | None]]

iteration: int
timestamp: float
losses: dict[EvaluationPhase, dict[str, float | None]]
class qewton.optim.trainer.training_controllers.TrainerState(save_path, enable_logging: bool = True, log_interval: int = 100)[source]

Bases: object

Shared state container for training progress and logging.

TrainerState is passed to callbacks and optimization phases so they can inspect and update the current training status.

Parameters:
  • save_path (str) – Directory path used for saving callback output.

  • enable_logging (bool, optional) – Whether to record log history. Defaults to True.

  • log_interval (int, optional) – Number of iterations between log entries. Defaults to 100.

current_optimization_phase: OptimizationPhase
iteration: int
total_train_loss: float
losses: dict[EvaluationPhase, dict[str, float | None]]
history: list[LogEntry]
callback_info: dict[str, Any]
callback_objectives: dict[str, ConstraintObjective]
stop_stage: bool
start_training_timer()[source]

Start the training duration timer.

stop_training_timer(reason: str = '')[source]

Stop the timer and optionally record a termination reason.

Parameters:

reason (str) – Reason for stopping training.

property stop_training

Whether training should stop completely.

Type:

bool

detach_data(data_dict) → dict[EvaluationPhase, dict[str, float | None]][source]

Convert backend tensor losses to plain Python scalars.

Parameters:

data_dict – Raw loss dictionary potentially containing tensor objects.

Returns:

Detached loss values.

Return type:

dict[EvaluationPhase, dict[str, float | None]]

clear_data_dict()[source]

Reset stored loss values for all evaluation phases.

check_file_path(callbacks)[source]

Validate the save path and create a unique directory when needed.

Parameters:

callbacks (list[Callback]) – Registered callbacks that may save data.

log_step()[source]

Append the current loss snapshot to history if logging is enabled.

class qewton.optim.trainer.training_controllers.OptimizationPhase(optimizer: Optimizer, lr: float | HyperParameter, max_iterations: int | HyperParameter, optimizer_args: dict | None = None, lr_scheduler: LR_Scheduler | None = None)[source]

Bases: object

Encapsulates one phase of optimization, including optimizer and learning rate scheduling.

OptimizationPhase manages optimizer setup, per-step execution, cleanup, and hyperparameter extraction for a single training stage.

Parameters:
  • optimizer (Optimizer) – Optimizer wrapper defining the backend and params.

  • lr (float | HyperParameter) – Learning rate value or hyperparameter.

  • max_iterations (int | HyperParameter) – Iteration count or hyperparameter.

  • optimizer_args (dict | None, optional) – Additional optimizer kwargs. Defaults to None.

  • lr_scheduler (Any, optional) – Optional learning rate scheduler class or callable. Defaults to None.

  • lr_scheduler_args (dict | None, optional) – Arguments for the scheduler. Defaults to None.

Raises:

ValueError – If the optimizer backend is unsupported.

optimizer: Optimizer
optimizer_obj: Any
setup_fn: Callable
step_fn: Callable
cleanup_fn: Callable
get_hyperparameter() → set[HyperParameter][source]

Return the set of HyperParameter instances referenced by this phase.

Returns:

Hyperparameters used by this optimization phase.

Return type:

set[HyperParameter]

setup_optimizer(trainer)[source]

Build and initialize the backend optimizer object for this phase.

Parameters:

trainer (Trainer) – Trainer instance used to configure the optimizer.

do_optimization_step(eval_function: Callable, step_idx: int, train_state: TrainerState)[source]

Execute one optimization step using the backend-specific step function.

Parameters:
  • eval_function (Callable) – Function invoked to compute losses.

  • step_idx (int) – Index of the current step in this phase.

  • train_state (TrainerState) – Shared training state.

cleanup()[source]

Perform backend-specific cleanup after the optimization phase ends.