cann.engine package

Submodules

cann.engine.calibration module

cann.engine.calibration.calibrate_model(trained_model, market_surface, calibration_config)[source]

Calibrate model parameters to a market surface using a trained surrogate.

The columns of market_surface.market_inputs must match the feature ordering specified by trained_model.model_config.market_inputs.

This constructs a loss function J(θ) and passes it to the optimizer.

Parameters:
  • trained_model (TrainedModel) – The trained surrogate model to be calibrated.

  • market_surface (MarketSurface) – The market surface data for calibration.

  • calibration_config (CalibrationConfig) – Configuration settings for the calibration process.

Returns:

The result of the calibration optimization.

Return type:

CalibrationResult

Notes

The optimization is performed with a global optimizer (Differential Evolution). Surrogate inference is batched and will use CUDA if available, otherwise CPU.

cann.engine.calibration.calibrate_model_with_fixed_parameters(*, trained_model, market_surface, calibration_config, fixed_parameters, free_parameter_names=None)[source]

Calibrate only a subset of parameters while holding others fixed.

This is useful when you want, e.g., a 3-parameter calibration using a surrogate that was trained on the full 5-parameter Heston space.

Parameters:
  • trained_model – Trained surrogate model.

  • market_surface – Observed market surface.

  • calibration_config – Optimizer configuration.

  • fixed_parameters – Mapping of parameter name -> fixed value.

  • free_parameter_names – Optional explicit list of parameter names to optimize. If not provided, all parameters not in fixed_parameters are optimized.

Returns:

CalibrationResult where optimal_parameters is the full parameter vector in model-config ordering.

cann.engine.calibration_config module

class cann.engine.calibration_config.CalibrationConfig(optimizer='de', strategy='best1bin', max_iter=2000, pop_size=10, tol=0.01, mutation=(0.5, 1.0), recombination=0.7, init='latinhypercube', polish=True, batch_size=32768, weight_atm=1.0, seed=42)[source]

Bases: object

Settings for the calibration optimization process.

Key fields include max_iter, pop_size, strategy, and inference batch_size.

batch_size = 32768
classmethod from_dict(cfg)[source]

Create a CalibrationConfig instance from a dictionary.

Parameters:

cfg (dict) – Dictionary containing configuration parameters.

Returns:

Parsed calibration configuration.

Return type:

CalibrationConfig

Notes

If mutation is provided as a string (e.g. from YAML), it is parsed via ast.literal_eval() when possible.

init = 'latinhypercube'
max_iter = 2000
mutation = (0.5, 1.0)
optimizer = 'de'
polish = True
pop_size = 10
recombination = 0.7
seed = 42
strategy = 'best1bin'
tol = 0.01
weight_atm = 1.0
class cann.engine.calibration_config.CalibrationResult(optimal_parameters, final_loss, num_iterations, num_function_evals, runtime_seconds, converged, diagnostics)[source]

Bases: object

Result of the calibration optimization process after optimization.

Fields include optimal_parameters, final_loss, convergence diagnostics, and optional optimizer diagnostics.

converged
diagnostics
final_loss
num_function_evals
num_iterations
optimal_parameters
runtime_seconds

cann.engine.training module

Training engine and trained-surrogate containers.

This module contains the high-level training entrypoint train_surrogate() and the thin wrappers (SurrogateModel, TrainedModel) used throughout the package.

class cann.engine.training.SurrogateModel(network, model_cfg, version='0.0.1')[source]

Bases: object

Wrapper around the neural network surrogate, scalers and metadata.

Fields:

network (PyTorch module), model_cfg (feature/parameter layout), and optional version string.

eval()[source]

Set the surrogate model to evaluation mode.

Returns:

Self, in evaluation mode.

Return type:

SurrogateModel

model_cfg
network
predict(parameters, market_inputs, batch_size=8192, device='cpu')

Convenience prediction helper for calibration / sanity checks.

Parameters:
  • parameters (np.ndarray) – Array of model parameters with shape (N, n).

  • market_inputs (np.ndarray) – Array of market input features with shape (N, m).

  • batch_size (int) – Batch size for prediction. Defaults to 8192.

  • device (torch.device | str) – Device to run prediction on. Defaults to “cpu”.

Returns:

Predicted outputs with shape (N, output_dim).

Return type:

np.ndarray

to(device)[source]

Move the surrogate model to the specified device.

Parameters:

device – Target device (e.g., “cpu”, “cuda”, “mps”).

train(train_dataset, validation_dataset, training_config, verbose=True, checkpoint_dir=None, checkpoint_every_epochs=None, resume_checkpoint=None, checkpoint_metadata=None)[source]

Train the surrogate model on the provided training dataset.

