Skip to content

optuna_tune

Optuna tuning module.

Classes:

  • Objective

    Objective class for Optuna tuning.

Functions:

Objective

Objective(
    model_class: type[StimulusModel],
    network_params: dict[
        str, TunableParameter | VariableList
    ],
    optimizer_params: dict[str, TunableParameter],
    data_params: dict[str, TunableParameter],
    loss_params: dict[str, TunableParameter],
    train_torch_dataset: Dataset,
    val_torch_dataset: Dataset,
    artifact_store: Any,
    max_samples: int = 1000,
    compute_objective_every_n_samples: int = 50,
    target_metric: str = "val_loss",
    device: device | None = None,
)

Objective class for Optuna tuning.

Parameters:

  • model_class (type[StimulusModel]) –

    The model class to be tuned.

  • network_params (dict[str, TunableParameter | VariableList]) –

    The network parameters to be tuned.

  • optimizer_params (dict[str, TunableParameter]) –

    The optimizer parameters to be tuned.

  • data_params (dict[str, TunableParameter]) –

    The data parameters to be tuned.

  • loss_params (dict[str, TunableParameter]) –

    The loss parameters to be tuned.

  • train_torch_dataset (Dataset) –

    The training dataset.

  • val_torch_dataset (Dataset) –

    The validation dataset.

  • artifact_store (Any) –

    The artifact store to save the model and optimizer.

  • max_samples (int, default: 1000 ) –

    The maximum number of samples to train.

  • compute_objective_every_n_samples (int, default: 50 ) –

    The number of samples to compute the objective.

  • target_metric (str, default: 'val_loss' ) –

    The target metric to optimize.

  • device (device | None, default: None ) –

    The device to run the training on.

Methods:

  • get_metrics

    Compute the objective metric(s) for the tuning process.

  • objective

    Compute the objective metric(s) for the tuning process.

  • save_checkpoint

    Save the model and optimizer to the trial.

Source code in src/stimulus/learner/optuna_tune.py
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
def __init__(
    self,
    model_class: type[StimulusModel],
    network_params: dict[str, model_schema.TunableParameter | model_schema.VariableList],
    optimizer_params: dict[str, model_schema.TunableParameter],
    data_params: dict[str, model_schema.TunableParameter],
    loss_params: dict[str, model_schema.TunableParameter],
    train_torch_dataset: datasets.Dataset,
    val_torch_dataset: datasets.Dataset,
    artifact_store: Any,
    max_samples: int = 1000,
    compute_objective_every_n_samples: int = 50,
    target_metric: str = "val_loss",
    device: torch.device | None = None,
):
    """Initialize the Objective class.

    Args:
        model_class: The model class to be tuned.
        network_params: The network parameters to be tuned.
        optimizer_params: The optimizer parameters to be tuned.
        data_params: The data parameters to be tuned.
        loss_params: The loss parameters to be tuned.
        train_torch_dataset: The training dataset.
        val_torch_dataset: The validation dataset.
        artifact_store: The artifact store to save the model and optimizer.
        max_samples: The maximum number of samples to train.
        compute_objective_every_n_samples: The number of samples to compute the objective.
        target_metric: The target metric to optimize.
        device: The device to run the training on.
    """
    self.model_class = model_class
    self.network_params = network_params
    self.optimizer_params = optimizer_params
    self.data_params = data_params
    self.loss_params = loss_params

    # Add sample_id column to datasets for per-sample loss tracking (as integers)
    self.train_torch_dataset = train_torch_dataset.add_column(
        "sample_id",
        list(range(len(train_torch_dataset))),
    )
    self.val_torch_dataset = val_torch_dataset.add_column(
        "sample_id",
        list(range(len(val_torch_dataset))),
    )

    self.artifact_store = artifact_store
    self.target_metric = target_metric
    self.max_samples = max_samples
    self.compute_objective_every_n_samples = compute_objective_every_n_samples
    if device is None:
        self.device = torch.device("cpu")
    else:
        self.device = device

get_metrics

get_metrics(
    model_instance: StimulusModel,
    data_loader: DataLoader,
    loss_dict: dict[str, Module],
    device: device,
) -> dict[str, float]

Compute the objective metric(s) for the tuning process.

