QML tools
ML Tools
This module implements a Trainer
class for torch Modules
and QuantumModel
. It also implements the QNN
class and callbacks that can be used with the trainer module.
Trainer(model, optimizer, config, loss_fn='mse', train_dataloader=None, val_dataloader=None, test_dataloader=None, optimize_step=optimize_step, device=None, dtype=None, max_batches=None)
Bases:
Trainer class to manage and execute training, validation, and testing loops for a model (eg.
QNN).
This class handles the overall training process, including: - Managing epochs and steps - Handling data loading and batching - Computing and updating gradients - Logging and monitoring training metrics
ATTRIBUTE | DESCRIPTION |
---|---|
|
The current epoch number.
TYPE:
|
|
The global step across all epochs.
TYPE:
|
|
Device for logging, default is "cpu".
TYPE:
|
|
Device used for computation.
TYPE:
|
|
Data type used for computation.
TYPE:
|
|
Data type for data. Depends on the model's data type.
TYPE:
|
Inherited Attributes
use_grad (bool): Indicates if gradients are used for optimization. Default is True.
model (nn.Module): The neural network model. optimizer (optim.Optimizer | NGOptimizer | None): The optimizer for training. config (TrainConfig): The configuration settings for training. train_dataloader (DataLoader | DictDataLoader | None): DataLoader for training data. val_dataloader (DataLoader | DictDataLoader | None): DataLoader for validation data. test_dataloader (DataLoader | DictDataLoader | None): DataLoader for testing data.
optimize_step (Callable): Function for performing an optimization step. loss_fn (Callable): loss function to use.
num_training_batches (int): Number of training batches. num_validation_batches (int): Number of validation batches. num_test_batches (int): Number of test batches.
state (str): Current state in the training process
Default training routine
for epoch in max_iter + 1:
# Training
for batch in train_batches:
train model
# Validation
if val_every % epoch == 0:
for batch in val_batches:
train model
Notes
- In case of InfiniteTensorDataset, number of batches = 1.
- In case of TensorDataset, number of batches are default.
- Training is run for max_iter + 1 epochs. Epoch 0 logs untrained model.
- Please look at the CallbackManager initialize_callbacks method to review the default logging behavior.
Examples:
import torch
from torch.optim import SGD
from qadence import (
feature_map,
hamiltonian_factory,
hea,
QNN,
QuantumCircuit,
TrainConfig,
Z,
)
from qadence.ml_tools.trainer import Trainer
from qadence.ml_tools.optimize_step import optimize_step
from qadence.ml_tools import TrainConfig
from qadence.ml_tools.data import to_dataloader
# Initialize the model
n_qubits = 2
fm = feature_map(n_qubits)
ansatz = hea(n_qubits=n_qubits, depth=2)
observable = hamiltonian_factory(n_qubits, detuning=Z)
circuit = QuantumCircuit(n_qubits, fm, ansatz)
model = QNN(circuit, observable, backend="pyqtorch", diff_mode="ad")
# Set up the optimizer
optimizer = SGD(model.parameters(), lr=0.001)
# Use TrainConfig for configuring the training process
config = TrainConfig(
max_iter=100,
print_every=10,
write_every=10,
checkpoint_every=10,
val_every=10
)
# Create the Trainer instance with TrainConfig
trainer = Trainer(
model=model,
optimizer=optimizer,
config=config,
loss_fn="mse",
optimize_step=optimize_step
)
batch_size = 25
x = torch.linspace(0, 1, 32).reshape(-1, 1)
y = torch.sin(x)
train_loader = to_dataloader(x, y, batch_size=batch_size, infinite=True)
val_loader = to_dataloader(x, y, batch_size=batch_size, infinite=False)
# Train the model
model, optimizer = trainer.fit(train_loader, val_loader)
This also supports both gradient based and gradient free optimization. The default support is for gradient based optimization.
Notes:
- set_use_grad() (class level):This method is used to set the global
use_grad
flag, controlling whether the trainer uses gradient-based optimization. - Context Managers (instance level):
enable_grad_opt()
anddisable_grad_opt()
are context managers that temporarily switch the optimization mode for specific code blocks. This is useful when you want to mix gradient-based and gradient-free optimization in the same training process.
Examples
Gradient based optimization example Usage:
from torch import optim
optimizer = optim.SGD(model.parameters(), lr=0.01)
Trainer.set_use_grad(True)
trainer = Trainer(
model=model,
optimizer=optimizer,
config=config,
loss_fn="mse"
)
trainer.fit(train_loader, val_loader)
trainer = Trainer(
model=model,
config=config,
loss_fn="mse"
)
with trainer.enable_grad_opt(optimizer):
trainer.fit(train_loader, val_loader)
Gradient free optimization example Usage:
import nevergrad as ng
from qadence.ml_tools.parameters import num_parameters
ng_optimizer = ng.optimizers.NGOpt(
budget=config.max_iter, parametrization= num_parameters(model)
)
Trainer.set_use_grad(False)
trainer = Trainer(
model=model,
optimizer=ng_optimizer,
config=config,
loss_fn="mse"
)
trainer.fit(train_loader, val_loader)
import nevergrad as ng
from qadence.ml_tools.parameters import num_parameters
ng_optimizer = ng.optimizers.NGOpt(
budget=config.max_iter, parametrization= num_parameters(model)
)
trainer = Trainer(
model=model,
config=config,
loss_fn="mse"
)
with trainer.disable_grad_opt(ng_optimizer):
trainer.fit(train_loader, val_loader)
Initializes the Trainer class.
PARAMETER | DESCRIPTION |
---|---|
model |
The PyTorch model to train.
TYPE:
|
optimizer |
The optimizer for training.
TYPE:
|
config |
Training configuration object.
TYPE:
|
loss_fn |
Loss function used for training. If not specified, default mse loss will be used.
TYPE:
|
train_dataloader |
DataLoader for training data.
TYPE:
|
val_dataloader |
DataLoader for validation data.
TYPE:
|
test_dataloader |
DataLoader for test data.
TYPE:
|
optimize_step |
Function to execute an optimization step.
TYPE:
|
device |
Device to use for computation.
TYPE:
|
dtype |
Data type for computation.
TYPE:
|
max_batches |
Maximum number of batches to process per epoch. This is only valid in case of finite TensorDataset dataloaders. if max_batches is not None, the maximum number of batches used will be min(max_batches, len(dataloader.dataset)) In case of InfiniteTensorDataset only 1 batch per epoch is used.
TYPE:
|
Source code in qadence/ml_tools/trainer.py
build_optimize_result(result)
Builds and stores the optimization result by calculating the average loss and metrics.
Result (or loss_metrics) can have multiple formats:
- None
Indicates no loss or metrics data is provided.
- tuple[torch.Tensor, dict[str, Any]]
A single tuple containing the loss tensor
and metrics dictionary - at the end of batch.
- list[tuple[torch.Tensor, dict[str, Any]]]
A list of tuples for
multiple batches.
- list[list[tuple[torch.Tensor, dict[str, Any]]]]
A list of lists of tuples,
where each inner list represents metrics across multiple batches within an epoch.
PARAMETER | DESCRIPTION |
---|---|
result |
(None | tuple[torch.Tensor, dict[Any, Any]] | list[tuple[torch.Tensor, dict[Any, Any]]] | list[list[tuple[torch.Tensor, dict[Any, Any]]]]) The loss and metrics data, which can have multiple formats
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
None
|
This method does not return anything. It sets
TYPE:
|
None
|
the computed average loss and metrics. |
Source code in qadence/ml_tools/trainer.py
630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 |
|
fit(train_dataloader=None, val_dataloader=None)
Fits the model using the specified training configuration.
The dataloaders can be provided to train on new datasets, or the default dataloaders provided in the trainer will be used.
PARAMETER | DESCRIPTION |
---|---|
train_dataloader |
DataLoader for training data.
TYPE:
|
val_dataloader |
DataLoader for validation data.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
|
tuple[nn.Module, optim.Optimizer]: The trained model and optimizer. |
Source code in qadence/ml_tools/trainer.py
run_test_batch(batch)
Runs a single test batch.
PARAMETER | DESCRIPTION |
---|---|
batch |
Batch of data from the DataLoader.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
|
tuple[torch.Tensor, dict[str, Any]]: Loss and metrics for the batch. |
Source code in qadence/ml_tools/trainer.py
run_train_batch(batch)
Runs a single training batch, performing optimization.
We use the step function to optimize the model based on use_grad. use_grad = True entails gradient based optimization, for which we use optimize_step function. use_grad = False entails gradient free optimization, for which we use update_ng_parameters function.
PARAMETER | DESCRIPTION |
---|---|
batch |
Batch of data from the DataLoader.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
|
tuple[torch.Tensor, dict[str, Any]]: Loss and metrics for the batch. tuple of (loss, metrics) |
Source code in qadence/ml_tools/trainer.py
run_training(dataloader)
Runs the training for a single epoch, iterating over multiple batches.
PARAMETER | DESCRIPTION |
---|---|
dataloader |
DataLoader for training data.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
|
list[tuple[torch.Tensor, dict[str, Any]]]: Loss and metrics for each batch. list -> tuples Training Batches -> (loss, metrics) |
Source code in qadence/ml_tools/trainer.py
run_val_batch(batch)
Runs a single validation batch.
PARAMETER | DESCRIPTION |
---|---|
batch |
Batch of data from the DataLoader.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
|
tuple[torch.Tensor, dict[str, Any]]: Loss and metrics for the batch. |
Source code in qadence/ml_tools/trainer.py
run_validation(dataloader)
Runs the validation loop for a single epoch, iterating over multiple batches.
PARAMETER | DESCRIPTION |
---|---|
dataloader |
DataLoader for validation data.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
|
list[tuple[torch.Tensor, dict[str, Any]]]: Loss and metrics for each batch. list -> tuples Validation Batches -> (loss, metrics) |
Source code in qadence/ml_tools/trainer.py
test(test_dataloader=None)
Runs the testing loop if a test DataLoader is provided.
if the test_dataloader is not provided, default test_dataloader defined in the Trainer class is used.
PARAMETER | DESCRIPTION |
---|---|
test_dataloader |
DataLoader for test data.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
|
list[tuple[torch.Tensor, dict[str, Any]]]: Loss and metrics for each batch. list -> tuples Test Batches -> (loss, metrics) |
Source code in qadence/ml_tools/trainer.py
AnsatzConfig(depth=1, ansatz_type=AnsatzType.HEA, ansatz_strategy=Strategy.DIGITAL, strategy_args=dict(), param_prefix='theta', tag=None)
dataclass
ansatz_strategy: Strategy = Strategy.DIGITAL
class-attribute
instance-attribute
Ansatz strategy.
Strategy.DIGITAL
for fully digital ansatz. Required if ansatz_type
is AnsatzType.IIA
.
Strategy.SDAQC
for analog entangling block.
Strategy.RYDBERG
for fully rydberg hea ansatz.
ansatz_type: AnsatzType = AnsatzType.HEA
class-attribute
instance-attribute
What type of ansatz.
AnsatzType.HEA
for Hardware Efficient Ansatz.
AnsatzType.IIA
for Identity intialized Ansatz.
depth: int = 1
class-attribute
instance-attribute
Number of layers of the ansatz.
param_prefix: str = 'theta'
class-attribute
instance-attribute
The base bame of the variational parameter.
strategy_args: dict = field(default_factory=dict)
class-attribute
instance-attribute
A dictionary containing keyword arguments to the function creating the ansatz.
Details about each below.
For Strategy.DIGITAL
strategy, accepts the following:
periodic (bool): if the qubits should be linked periodically.
periodic=False is not supported in emu-c.
operations (list): list of operations to cycle through in the
digital single-qubit rotations of each layer.
Defaults to [RX, RY, RX] for hea and [RX, RY] for iia.
entangler (AbstractBlock): 2-qubit entangling operation.
Supports CNOT, CZ, CRX, CRY, CRZ, CPHASE. Controlld rotations
will have variational parameters on the rotation angles.
Defaults to CNOT
For Strategy.SDAQC
strategy, accepts the following:
operations (list): list of operations to cycle through in the
digital single-qubit rotations of each layer.
Defaults to [RX, RY, RX] for hea and [RX, RY] for iia.
entangler (AbstractBlock): Hamiltonian generator for the
analog entangling layer. Time parameter is considered variational.
Defaults to NN interaction.
For Strategy.RYDBERG
strategy, accepts the following:
addressable_detuning: whether to turn on the trainable semi-local addressing pattern
on the detuning (n_i terms in the Hamiltonian).
Defaults to True.
addressable_drive: whether to turn on the trainable semi-local addressing pattern
on the drive (sigma_i^x terms in the Hamiltonian).
Defaults to False.
tunable_phase: whether to have a tunable phase to get both sigma^x and sigma^y rotations
in the drive term. If False, only a sigma^x term will be included in the drive part
of the Hamiltonian generator.
Defaults to False.
tag: str | None = None
class-attribute
instance-attribute
String to indicate the name tag of the ansatz.
Defaults to None, in which case no tag will be applied.
FeatureMapConfig(num_features=0, basis_set=BasisSet.FOURIER, reupload_scaling=ReuploadScaling.CONSTANT, feature_range=None, target_range=None, multivariate_strategy=MultivariateStrategy.PARALLEL, feature_map_strategy=Strategy.DIGITAL, param_prefix=None, num_repeats=0, operation=None, inputs=None, tag=None)
dataclass
basis_set: BasisSet | dict[str, BasisSet] = BasisSet.FOURIER
class-attribute
instance-attribute
Basis set for feature encoding.
Takes qadence.BasisSet. Give a single BasisSet to use the same for all features. Give a dict of (str, BasisSet) where the key is the name of the variable and the value is the BasisSet to use for encoding that feature. BasisSet.FOURIER for Fourier encoding. BasisSet.CHEBYSHEV for Chebyshev encoding.
feature_map_strategy: Strategy = Strategy.DIGITAL
class-attribute
instance-attribute
Strategy for feature map.
Accepts DIGITAL, ANALOG or RYDBERG. Defaults to DIGITAL.
If the strategy is incompatible with the operation
chosen, then operation
gets preference and the given strategy is ignored.
feature_range: tuple[float, float] | dict[str, tuple[float, float]] | None = None
class-attribute
instance-attribute
Range of data that the input data is assumed to come from.
Give a single tuple to use the same range for all features. Give a dict of (str, tuple) where the key is the name of the variable and the value is the feature range to use for that feature.
inputs: list[Basic | str] | None = None
class-attribute
instance-attribute
List that indicates the order of variables of the tensors that are passed.
Optional if a single feature is being encoded, required otherwise. Given input tensors
xs = torch.rand(batch_size, input_size:=2)
a QNN with inputs=["t", "x"]
will
assign t, x = xs[:,0], xs[:,1]
.
multivariate_strategy: MultivariateStrategy = MultivariateStrategy.PARALLEL
class-attribute
instance-attribute
The encoding strategy in case of multi-variate function.
Takes qadence.MultivariateStrategy.
If PARALLEL, the features are encoded in one block of rotation gates
with the register being split in sub-registers for each feature.
If SERIES, the features are encoded sequentially using the full register for each feature, with
an ansatz block between them. PARALLEL is allowed only for DIGITAL feature_map_strategy
.
num_features: int = 0
class-attribute
instance-attribute
Number of feature parameters to be encoded.
Defaults to 0. Thus, no feature parameters are encoded.
num_repeats: int | dict[str, int] = 0
class-attribute
instance-attribute
Number of feature map layers repeated in the data reuploading step.
If all features are to be repeated the same number of times, then can give a single
int
. For different number of repetitions for each feature, provide a dict
of (str, int) where the key is the name of the variable and the value is the
number of repetitions for that feature.
This amounts to the number of additional reuploads. So if num_repeats
is N,
the data gets uploaded N+1 times. Defaults to no repetition.
operation: Callable[[Parameter | Basic], AnalogBlock] | Type[RX] | None = None
class-attribute
instance-attribute
Type of operation.
Choose among the analog or digital rotations or a custom
callable function returning an AnalogBlock instance. If the type of operation is
incompatible with the strategy
chosen, then operation
gets preference and
the given strategy is ignored.
param_prefix: str | None = None
class-attribute
instance-attribute
String prefix to create trainable parameters in Feature Map.
A string prefix to create trainable parameters multiplying the feature parameter
inside the feature-encoding function. Note that currently this does not take into
account the domain of the feature-encoding function.
Defaults to None
and thus, the feature map is not trainable.
Note that this is separate from the name of the parameter.
The user can provide a single prefix for all features, and it will be appended
by appropriate feature name automatically.
reupload_scaling: ReuploadScaling | dict[str, ReuploadScaling] = ReuploadScaling.CONSTANT
class-attribute
instance-attribute
Scaling for encoding the same feature on different qubits.
Scaling used to encode the same feature on different qubits in the same layer of the feature maps. Takes qadence.ReuploadScaling. Give a single ReuploadScaling to use the same for all features. Give a dict of (str, ReuploadScaling) where the key is the name of the variable and the value is the ReuploadScaling to use for encoding that feature. ReuploadScaling.CONSTANT for constant scaling. ReuploadScaling.TOWER for linearly increasing scaling. ReuploadScaling.EXP for exponentially increasing scaling.
tag: str | None = None
class-attribute
instance-attribute
String to indicate the name tag of the feature map.
Defaults to None, in which case no tag will be applied.
target_range: tuple[float, float] | dict[str, tuple[float, float]] | None = None
class-attribute
instance-attribute
Range of data the data encoder assumes as natural range.
Give a single tuple to use the same range for all features. Give a dict of (str, tuple) where the key is the name of the variable and the value is the target range to use for that feature.
TrainConfig(max_iter=10000, print_every=0, write_every=0, checkpoint_every=0, plot_every=0, callbacks=lambda: list()(), log_model=False, root_folder=Path('./qml_logs'), create_subfolder_per_run=False, log_folder=Path('./'), checkpoint_best_only=False, val_every=0, val_epsilon=1e-05, validation_criterion=None, trainstop_criterion=None, batch_size=1, verbose=True, tracking_tool=ExperimentTrackingTool.TENSORBOARD, hyperparams=dict(), plotting_functions=tuple(), _subfolders=list())
dataclass
Default configuration for the training process.
This class provides default settings for various aspects of the training loop,
such as logging, checkpointing, and validation. The default values for these
fields can be customized when an instance of TrainConfig
is created.
Example:
TrainConfig(max_iter=10000, print_every=0, write_every=0, checkpoint_every=0, plot_every=0, callbacks=[], log_model=False, root_folder='/tmp/train', create_subfolder_per_run=False, log_folder=PosixPath('.'), checkpoint_best_only=False, val_every=0, val_epsilon=1e-05, validation_criterion=None, trainstop_criterion=None, batch_size=1, verbose=True, tracking_tool=<ExperimentTrackingTool.TENSORBOARD: 'tensorboard'>, hyperparams={}, plotting_functions=(), _subfolders=[])
batch_size: int = 1
class-attribute
instance-attribute
The batch size to use when processing a list or tuple of torch.Tensors.
This specifies how many samples are processed in each training iteration.
callbacks: list = field(default_factory=lambda: list())
class-attribute
instance-attribute
List of callbacks to execute during training.
Callbacks can be used for custom behaviors, such as early stopping, custom logging, or other actions triggered at specific events.
checkpoint_best_only: bool = False
class-attribute
instance-attribute
If True
, checkpoints are only saved if there is an improvement in the.
validation metric. This conserves storage by only keeping the best models.
validation_criterion is required when this is set to True.
checkpoint_every: int = 0
class-attribute
instance-attribute
Frequency (in epochs) for saving model and optimizer checkpoints during training.
Set to 0 to disable checkpointing. This helps in resuming training or recovering models. Note that setting checkpoint_best_only = True will disable this and only best checkpoints will be saved.
create_subfolder_per_run: bool = False
class-attribute
instance-attribute
Whether to create a subfolder for each run, named <id>_<timestamp>_<PID>
.
This ensures logs and checkpoints from different runs do not overwrite each other,
which is helpful for rapid prototyping. If False
, training will resume from
the latest checkpoint if one exists in the specified log folder.
hyperparams: dict = field(default_factory=dict)
class-attribute
instance-attribute
A dictionary of hyperparameters to be tracked.
This can include learning rates, regularization parameters, or any other training-related configurations.
log_folder: Path = Path('./')
class-attribute
instance-attribute
The log folder for saving checkpoints and tensorboard logs.
This stores the path where all logs and checkpoints are being saved
for this training session. log_folder
takes precedence over root_folder
and
create_subfolder_per_run
arguments. If the user specifies a log_folder,
all checkpoints will be saved in this folder and root_folder
argument
will not be used.
log_model: bool = False
class-attribute
instance-attribute
Whether to log a serialized version of the model.
When set to True
, the
model's state will be logged, useful for model versioning and reproducibility.
max_iter: int = 10000
class-attribute
instance-attribute
Number of training iterations (epochs) to perform.
This defines the total number of times the model will be updated.
In case of InfiniteTensorDataset, each epoch will have 1 batch. In case of TensorDataset, each epoch will have len(dataloader) batches.
plot_every: int = 0
class-attribute
instance-attribute
Frequency (in epochs) for generating and saving figures during training.
Set to 0 to disable plotting.
plotting_functions: tuple[LoggablePlotFunction, ...] = field(default_factory=tuple)
class-attribute
instance-attribute
Functions used for in-training plotting.
These are called to generate plots that are logged or saved at specified intervals.
print_every: int = 0
class-attribute
instance-attribute
Frequency (in epochs) for printing loss and metrics to the console during training.
Set to 0 to disable this output, meaning that metrics and loss will not be printed during training.
root_folder: Path = Path('./qml_logs')
class-attribute
instance-attribute
The root folder for saving checkpoints and tensorboard logs.
The default path is "./qml_logs"
This can be set to a specific directory where training artifacts are to be stored.
Checkpoints will be saved inside a subfolder in this directory. Subfolders will be
created based on create_subfolder_per_run
argument.
tracking_tool: ExperimentTrackingTool = ExperimentTrackingTool.TENSORBOARD
class-attribute
instance-attribute
The tool used for tracking training progress and logging metrics.
Options include tools like TensorBoard, which help visualize and monitor model training.
trainstop_criterion: Callable | None = None
class-attribute
instance-attribute
A function to determine if the training process should stop based on a.
specific stopping metric. If None
, training continues until max_iter
is reached.
val_epsilon: float = 1e-05
class-attribute
instance-attribute
A small safety margin used to compare the current validation loss with the.
best previous validation loss. This is used to determine improvements in metrics.
val_every: int = 0
class-attribute
instance-attribute
Frequency (in epochs) for performing validation.
If set to 0, validation is not performed.
Note that metrics from validation are always written, regardless of the write_every
setting.
Note that initial validation happens at the start of training (when val_every > 0)
For initial validation - initial metrics are written.
- checkpoint is saved (when checkpoint_best_only = False)
validation_criterion: Callable | None = None
class-attribute
instance-attribute
A function to evaluate whether a given validation metric meets a desired condition.
The validation_criterion has the following format: def validation_criterion(val_loss: float, best_val_loss: float, val_epsilon: float) -> bool: # process
If None
, no custom validation criterion is applied.
verbose: bool = True
class-attribute
instance-attribute
Whether to print metrics and status messages during training.
If True
, detailed metrics and status updates will be displayed in the console.
write_every: int = 0
class-attribute
instance-attribute
Frequency (in epochs) for writing loss and metrics using the tracking tool during training.
Set to 0 to disable this logging, which prevents metrics from being logged to the tracking tool. Note that the metrics will always be written at the end of training regardless of this setting.
get_parameters(model)
Retrieve all trainable model parameters in a single vector.
PARAMETER | DESCRIPTION |
---|---|
model |
the input PyTorch model
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
Tensor
|
a 1-dimensional tensor with the parameters
TYPE:
|
Source code in qadence/ml_tools/parameters.py
num_parameters(model)
set_parameters(model, theta)
Set all trainable parameters of a model from a single vector.
Notice that this function assumes prior knowledge of right number of parameters in the model
PARAMETER | DESCRIPTION |
---|---|
model |
the input PyTorch model
TYPE:
|
theta |
the parameters to assign
TYPE:
|
Source code in qadence/ml_tools/parameters.py
optimize_step(model, optimizer, loss_fn, xs, device=None, dtype=None)
Default Torch optimize step with closure.
This is the default optimization step.
PARAMETER | DESCRIPTION |
---|---|
model |
The input model to be optimized.
TYPE:
|
optimizer |
The chosen Torch optimizer.
TYPE:
|
loss_fn |
A custom loss function that returns the loss value and a dictionary of metrics.
TYPE:
|
xs |
The input data. If None, it means the given model does not require any input data.
TYPE:
|
device |
A target device to run computations on.
TYPE:
|
dtype |
Data type for
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
|
tuple[Tensor | float, dict | None]: A tuple containing the computed loss value and a dictionary with collected metrics. |
Source code in qadence/ml_tools/optimize_step.py
update_ng_parameters(model, optimizer, loss_fn, data, ng_params)
Update the model parameters using Nevergrad.
This function integrates Nevergrad for derivative-free optimization.
PARAMETER | DESCRIPTION |
---|---|
model |
The PyTorch model to be optimized.
TYPE:
|
optimizer |
A Nevergrad optimizer instance.
TYPE:
|
loss_fn |
A custom loss function that returns the loss value and a dictionary of metrics.
TYPE:
|
data |
Input data for the model. If None, it means the model does not require input data.
TYPE:
|
ng_params |
The current set of parameters managed by Nevergrad.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
|
tuple[float, dict, ng.p.Array]: A tuple containing the computed loss value, a dictionary of metrics, and the updated Nevergrad parameters. |
Source code in qadence/ml_tools/optimize_step.py
DictDataLoader(dataloaders)
dataclass
This class only holds a dictionary of DataLoader
s and samples from them.
InfiniteTensorDataset(*tensors)
Bases:
Randomly sample points from the first dimension of the given tensors.
Behaves like a normal torch Dataset
just that we can sample from it as
many times as we want.
Examples:
import torch
from qadence.ml_tools.data import InfiniteTensorDataset
x_data, y_data = torch.rand(5,2), torch.ones(5,1)
# The dataset accepts any number of tensors with the same batch dimension
ds = InfiniteTensorDataset(x_data, y_data)
# call `next` to get one sample from each tensor:
xs = next(iter(ds))
Source code in qadence/ml_tools/data.py
OptimizeResult(iteration, model, optimizer, loss=None, metrics=lambda: dict()(), extra=lambda: dict()())
dataclass
OptimizeResult stores many optimization intermediate values.
We store at a current iteration, the model, optimizer, loss values, metrics. An extra dict can be used for saving other information to be used for callbacks.
extra: dict = field(default_factory=lambda: dict())
class-attribute
instance-attribute
Extra dict for saving anything else to be used in callbacks.
iteration: int
instance-attribute
Current iteration number.
loss: Tensor | float | None = None
class-attribute
instance-attribute
Loss value.
metrics: dict = field(default_factory=lambda: dict())
class-attribute
instance-attribute
Metrics that can be saved during training.
model: Module
instance-attribute
Model at iteration.
optimizer: Optimizer | NGOptimizer
instance-attribute
Optimizer at iteration.
data_to_device(xs, *args, **kwargs)
Utility method to move arbitrary data to 'device'.
to_dataloader(*tensors, batch_size=1, infinite=False)
Convert torch tensors an (infinite) Dataloader.
PARAMETER | DESCRIPTION |
---|---|
*tensors |
Torch tensors to use in the dataloader.
TYPE:
|
batch_size |
batch size of sampled tensors
TYPE:
|
infinite |
if
TYPE:
|
Examples:
import torch
from qadence.ml_tools import to_dataloader
(x, y, z) = [torch.rand(10) for _ in range(3)]
loader = iter(to_dataloader(x, y, z, batch_size=5, infinite=True))
print(next(loader))
print(next(loader))
print(next(loader))
[tensor([0.6089, 0.5589, 0.6142, 0.2165, 0.6462]), tensor([0.3149, 0.6751, 0.1210, 0.8103, 0.9142]), tensor([0.2031, 0.9552, 0.8790, 0.5408, 0.5527])]
[tensor([0.5184, 0.1583, 0.2599, 0.3707, 0.7417]), tensor([0.3621, 0.0112, 0.1667, 0.2752, 0.2930]), tensor([0.1747, 0.9271, 0.7204, 0.5249, 0.1339])]
[tensor([0.6089, 0.5589, 0.6142, 0.2165, 0.6462]), tensor([0.3149, 0.6751, 0.1210, 0.8103, 0.9142]), tensor([0.2031, 0.9552, 0.8790, 0.5408, 0.5527])]
Source code in qadence/ml_tools/data.py
QNN(circuit, observable, backend=BackendName.PYQTORCH, diff_mode=DiffMode.AD, measurement=None, noise=None, configuration=None, inputs=None, input_diff_mode=InputDiffMode.AD)
Bases:
Quantum neural network model for n-dimensional inputs.
Examples:
import torch
from qadence import QuantumCircuit, QNN, Z
from qadence import hea, feature_map, hamiltonian_factory, kron
# create the circuit
n_qubits, depth = 2, 4
fm = kron(
feature_map(1, support=(0,), param="x"),
feature_map(1, support=(1,), param="y")
)
ansatz = hea(n_qubits=n_qubits, depth=depth)
circuit = QuantumCircuit(n_qubits, fm, ansatz)
obs_base = hamiltonian_factory(n_qubits, detuning=Z)
# the QNN will yield two outputs
obs = [2.0 * obs_base, 4.0 * obs_base]
# initialize and use the model
qnn = QNN(circuit, obs, inputs=["x", "y"])
y = qnn(torch.rand(3, 2))
Initialize the QNN.
The number of inputs is determined by the feature parameters in the input quantum circuit while the number of outputs is determined by how many observables are provided as input
PARAMETER | DESCRIPTION |
---|---|
circuit |
The quantum circuit to use for the QNN.
TYPE:
|
observable |
The observable.
TYPE:
|
backend |
The chosen quantum backend.
TYPE:
|
diff_mode |
The differentiation engine to use. Choices 'gpsr' or 'ad'.
TYPE:
|
measurement |
optional measurement protocol. If None, use exact expectation value with a statevector simulator
TYPE:
|
noise |
A noise model to use.
TYPE:
|
configuration |
optional configuration for the backend
TYPE:
|
inputs |
List that indicates the order of variables of the tensors that are passed
to the model. Given input tensors
TYPE:
|
input_diff_mode |
The differentiation mode for the input tensor.
TYPE:
|
Source code in qadence/ml_tools/models.py
forward(values=None, state=None, measurement=None, noise=None, endianness=Endianness.BIG)
Forward pass of the model.
This returns the (differentiable) expectation value of the given observable
operator defined in the constructor. Differently from the base QuantumModel
class, the QNN accepts also a tensor as input for the forward pass. The
tensor is expected to have shape: n_batches x in_features
where n_batches
is the number of data points and in_features
is the dimensionality of the problem
The output of the forward pass is the expectation value of the input
observable(s). If a single observable is given, the output shape is
n_batches
while if multiple observables are given the output shape
is instead n_batches x n_observables
PARAMETER | DESCRIPTION |
---|---|
values |
the values of the feature parameters
TYPE:
|
state |
Initial state.
TYPE:
|
measurement |
optional measurement protocol. If None, use exact expectation value with a statevector simulator
TYPE:
|
noise |
A noise model to use.
TYPE:
|
endianness |
Endianness of the resulting bit strings.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
Tensor
|
a tensor with the expectation value of the observables passed in the constructor of the model
TYPE:
|
Source code in qadence/ml_tools/models.py
from_configs(register, obs_config, fm_config=FeatureMapConfig(), ansatz_config=AnsatzConfig(), backend=BackendName.PYQTORCH, diff_mode=DiffMode.AD, measurement=None, noise=None, configuration=None, input_diff_mode=InputDiffMode.AD)
classmethod
Create a QNN from a set of configurations.
PARAMETER | DESCRIPTION |
---|---|
register |
The number of qubits or a register object.
TYPE:
|
obs_config |
The configuration(s) for the observable(s).
TYPE:
|
fm_config |
The configuration for the feature map. Defaults to no feature encoding block.
TYPE:
|
ansatz_config |
The configuration for the ansatz. Defaults to a single layer of hardware efficient ansatz.
TYPE:
|
backend |
The chosen quantum backend.
TYPE:
|
diff_mode |
The differentiation engine to use. Choices are 'gpsr' or 'ad'.
TYPE:
|
measurement |
Optional measurement protocol. If None, use exact expectation value with a statevector simulator.
TYPE:
|
noise |
A noise model to use.
TYPE:
|
configuration |
Optional backend configuration.
TYPE:
|
input_diff_mode |
The differentiation mode for the input tensor.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
|
A QNN object. |
RAISES | DESCRIPTION |
---|---|
|
If the observable configuration is not provided. |
Example:
import torch
from qadence.ml_tools.config import AnsatzConfig, FeatureMapConfig
from qadence.ml_tools import QNN
from qadence.constructors import ObservableConfig
from qadence.operations import Z
from qadence.types import (
AnsatzType, BackendName, BasisSet, ObservableTransform, ReuploadScaling, Strategy
)
register = 4
obs_config = ObservableConfig(
detuning=Z,
scale=5.0,
shift=0.0,
transformation_type=ObservableTransform.SCALE,
trainable_transform=None,
)
fm_config = FeatureMapConfig(
num_features=2,
inputs=["x", "y"],
basis_set=BasisSet.FOURIER,
reupload_scaling=ReuploadScaling.CONSTANT,
feature_range={
"x": (-1.0, 1.0),
"y": (0.0, 1.0),
},
)
ansatz_config = AnsatzConfig(
depth=2,
ansatz_type=AnsatzType.HEA,
ansatz_strategy=Strategy.DIGITAL,
)
qnn = QNN.from_configs(
register, obs_config, fm_config, ansatz_config, backend=BackendName.PYQTORCH
)
x = torch.rand(2, 2)
y = qnn(x)
Source code in qadence/ml_tools/models.py
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 |
|
derivative(ufa, x, derivative_indices)
Compute derivatives w.r.t.
inputs of a UFA with a single output. The
derivative_indices
specify which derivative(s) are computed. E.g.
derivative_indices=(1,2)
would compute the a second order derivative w.r.t
to the indices 1
and 2
of the input tensor.
PARAMETER | DESCRIPTION |
---|---|
ufa |
The model for which we want to compute the derivative.
TYPE:
|
x |
(batch_size, input_size) input tensor.
TYPE:
|
derivative_indices |
Define which derivatives to compute.
TYPE:
|
Examples:
If we create a UFA with three inputs and denote the first, second, and third
input with x
, y
, and z
we can compute the following derivatives w.r.t
to those inputs:
import torch
from qadence.ml_tools.models import derivative, QNN
from qadence.ml_tools.config import FeatureMapConfig, AnsatzConfig
from qadence.constructors.hamiltonians import ObservableConfig
from qadence.operations import Z
fm_config = FeatureMapConfig(num_features=3, inputs=["x", "y", "z"])
ansatz_config = AnsatzConfig()
obs_config = ObservableConfig(detuning=Z)
f = QNN.from_configs(
register=3, obs_config=obs_config, fm_config=fm_config, ansatz_config=ansatz_config,
)
inputs = torch.rand(5,3,requires_grad=True)
# df_dx
derivative(f, inputs, (0,))
# d2f_dydz
derivative(f, inputs, (1,2))
# d3fdy2dx
derivative(f, inputs, (1,1,0))
Source code in qadence/ml_tools/models.py
format_to_dict_fn(inputs=[])
Format an input tensor into the format required by the forward pass.
The tensor is assumed to have dimensions: n_batches x in_features where in_features corresponds to the number of input features of the QNN
Source code in qadence/ml_tools/models.py
Callback(on='idle', called_every=1, callback=None, callback_condition=None, modify_optimize_result=None)
Base class for defining various training callbacks.
ATTRIBUTE | DESCRIPTION |
---|---|
|
The event on which to trigger the callback. Must be a valid on value from: ["train_start", "train_end", "train_epoch_start", "train_epoch_end", "train_batch_start", "train_batch_end","val_epoch_start", "val_epoch_end", "val_batch_start", "val_batch_end", "test_batch_start", "test_batch_end"]
TYPE:
|
|
Frequency of callback calls in terms of iterations.
TYPE:
|
|
The function to call if the condition is met.
TYPE:
|
|
Condition to check before calling.
TYPE:
|
|
Function to modify
TYPE:
|
A callback can be defined in two ways:
- By providing a callback function directly in the base class: This is useful for simple callbacks that don't require subclassing.
Example:
from qadence.ml_tools.callbacks import Callback
def custom_callback_function(trainer, config, writer):
print("Custom callback executed.")
custom_callback = Callback(
on="train_end",
called_every=5,
callback=custom_callback_function
)
- By inheriting and implementing the
run_callback
method: This is suitable for more complex callbacks that require customization.
Example:
from qadence.ml_tools.callbacks import Callback
class CustomCallback(Callback):
def run_callback(self, trainer, config, writer):
print("Custom behavior in the inherited run_callback method.")
custom_callback = CustomCallback(on="train_end", called_every=10)
Source code in qadence/ml_tools/callbacks/callback.py
on: TrainingStage | str
property
writable
Returns the TrainingStage.
RETURNS | DESCRIPTION |
---|---|
TrainingStage
|
TrainingStage for the callback
TYPE:
|
__call__(when, trainer, config, writer)
Executes the callback if conditions are met.
PARAMETER | DESCRIPTION |
---|---|
when |
The event when the callback is triggered.
TYPE:
|
trainer |
The training object.
TYPE:
|
config |
The configuration object.
TYPE:
|
writer |
The writer object for logging.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
Any
|
Result of the callback function if executed.
TYPE:
|
Source code in qadence/ml_tools/callbacks/callback.py
run_callback(trainer, config, writer)
Executes the defined callback.
PARAMETER | DESCRIPTION |
---|---|
trainer |
The training object.
TYPE:
|
config |
The configuration object.
TYPE:
|
writer |
The writer object for logging.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
Any
|
Result of the callback execution.
TYPE:
|
RAISES | DESCRIPTION |
---|---|
|
If not implemented in subclasses. |
Source code in qadence/ml_tools/callbacks/callback.py
LoadCheckpoint(on='idle', called_every=1, callback=None, callback_condition=None, modify_optimize_result=None)
Bases:
Callback to load a model checkpoint.
Source code in qadence/ml_tools/callbacks/callback.py
run_callback(trainer, config, writer)
Loads a model checkpoint.
PARAMETER | DESCRIPTION |
---|---|
trainer |
The training object.
TYPE:
|
config |
The configuration object.
TYPE:
|
writer |
The writer object for logging.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
Any
|
The result of loading the checkpoint.
TYPE:
|
Source code in qadence/ml_tools/callbacks/callback.py
LogHyperparameters(on='idle', called_every=1, callback=None, callback_condition=None, modify_optimize_result=None)
Bases:
Callback to log hyperparameters using the writer.
The LogHyperparameters
callback can be added to the TrainConfig
callbacks
as a custom user defined callback.
Example Usage in TrainConfig
:
To use LogHyperparameters
, include it in the callbacks
list when setting up your
TrainConfig
:
from qadence.ml_tools import TrainConfig
from qadence.ml_tools.callbacks import LogHyperparameters
# Create an instance of the LogHyperparameters callback
log_hyper_callback = LogHyperparameters(on = "val_batch_end", called_every = 100)
config = TrainConfig(
max_iter=10000,
# Print metrics every 1000 training epochs
print_every=1000,
# Add the custom callback that runs every 100 val_batch_end
callbacks=[log_hyper_callback]
)
Source code in qadence/ml_tools/callbacks/callback.py
run_callback(trainer, config, writer)
Logs hyperparameters using the writer.
PARAMETER | DESCRIPTION |
---|---|
trainer |
The training object.
TYPE:
|
config |
The configuration object.
TYPE:
|
writer |
The writer object for logging.
TYPE:
|
Source code in qadence/ml_tools/callbacks/callback.py
LogModelTracker(on='idle', called_every=1, callback=None, callback_condition=None, modify_optimize_result=None)
Bases:
Callback to log the model using the writer.
Source code in qadence/ml_tools/callbacks/callback.py
run_callback(trainer, config, writer)
Logs the model using the writer.
PARAMETER | DESCRIPTION |
---|---|
trainer |
The training object.
TYPE:
|
config |
The configuration object.
TYPE:
|
writer |
The writer object for logging.
TYPE:
|
Source code in qadence/ml_tools/callbacks/callback.py
PlotMetrics(on='idle', called_every=1, callback=None, callback_condition=None, modify_optimize_result=None)
Bases:
Callback to plot metrics using the writer.
The PlotMetrics
callback can be added to the TrainConfig
callbacks as
a custom user defined callback.
Example Usage in TrainConfig
:
To use PlotMetrics
, include it in the callbacks
list when setting up your
TrainConfig
:
from qadence.ml_tools import TrainConfig
from qadence.ml_tools.callbacks import PlotMetrics
# Create an instance of the PlotMetrics callback
plot_metrics_callback = PlotMetrics(on = "val_batch_end", called_every = 100)
config = TrainConfig(
max_iter=10000,
# Print metrics every 1000 training epochs
print_every=1000,
# Add the custom callback that runs every 100 val_batch_end
callbacks=[plot_metrics_callback]
)
Source code in qadence/ml_tools/callbacks/callback.py
run_callback(trainer, config, writer)
Plots metrics using the writer.
PARAMETER | DESCRIPTION |
---|---|
trainer |
The training object.
TYPE:
|
config |
The configuration object.
TYPE:
|
writer |
The writer object for logging.
TYPE:
|
Source code in qadence/ml_tools/callbacks/callback.py
PrintMetrics(on='idle', called_every=1, callback=None, callback_condition=None, modify_optimize_result=None)
Bases:
Callback to print metrics using the writer.
The PrintMetrics
callback can be added to the TrainConfig
callbacks as a custom user defined callback.
Example Usage in TrainConfig
:
To use PrintMetrics
, include it in the callbacks
list when
setting up your TrainConfig
:
from qadence.ml_tools import TrainConfig
from qadence.ml_tools.callbacks import PrintMetrics
# Create an instance of the PrintMetrics callback
print_metrics_callback = PrintMetrics(on = "val_batch_end", called_every = 100)
config = TrainConfig(
max_iter=10000,
# Print metrics every 1000 training epochs
print_every=1000,
# Add the custom callback that runs every 100 val_batch_end
callbacks=[print_metrics_callback]
)
Source code in qadence/ml_tools/callbacks/callback.py
run_callback(trainer, config, writer)
Prints metrics using the writer.
PARAMETER | DESCRIPTION |
---|---|
trainer |
The training object.
TYPE:
|
config |
The configuration object.
TYPE:
|
writer |
The writer object for logging.
TYPE:
|
Source code in qadence/ml_tools/callbacks/callback.py
SaveBestCheckpoint(on, called_every)
Bases:
Callback to save the best model checkpoint based on a validation criterion.
Initializes the SaveBestCheckpoint callback.
PARAMETER | DESCRIPTION |
---|---|
on |
The event to trigger the callback.
TYPE:
|
called_every |
Frequency of callback calls in terms of iterations.
TYPE:
|
Source code in qadence/ml_tools/callbacks/callback.py
run_callback(trainer, config, writer)
Saves the checkpoint if the current loss is better than the best loss.
PARAMETER | DESCRIPTION |
---|---|
trainer |
The training object.
TYPE:
|
config |
The configuration object.
TYPE:
|
writer |
The writer object for logging.
TYPE:
|
Source code in qadence/ml_tools/callbacks/callback.py
SaveCheckpoint(on='idle', called_every=1, callback=None, callback_condition=None, modify_optimize_result=None)
Bases:
Callback to save a model checkpoint.
The SaveCheckpoint
callback can be added to the TrainConfig
callbacks
as a custom user defined callback.
Example Usage in TrainConfig
:
To use SaveCheckpoint
, include it in the callbacks
list when setting up your
TrainConfig
:
from qadence.ml_tools import TrainConfig
from qadence.ml_tools.callbacks import SaveCheckpoint
# Create an instance of the SaveCheckpoint callback
save_checkpoint_callback = SaveCheckpoint(on = "val_batch_end", called_every = 100)
config = TrainConfig(
max_iter=10000,
# Print metrics every 1000 training epochs
print_every=1000,
# Add the custom callback that runs every 100 val_batch_end
callbacks=[save_checkpoint_callback]
)
Source code in qadence/ml_tools/callbacks/callback.py
run_callback(trainer, config, writer)
Saves a model checkpoint.
PARAMETER | DESCRIPTION |
---|---|
trainer |
The training object.
TYPE:
|
config |
The configuration object.
TYPE:
|
writer |
The writer object for logging.
TYPE:
|
Source code in qadence/ml_tools/callbacks/callback.py
WriteMetrics(on='idle', called_every=1, callback=None, callback_condition=None, modify_optimize_result=None)
Bases:
Callback to write metrics using the writer.
The WriteMetrics
callback can be added to the TrainConfig
callbacks as
a custom user defined callback.
Example Usage in TrainConfig
:
To use WriteMetrics
, include it in the callbacks
list when setting up your
TrainConfig
:
from qadence.ml_tools import TrainConfig
from qadence.ml_tools.callbacks import WriteMetrics
# Create an instance of the WriteMetrics callback
write_metrics_callback = WriteMetrics(on = "val_batch_end", called_every = 100)
config = TrainConfig(
max_iter=10000,
# Print metrics every 1000 training epochs
print_every=1000,
# Add the custom callback that runs every 100 val_batch_end
callbacks=[write_metrics_callback]
)
Source code in qadence/ml_tools/callbacks/callback.py
run_callback(trainer, config, writer)
Writes metrics using the writer.
PARAMETER | DESCRIPTION |
---|---|
trainer |
The training object.
TYPE:
|
config |
The configuration object.
TYPE:
|
writer |
The writer object for logging.
TYPE:
|
Source code in qadence/ml_tools/callbacks/callback.py
BaseTrainer(model, optimizer, config, loss_fn='mse', optimize_step=optimize_step, train_dataloader=None, val_dataloader=None, test_dataloader=None, max_batches=None)
Base class for training machine learning models using a given optimizer.
The base class implements contextmanager for gradient based/free optimization, properties, property setters, input validations, callback decorator generator, and empty hooks for different training steps.
This class provides
- Context managers for enabling/disabling gradient-based optimization
- Properties for managing models, optimizers, and dataloaders
- Input validations and a callback decorator generator
- Config and callback managers using the provided
TrainConfig
ATTRIBUTE | DESCRIPTION |
---|---|
|
Indicates if gradients are used for optimization. Default is True.
TYPE:
|
|
The neural network model.
TYPE:
|
|
The optimizer for training.
TYPE:
|
|
The configuration settings for training.
TYPE:
|
|
DataLoader for training data.
TYPE:
|
|
DataLoader for validation data.
TYPE:
|
|
DataLoader for testing data.
TYPE:
|
|
Function for performing an optimization step.
TYPE:
|
|
loss function to use. Default loss function used is 'mse'
TYPE:
|
|
Number of training batches. In case of InfiniteTensorDataset only 1 batch per epoch is used.
TYPE:
|
|
Number of validation batches. In case of InfiniteTensorDataset only 1 batch per epoch is used.
TYPE:
|
|
Number of test batches. In case of InfiniteTensorDataset only 1 batch per epoch is used.
TYPE:
|
|
Current state in the training process
TYPE:
|
Initializes the BaseTrainer.
PARAMETER | DESCRIPTION |
---|---|
model |
The model to train.
TYPE:
|
optimizer |
The optimizer for training.
TYPE:
|
config |
The TrainConfig settings for training.
TYPE:
|
loss_fn |
The loss function to use. str input to be specified to use a default loss function. currently supported loss functions: 'mse', 'cross_entropy'. If not specified, default mse loss will be used.
TYPE:
|
train_dataloader |
DataLoader for training data. If the model does not need data to evaluate loss, no dataset should be provided.
TYPE:
|
val_dataloader |
DataLoader for validation data.
TYPE:
|
test_dataloader |
DataLoader for testing data.
TYPE:
|
max_batches |
Maximum number of batches to process per epoch. This is only valid in case of finite TensorDataset dataloaders. if max_batches is not None, the maximum number of batches used will be min(max_batches, len(dataloader.dataset)) In case of InfiniteTensorDataset only 1 batch per epoch is used.
TYPE:
|
Source code in qadence/ml_tools/train_utils/base_trainer.py
config: TrainConfig
property
writable
Returns the training configuration.
RETURNS | DESCRIPTION |
---|---|
TrainConfig
|
The configuration object.
TYPE:
|
model: nn.Module
property
writable
Returns the model if set, otherwise raises an error.
RETURNS | DESCRIPTION |
---|---|
|
nn.Module: The model. |
optimizer: optim.Optimizer | NGOptimizer | None
property
writable
Returns the optimizer if set, otherwise raises an error.
RETURNS | DESCRIPTION |
---|---|
|
optim.Optimizer | NGOptimizer | None: The optimizer. |
test_dataloader: DataLoader
property
writable
Returns the test DataLoader, validating its type.
RETURNS | DESCRIPTION |
---|---|
DataLoader
|
The DataLoader for testing data.
TYPE:
|
train_dataloader: DataLoader
property
writable
Returns the training DataLoader, validating its type.
RETURNS | DESCRIPTION |
---|---|
DataLoader
|
The DataLoader for training data.
TYPE:
|
use_grad: bool
property
writable
Returns the optimization framework for the trainer.
use_grad = True : Gradient based optimization use_grad = False : Gradient free optimization
RETURNS | DESCRIPTION |
---|---|
bool
|
Bool value for using gradient.
TYPE:
|
val_dataloader: DataLoader
property
writable
Returns the validation DataLoader, validating its type.
RETURNS | DESCRIPTION |
---|---|
DataLoader
|
The DataLoader for validation data.
TYPE:
|
callback(phase)
staticmethod
Decorator for executing callbacks before and after a phase.
Phase are different hooks during the training. list of valid phases is defined in Callbacks. We also update the current state of the training process in the callback decorator.
PARAMETER | DESCRIPTION |
---|---|
phase |
The phase for which the callback is executed (e.g., "train", "train_epoch", "train_batch").
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
Callable
|
The decorated function.
TYPE:
|
Source code in qadence/ml_tools/train_utils/base_trainer.py
disable_grad_opt(optimizer=None)
Context manager to temporarily disable gradient-based optimization.
PARAMETER | DESCRIPTION |
---|---|
optimizer |
The Nevergrad optimizer to use. If no optimizer is provided, default optimizer for trainer object will be used.
TYPE:
|
Source code in qadence/ml_tools/train_utils/base_trainer.py
enable_grad_opt(optimizer=None)
Context manager to temporarily enable gradient-based optimization.
PARAMETER | DESCRIPTION |
---|---|
optimizer |
The PyTorch optimizer to use. If no optimizer is provided, default optimizer for trainer object will be used.
TYPE:
|
Source code in qadence/ml_tools/train_utils/base_trainer.py
on_test_batch_end(test_batch_loss_metrics)
Called at the end of each testing batch.
PARAMETER | DESCRIPTION |
---|---|
test_batch_loss_metrics |
Metrics for the testing batch loss. tuple of (loss, metrics)
TYPE:
|
Source code in qadence/ml_tools/train_utils/base_trainer.py
on_test_batch_start(batch)
Called at the start of each testing batch.
PARAMETER | DESCRIPTION |
---|---|
batch |
A batch of data from the DataLoader. Typically a tuple containing input tensors and corresponding target tensors.
TYPE:
|
Source code in qadence/ml_tools/train_utils/base_trainer.py
on_train_batch_end(train_batch_loss_metrics)
Called at the end of each training batch.
PARAMETER | DESCRIPTION |
---|---|
train_batch_loss_metrics |
Metrics for the training batch loss. tuple of (loss, metrics)
TYPE:
|
Source code in qadence/ml_tools/train_utils/base_trainer.py
on_train_batch_start(batch)
Called at the start of each training batch.
PARAMETER | DESCRIPTION |
---|---|
batch |
A batch of data from the DataLoader. Typically a tuple containing input tensors and corresponding target tensors.
TYPE:
|
Source code in qadence/ml_tools/train_utils/base_trainer.py
on_train_end(train_losses, val_losses=None)
Called at the end of training.
PARAMETER | DESCRIPTION |
---|---|
train_losses |
Metrics for the training losses. list -> list -> tuples Epochs -> Training Batches -> (loss, metrics)
TYPE:
|
val_losses |
Metrics for the validation losses. list -> list -> tuples Epochs -> Validation Batches -> (loss, metrics)
TYPE:
|
Source code in qadence/ml_tools/train_utils/base_trainer.py
on_train_epoch_end(train_epoch_loss_metrics)
Called at the end of each training epoch.
PARAMETER | DESCRIPTION |
---|---|
train_epoch_loss_metrics |
Metrics for the training epoch losses. list -> tuples Training Batches -> (loss, metrics)
TYPE:
|
Source code in qadence/ml_tools/train_utils/base_trainer.py
on_train_epoch_start()
on_train_start()
on_val_batch_end(val_batch_loss_metrics)
Called at the end of each validation batch.
PARAMETER | DESCRIPTION |
---|---|
val_batch_loss_metrics |
Metrics for the validation batch loss. tuple of (loss, metrics)
TYPE:
|
Source code in qadence/ml_tools/train_utils/base_trainer.py
on_val_batch_start(batch)
Called at the start of each validation batch.
PARAMETER | DESCRIPTION |
---|---|
batch |
A batch of data from the DataLoader. Typically a tuple containing input tensors and corresponding target tensors.
TYPE:
|
Source code in qadence/ml_tools/train_utils/base_trainer.py
on_val_epoch_end(val_epoch_loss_metrics)
Called at the end of each validation epoch.
PARAMETER | DESCRIPTION |
---|---|
val_epoch_loss_metrics |
Metrics for the validation epoch loss. list -> tuples Validation Batches -> (loss, metrics)
TYPE:
|
Source code in qadence/ml_tools/train_utils/base_trainer.py
on_val_epoch_start()
set_use_grad(value)
classmethod
Sets the global use_grad flag.
PARAMETER | DESCRIPTION |
---|---|
value |
Whether to use gradient-based optimization.
TYPE:
|
Source code in qadence/ml_tools/train_utils/base_trainer.py
BaseWriter
Bases:
Abstract base class for experiment tracking writers.
METHOD | DESCRIPTION |
---|---|
|
Opens the writer and sets up the logging environment. |
|
Closes the writer and finalizes any ongoing logging processes. |
|
Prints metrics and loss in a formatted manner. |
|
Writes the optimization results to the tracking tool. |
|
Logs the hyperparameters to the tracking tool. |
|
Logs model plots using provided plotting functions. |
|
Logs the model and any relevant information. |
close()
abstractmethod
log_hyperparams(hyperparams)
abstractmethod
Logs hyperparameters.
PARAMETER | DESCRIPTION |
---|---|
hyperparams |
A dictionary of hyperparameters to log.
TYPE:
|
Source code in qadence/ml_tools/callbacks/writer_registry.py
log_model(model, train_dataloader=None, val_dataloader=None, test_dataloader=None)
abstractmethod
Logs the model and associated data.
PARAMETER | DESCRIPTION |
---|---|
model |
The model to log.
TYPE:
|
train_dataloader |
DataLoader for training data.
TYPE:
|
val_dataloader |
DataLoader for validation data.
TYPE:
|
test_dataloader |
DataLoader for testing data.
TYPE:
|
Source code in qadence/ml_tools/callbacks/writer_registry.py
open(config, iteration=None)
abstractmethod
Opens the writer and prepares it for logging.
PARAMETER | DESCRIPTION |
---|---|
config |
Configuration object containing settings for logging.
TYPE:
|
iteration |
The iteration step to start logging from. Defaults to None.
TYPE:
|
Source code in qadence/ml_tools/callbacks/writer_registry.py
plot(model, iteration, plotting_functions)
abstractmethod
Logs plots of the model using provided plotting functions.
PARAMETER | DESCRIPTION |
---|---|
model |
The model to plot.
TYPE:
|
iteration |
The current iteration number.
TYPE:
|
plotting_functions |
Functions used to generate plots.
TYPE:
|
Source code in qadence/ml_tools/callbacks/writer_registry.py
print_metrics(result)
Prints the metrics and loss in a readable format.
PARAMETER | DESCRIPTION |
---|---|
result |
The optimization results to display.
TYPE:
|
Source code in qadence/ml_tools/callbacks/writer_registry.py
write(result)
abstractmethod
Logs the results of the current iteration.
PARAMETER | DESCRIPTION |
---|---|
result |
The optimization results to log.
TYPE:
|
Source code in qadence/ml_tools/callbacks/writer_registry.py
MLFlowWriter()
Bases:
Writer for logging to MLflow.
ATTRIBUTE | DESCRIPTION |
---|---|
|
The active MLflow run.
TYPE:
|
|
The MLflow module.
TYPE:
|
Source code in qadence/ml_tools/callbacks/writer_registry.py
close()
get_signature_from_dataloader(model, dataloader)
Infers the signature of the model based on the input data from the dataloader.
PARAMETER | DESCRIPTION |
---|---|
model |
The model to use for inference.
TYPE:
|
dataloader |
DataLoader for model inputs.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
|
Optional[Any]: The inferred signature, if available. |
Source code in qadence/ml_tools/callbacks/writer_registry.py
log_hyperparams(hyperparams)
Logs hyperparameters to MLflow.
PARAMETER | DESCRIPTION |
---|---|
hyperparams |
A dictionary of hyperparameters to log.
TYPE:
|
Source code in qadence/ml_tools/callbacks/writer_registry.py
log_model(model, train_dataloader=None, val_dataloader=None, test_dataloader=None)
Logs the model and its signature to MLflow using the provided data loaders.
PARAMETER | DESCRIPTION |
---|---|
model |
The model to log.
TYPE:
|
train_dataloader |
DataLoader for training data.
TYPE:
|
val_dataloader |
DataLoader for validation data.
TYPE:
|
test_dataloader |
DataLoader for testing data.
TYPE:
|
Source code in qadence/ml_tools/callbacks/writer_registry.py
open(config, iteration=None)
Opens the MLflow writer and initializes an MLflow run.
PARAMETER | DESCRIPTION |
---|---|
config |
Configuration object containing settings for logging.
TYPE:
|
iteration |
The iteration step to start logging from. Defaults to None.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
mlflow
|
The MLflow module instance.
TYPE:
|
Source code in qadence/ml_tools/callbacks/writer_registry.py
plot(model, iteration, plotting_functions)
Logs plots of the model using provided plotting functions.
PARAMETER | DESCRIPTION |
---|---|
model |
The model to plot.
TYPE:
|
iteration |
The current iteration number.
TYPE:
|
plotting_functions |
Functions used to generate plots.
TYPE:
|
Source code in qadence/ml_tools/callbacks/writer_registry.py
write(result)
Logs the results of the current iteration to MLflow.
PARAMETER | DESCRIPTION |
---|---|
result |
The optimization results to log.
TYPE:
|
Source code in qadence/ml_tools/callbacks/writer_registry.py
TensorBoardWriter()
Bases:
Writer for logging to TensorBoard.
ATTRIBUTE | DESCRIPTION |
---|---|
|
The TensorBoard SummaryWriter instance.
TYPE:
|
Source code in qadence/ml_tools/callbacks/writer_registry.py
close()
log_hyperparams(hyperparams)
Logs hyperparameters to TensorBoard.
PARAMETER | DESCRIPTION |
---|---|
hyperparams |
A dictionary of hyperparameters to log.
TYPE:
|
Source code in qadence/ml_tools/callbacks/writer_registry.py
log_model(model, train_dataloader=None, val_dataloader=None, test_dataloader=None)
Logs the model.
Currently not supported by TensorBoard.
PARAMETER | DESCRIPTION |
---|---|
model |
The model to log.
TYPE:
|
train_dataloader |
DataLoader for training data.
TYPE:
|
val_dataloader |
DataLoader for validation data.
TYPE:
|
test_dataloader |
DataLoader for testing data.
TYPE:
|
Source code in qadence/ml_tools/callbacks/writer_registry.py
open(config, iteration=None)
Opens the TensorBoard writer.
PARAMETER | DESCRIPTION |
---|---|
config |
Configuration object containing settings for logging.
TYPE:
|
iteration |
The iteration step to start logging from. Defaults to None.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
SummaryWriter
|
The initialized TensorBoard writer.
TYPE:
|
Source code in qadence/ml_tools/callbacks/writer_registry.py
plot(model, iteration, plotting_functions)
Logs plots of the model using provided plotting functions.
PARAMETER | DESCRIPTION |
---|---|
model |
The model to plot.
TYPE:
|
iteration |
The current iteration number.
TYPE:
|
plotting_functions |
Functions used to generate plots.
TYPE:
|
Source code in qadence/ml_tools/callbacks/writer_registry.py
write(result)
Logs the results of the current iteration to TensorBoard.
PARAMETER | DESCRIPTION |
---|---|
result |
The optimization results to log.
TYPE:
|
Source code in qadence/ml_tools/callbacks/writer_registry.py
get_writer(tracking_tool)
Factory method to get the appropriate writer based on the tracking tool.
PARAMETER | DESCRIPTION |
---|---|
tracking_tool |
The experiment tracking tool to use.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
BaseWriter
|
An instance of the appropriate writer.
TYPE:
|