Parameters:
  • train_dataset (ParamSurfaceDataset) – Dataset for training.

  • validation_dataset (ParamSurfaceDataset | None) – Dataset for validation.

  • training_config (TrainingConfig) – Configuration for training.

  • verbose (bool) – Whether to print training progress. Defaults to True.

  • checkpoint_dir (str | Path | None) – Optional directory for resumable checkpoints.

  • checkpoint_every_epochs (int | None) – Save a checkpoint after this many epochs.

  • resume_checkpoint (str | Path | None) – Optional checkpoint to resume from.

  • checkpoint_metadata (Mapping[str, Any] | None) – Provenance stored in checkpoints.

Returns:

A trained model wrapper containing this surrogate and training metadata.

Return type:

TrainedModel

Raises:

ValueError – If the provided datasets do not contain observed targets.

version = '0.0.1'
class cann.engine.training.TrainedModel(surrogate, training_config, model_config, training_metrics, path=None, training_date=<factory>)[source]

Bases: object

Container for a trained surrogate model along with training metadata.

Fields:

surrogate plus associated configs and training metadata.

model_config
path = None
surrogate
training_config
training_date
training_metrics
cann.engine.training.evaluate_surrogate_dataset(surrogate, dataset, *, batch_size=8192, device='cpu')[source]

Evaluate a trained surrogate against an observed dataset.

cann.engine.training.train_surrogate(model_config, parameters, market_inputs, observed, verbose=True, training_config=None, checkpoint_dir=None, checkpoint_every_epochs=None, resume_checkpoint=None, checkpoint_metadata=None)[source]

Train a neural network surrogate model on the provided dataset. The parameters and market_inputs should be numpy arrays with columns in the order of the parameters and market_inputs defined by the model_config provided.

This is the high-level entry point used by the public API. Implementation will perform: - dataset split - surrogate construction - training loop - metric computation

Parameters:
  • model_config (ModelConfig) – Configuration for the underlying pricing model.

  • parameters (np.ndarray) – Array of model parameters with shape (N, n).

  • market_inputs (np.ndarray) – Array of market input features with shape (N, m).

  • observed (np.ndarray) – Array of observed market values with shape (N, ) or (N, 1).

  • verbose (bool) – Whether to print training progress. Defaults to True.

  • training_config (TrainingConfig | None) – Training hyperparameters. If not provided, ModelConfig.train_defaults is used.

  • checkpoint_dir (str | Path | None) – Optional directory for resumable checkpoints.

  • checkpoint_every_epochs (int | None) – Save a checkpoint after this many epochs.

  • resume_checkpoint (str | Path | None) – Optional checkpoint to resume from.

  • checkpoint_metadata (Mapping[str, Any] | None) – Provenance stored in checkpoints.

Returns:

The trained model and (optionally) the test split dataset (None if the test fraction is 0).

Return type:

Tuple[TrainedModel, ParamSurfaceDataset | None]

Raises:

ValueError – If no training configuration is available.

cann.engine.training_config module

class cann.engine.training_config.TrainingConfig(batch_size=32768, epochs=4800, dropout_rate=0.0, batch_norm=False, learning_rate=0.001, lr_decay_every_epochs=None, lr_decay_factor=0.5, min_learning_rate=0.0, optimizer='adam', loss='mse', validation_every_epochs=100, hidden_layers=<factory>, activation='relu', weight_init='default', weight_init_min=-0.05, weight_init_max=0.05, bias_init=None, train_val_test_split=(0.8, 0.1, 0.1), shuffle=True, early_stopping=False, device='cuda', random_seed=42)[source]

Bases: object

Hyperparameters and settings for training the surrogate model.

Commonly adjusted fields are epochs, batch_size, learning_rate, hidden_layers, activation, and train_val_test_split.

activation = 'relu'
batch_norm = False
batch_size = 32768
bias_init = None
device = 'cuda'
dropout_rate = 0.0
early_stopping = False
epochs = 4800
classmethod from_dict(cfg)[source]

Create a TrainingConfig instance from a dictionary.

Parameters:

cfg (dict) – Dictionary containing configuration parameters.

Returns:

Parsed training configuration.

Return type:

TrainingConfig

Raises:

TypeError – If the dictionary contains keys not accepted by TrainingConfig.

hidden_layers
learning_rate = 0.001
loss = 'mse'
lr_decay_every_epochs = None
lr_decay_factor = 0.5
min_learning_rate = 0.0
optimizer = 'adam'
random_seed = 42
shuffle = True
train_val_test_split = (0.8, 0.1, 0.1)
validation_every_epochs = 100
weight_init = 'default'
weight_init_max = 0.05
weight_init_min = -0.05

Module contents