Source code in src/stimulus/learner/optuna_tune.py
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
def get_metrics(
    self,
    model_instance: StimulusModel,
    data_loader: torch.utils.data.DataLoader,
    loss_dict: dict[str, torch.nn.Module],
    device: torch.device,
) -> dict[str, float]:
    """Compute the objective metric(s) for the tuning process."""

    def update_metric_dict(
        metric_dict: dict[str, torch.Tensor],
        metrics: dict[str, torch.Tensor],
        loss: torch.Tensor,
    ) -> dict[str, torch.Tensor]:
        """Update the metric dictionary with the new metrics and loss."""
        for key, value in metrics.items():
            if key not in metric_dict:
                if value.ndim == 0:
                    metric_dict[key] = value.unsqueeze(0)
                else:
                    metric_dict[key] = value
            elif value.ndim == 0:
                metric_dict[key] = torch.cat([metric_dict[key], value.unsqueeze(0)], dim=0)
            else:
                metric_dict[key] = torch.cat([metric_dict[key], value], dim=0)
        if "loss" not in metric_dict:
            if loss.ndim == 0:
                metric_dict["loss"] = loss.unsqueeze(0)
            else:
                metric_dict["loss"] = loss
        elif loss.ndim == 0:
            metric_dict["loss"] = torch.cat([metric_dict["loss"], loss.unsqueeze(0)], dim=0)
        else:
            metric_dict["loss"] = torch.cat([metric_dict["loss"], loss], dim=0)
        return metric_dict

    # set model in eval mode
    model_instance.eval()

    metric_dict: dict = {}

    for batch in data_loader:
        try:
            # Move all tensors to device (sample_id is now an integer tensor)
            device_batch = {}
            for key, value in batch.items():
                try:
                    device_batch[key] = value.to(device, non_blocking=True)
                except AttributeError as e:
                    raise AttributeError(
                        f"Error moving '{key}' to device during inference. Expected tensor but got {type(value)}. "
                        f"This usually happens when dataset columns contain non-tensor data. "
                        f"Original error: {e}",
                    ) from e

            # Perform a batch update
            loss, metrics = model_instance.inference(batch=device_batch, **loss_dict)

        except RuntimeError as e:
            if ("CUDA out of memory" in str(e) and self.device.type == "cuda") or (
                "MPS backend out of memory" in str(e) and self.device.type == "mps"
            ):
                logger.warning(f"{self.device.type.upper()} out of memory during training: {e}")
                logger.warning("Falling back to CPU for this trial")
                temp_device = torch.device("cpu")
                model_instance = model_instance.to(temp_device)
                # Consider adjusting batch size or other parameters
                device_batch = {key: value.to(temp_device) for key, value in batch.items()}
                # Retry the batch
                loss, metrics = model_instance.inference(batch=device_batch, **loss_dict)
            else:
                raise

        metric_dict = update_metric_dict(metric_dict, metrics, loss)

    # devide all metrics by number of batches
    for key in metric_dict:
        metric_dict[key] = metric_dict[key].mean()

    # Convert tensors to floats before returning
    return {k: v.item() if isinstance(v, torch.Tensor) else v for k, v in metric_dict.items()}

objective

objective(
    model_instance: StimulusModel,
    train_loader: DataLoader,
    val_loader: DataLoader,
    loss_dict: dict[str, Module],
    device: device,
) -> dict[str, float]

Compute the objective metric(s) for the tuning process.

The objectives are outputed by the model's batch function in the form of loss, metric_dictionary.

Source code in src/stimulus/learner/optuna_tune.py
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
def objective(
    self,
    model_instance: StimulusModel,
    train_loader: torch.utils.data.DataLoader,
    val_loader: torch.utils.data.DataLoader,
    loss_dict: dict[str, torch.nn.Module],
    device: torch.device,
) -> dict[str, float]:
    """Compute the objective metric(s) for the tuning process.

    The objectives are outputed by the model's batch function in the form of loss, metric_dictionary.
    """
    train_metrics = self.get_metrics(model_instance, train_loader, loss_dict, device)
    val_metrics = self.get_metrics(model_instance, val_loader, loss_dict, device)

    # add train_ and val_ prefix to related keys.
    return {
        **{f"train_{k}": v for k, v in train_metrics.items()},
        **{f"val_{k}": v for k, v in val_metrics.items()},
    }

save_checkpoint

save_checkpoint(
    trial: Trial,
    model_instance: StimulusModel,
    optimizer: Optimizer,
    complete_suggestions: dict,
) -> None

Save the model and optimizer to the trial.

Source code in src/stimulus/learner/optuna_tune.py
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
def save_checkpoint(
    self,
    trial: optuna.Trial,
    model_instance: StimulusModel,
    optimizer: torch.optim.Optimizer,
    complete_suggestions: dict,
) -> None:
    """Save the model and optimizer to the trial."""
    # Convert model to CPU before saving to avoid device-specific tensors
    model_instance = model_instance.cpu()
    optimizer_state = optimizer.state_dict()

    # Convert optimizer state to CPU tensors
    for param in optimizer_state["state"].values():
        for k, v in param.items():
            if isinstance(v, torch.Tensor):
                param[k] = v.cpu()
    unique_id = str(uuid.uuid4())[:8]
    model_path = f"{trial.number}_{unique_id}_model.safetensors"
    optimizer_path = f"{trial.number}_{unique_id}_optimizer.pt"
    model_suggestions_path = f"{trial.number}_{unique_id}_model_suggestions.json"
    safe_save_model(model_instance, model_path)
    torch.save(optimizer_state, optimizer_path)
    with open(model_suggestions_path, "w") as f:
        json.dump(complete_suggestions, f)
    artifact_id_model = optuna.artifacts.upload_artifact(
        artifact_store=self.artifact_store,
        file_path=model_path,
        study_or_trial=trial.study,
    )
    artifact_id_optimizer = optuna.artifacts.upload_artifact(
        artifact_store=self.artifact_store,
        file_path=optimizer_path,
        study_or_trial=trial.study,
    )
    artifact_id_model_suggestions = optuna.artifacts.upload_artifact(
        artifact_store=self.artifact_store,
        file_path=model_suggestions_path,
        study_or_trial=trial.study,
    )
    # delete the files from the local filesystem
    try:
        os.remove(model_path)
        os.remove(optimizer_path)
        os.remove(model_suggestions_path)
    except FileNotFoundError:
        logger.info(
            f"File was already deleted: {model_path} or {optimizer_path} or {model_suggestions_path}, most likely due to pruning",
        )
    trial.set_user_attr("model_id", artifact_id_model)
    trial.set_user_attr("model_path", model_path)
    trial.set_user_attr("optimizer_id", artifact_id_optimizer)
    trial.set_user_attr("optimizer_path", optimizer_path)
    trial.set_user_attr("model_suggestions_id", artifact_id_model_suggestions)
    trial.set_user_attr("model_suggestions_path", model_suggestions_path)

tune_loop

tune_loop(
    objective: Objective,
    pruner: BasePruner,
    sampler: BaseSampler,
    n_trials: int,
    direction: str,
    storage: BaseStorage | None = None,
) -> Study

Run the tuning loop.

Parameters:

  • objective (Objective) –

    The objective function to optimize.

  • pruner (BasePruner) –

    The pruner to use.

  • sampler (BaseSampler) –

    The sampler to use.

  • n_trials (int) –

    The number of trials to run.

  • direction (str) –

    The direction to optimize.

  • storage (BaseStorage | None, default: None ) –

    The storage to use.

Returns:

  • Study

    The study object.

Source code in src/stimulus/learner/optuna_tune.py
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
def tune_loop(
    objective: Objective,
    pruner: optuna.pruners.BasePruner,
    sampler: optuna.samplers.BaseSampler,
    n_trials: int,
    direction: str,
    storage: optuna.storages.BaseStorage | None = None,
) -> optuna.Study:
    """Run the tuning loop.

    Args:
        objective: The objective function to optimize.
        pruner: The pruner to use.
        sampler: The sampler to use.
        n_trials: The number of trials to run.
        direction: The direction to optimize.
        storage: The storage to use.

    Returns:
        The study object.
    """
    if storage is None:
        study = optuna.create_study(direction=direction, sampler=sampler, pruner=pruner)
    else:
        study = optuna.create_study(direction=direction, sampler=sampler, pruner=pruner, storage=storage)
    study.optimize(objective, n_trials=n_trials)
    return study