{ "cells": [ { "cell_type": "markdown", "id": "5bd1945a", "metadata": {}, "source": [ "# Deepvisiontools: Hyperparameters optimization (with Optuna)\n", "\n", "**Tutorial time: about 30mn**\n", "\n", "Welcome to deepvisiontools' hyperparameter optimization tutorial.\n", "\n", "The required prior knowledge for this tutorial is basic knowledge about deepvisiontools, average python knowledge while not strictly necessary can be helpful. To get started with deepvisiontools (installation and basic usages) we recommend that you first complete the getting_started tutorial.\n", "\n", "\n", "This tutorial will cover:\n", "- Hyperparameters optimization with basic helpers\n", "- Custom mutators (most flexible design)\n", "- Display optimization search (optuna dashboard etc.)\n", "\n", "**We strongly recommend that you have CUDA available on your machine to train on GPU.**\n", "\n", "To get started, please set up a Python environment (>= 3.10) and install the latest version of deepvisiontools with:\n", "\n", "```bash\n", "pip install deepvisiontools\n", "```\n", "\n", "You can download the demo datasets by running the following command in a shell:\n", "\n", "```bash\n", "deepvisiontools download-demo-datasets\n", "```\n", "\n", "You should obtain 3 datasets located in a `demo_datasets` folder:\n", "- Dice dataset: bounding box detection of dice\n", "- Vegann subset: vegetation vs. background segmentation in an agricultural context\n", "- COCO subset: common-object instance segmentation (1 mask per object present)\n", "\n", "The complete original datasets were found here:\n", "\n", "- The dice dataset was downloaded from Kaggle: https://www.kaggle.com/datasets/nellbyler/d6-dice\n", "- The VegannSubDataset is a small portion from: https://zenodo.org/records/7636408\n", "- The coco_6cls_subset was obtained from: https://universe.roboflow.com/nan-ixwz3/coco-y1tdb\n", "\n", "**Important: To have the same paths as the ones used in the tutorials, we suggest creating a root folder containing 2 folders: `tutos` (for all tutorials) and `demo_datasets` (for all datasets). Otherwise, you will need to change all paths accordingly.**\n", "\n", "### Check that CUDA is available on your machine\n", "\n", "First, check that CUDA is available. If the output of the cell is `True`, then you can continue. Otherwise, we advise you to test deepvisiontools on a machine where CUDA is available (GPU + proper libraries installed)." ] }, { "cell_type": "code", "execution_count": null, "id": "adbaf2ed", "metadata": {}, "outputs": [], "source": [ "import torch\n", "\n", "torch.cuda.is_available()" ] }, { "cell_type": "markdown", "id": "2dd8f430", "metadata": {}, "source": [ "\n", "This is only a hardware check. HPO can run on CPU, but the total time grows quickly because each trial trains a model. For the intended tutorial experience, use CUDA and keep the number of trials small." ] }, { "cell_type": "markdown", "id": "0ae65940", "metadata": {}, "source": [ "## Setup\n", "\n", "We use the Dice dataset because it is a fast one-class detection task. This keeps trial time short enough for a tutorial.\n", "\n", "For YOLO wrappers, we use a simple `x / 255.0` preprocessing function." ] }, { "cell_type": "code", "execution_count": null, "id": "4395e0cc", "metadata": {}, "outputs": [], "source": [ "from copy import deepcopy\n", "\n", "import torch\n", "from torchvision.transforms import v2\n", "\n", "from deepvisiontools import DeepVisionDataset, DeepVisionLoader\n", "from deepvisiontools import current, set_current\n", "from deepvisiontools.train import Trainer, TrainerConfig, launch\n", "from deepvisiontools.train.trainconfig import ModelSpec, WarmupConfig\n", "from deepvisiontools.train.optuna_wrapper import (\n", " AugmentationChoiceSpec,\n", " AugmentationPipelineSpec,\n", " AugmentationTransformSpec,\n", " OptunaConfig,\n", " OptunaPrunerConfig,\n", " OptunaSamplerConfig,\n", " OptunaScoreConfig,\n", " PlateauStopConfig,\n", " SearchSpaceSpec,\n", " run_optuna,\n", ")\n", "\n", "cfg = current()\n", "cfg = cfg.update_device(\"cuda\")\n", "cfg = cfg.update_bbox(num_classes=1)\n", "cfg = cfg.update_amp(True)\n", "set_current(cfg)" ] }, { "cell_type": "markdown", "id": "3a0fa0e3", "metadata": {}, "source": [ "\n", "The global config is set once so every trial starts with the same task assumptions: one detection class, CUDA as the preferred device, and AMP enabled by default." ] }, { "cell_type": "code", "execution_count": null, "id": "52c5b84c", "metadata": {}, "outputs": [], "source": [ "def yolo_preprocessing(x):\n", " return x / 255.0\n", "\n", "base_aug = [\n", " v2.RandomHorizontalFlip(p=0.5),\n", "]\n", "\n", "dice_dataset = DeepVisionDataset(\n", " \"../demo_datasets/DiceDataset\",\n", " reader=\"coco\",\n", " data_type_reader=\"bbox\",\n", " augmentation=base_aug,\n", " preprocessing=yolo_preprocessing,\n", ")\n", "\n", "train_set, valid_set, test_set = dice_dataset.split([0.7, 0.2, 0.1])\n", "\n", "train_loader = DeepVisionLoader(\n", " train_set,\n", " batch_size=8,\n", " shuffle=True,\n", ")\n", "valid_loader = DeepVisionLoader(\n", " valid_set,\n", " batch_size=8,\n", " shuffle=False,\n", ")" ] }, { "cell_type": "markdown", "id": "3a0497df", "metadata": {}, "source": [ "\n", "The hyperparameter optimization runner will clone the training config for every trial, but the dataset and loader will be identical up to the changes in augmentations." ] }, { "cell_type": "markdown", "id": "bd51c431", "metadata": {}, "source": [ "## Base config used by every trial\n", "\n", "A good Optuna setup starts with a normal training config. Optuna will clone this config, apply trial suggestions, run training, and reduce the monitored history into one objective value.\n", "\n", "For HPO, `ModelSpec` is strongly recommended because each trial must be able to rebuild its own model." ] }, { "cell_type": "code", "execution_count": null, "id": "1dbc87ab", "metadata": {}, "outputs": [], "source": [ "def build_base_config():\n", " config = TrainerConfig.build_registered_config(model=\"yolo\", config=\"yolo11n\", train_loader=train_loader, valid_loader=valid_loader)\n", "\n", " config.epochs = 5\n", "\n", " config.checkpoint.monitor = (\"valid/loss\", \"loss\")\n", " config.checkpoint.mode = \"min\"\n", "\n", " config.logging.backends = [\"mlflow\"]\n", " config.logging.mlflow_experiment_name = \"dice_hpo\"\n", " config.logging.mlflow_run_name = \"base\"\n", "\n", " return config\n", "\n", "base_config = build_base_config()\n", "base_config.validate()\n", "print(base_config)" ] }, { "cell_type": "markdown", "id": "43052d54", "metadata": {}, "source": [ "Here we start start from a normal registered `TrainerConfig`." ] }, { "cell_type": "markdown", "id": "e3e7e819", "metadata": {}, "source": [ "## SearchSpaceSpec: write suggestions into config paths\n", "\n", "`SearchSpaceSpec` creates one Optuna suggestion. If `path` is provided, the value is automatically written into the cloned `TrainerConfig`.\n", "\n", "Common useful paths are:\n", "\n", "| What you tune | Path |\n", "|---|---|\n", "| Learning rate | `optim.optim_args.lr` |\n", "| Weight decay | `optim.weight_decay` |\n", "| Accumulation | `precision.accumulate_steps` |\n", "| EMA on/off | `ema.enabled` |\n", "| EMA decay | `ema.decay` |\n", "| Model architecture | `model_spec.kwargs.arch` |\n", "\n", "A good practice when running hyperparameter optimization is too start simple and not too broad at first, before refining. This helps establish a strong baseline while identifying where the main limits lie (over/under fitting etc.)." ] }, { "cell_type": "code", "execution_count": null, "id": "7b32725e", "metadata": {}, "outputs": [], "source": [ "lr_space = SearchSpaceSpec(\n", " name=\"lr\",\n", " kind=\"float\",\n", " path=\"optim.optim_args.lr\",\n", " low=5e-5,\n", " high=8e-4,\n", " log=True,\n", ")\n", "\n", "weight_decay_space = SearchSpaceSpec(\n", " name=\"weight_decay\",\n", " kind=\"float\",\n", " path=\"optim.weight_decay\",\n", " low=1e-6,\n", " high=5e-3,\n", " log=True,\n", ")\n", "\n", "# this one is only important if you want to test optimization for larger effective batchs and only if you're limited by GPU memory. Otherwise just increase batch_size.\n", "accumulate_space = SearchSpaceSpec(\n", " name=\"accumulate_steps\",\n", " kind=\"categorical\",\n", " path=\"precision.accumulate_steps\",\n", " choices=[1, 2],\n", ")\n", "\n", "ema_decay_space = SearchSpaceSpec(\n", " name=\"ema_decay\",\n", " kind=\"float\",\n", " path=\"ema.decay\",\n", " low=0.95,\n", " high=0.999,\n", ")\n", "\n", "search_space = [\n", " lr_space,\n", " weight_decay_space,\n", " accumulate_space,\n", " ema_decay_space,\n", "]" ] }, { "cell_type": "markdown", "id": "e5a46bfc", "metadata": {}, "source": [ "\n", "Each `SearchSpaceSpec` has two roles: it asks Optuna for a value and, when `path` is provided, writes that value into the cloned `TrainerConfig`. The dotted paths are normal config paths such as optimizer kwargs, EMA fields, or precision settings." ] }, { "cell_type": "markdown", "id": "b1077bb5", "metadata": {}, "source": [ "## Objective score\n", "\n", "The Optuna runner monitors the same kind of values as checkpointing and early stopping.\n", "\n", "Here, we minimize validation loss, but you could maximize a specific metric instead:\n", "\n", "```python\n", "monitor=(\"valid/loss\", \"loss\")\n", "mode=\"min\"\n", "```\n", "\n", "The reducer controls how the final trial score is computed from the epoch history:\n", "\n", "- `\"best\"`: use the best epoch. This is the usual choice.\n", "- `\"last\"`: use the final epoch.\n", "- `\"top_k_mean\"`: average the best `top_k` epochs. This is useful when validation is noisy." ] }, { "cell_type": "code", "execution_count": null, "id": "1c83efd5", "metadata": {}, "outputs": [], "source": [ "score_config = OptunaScoreConfig(\n", " monitor=(\"valid/loss\", \"loss\"),\n", " mode=\"min\",\n", " reducer=\"best\",\n", ")\n", "\n", "stable_score_config = OptunaScoreConfig(\n", " monitor=(\"valid/loss\", \"loss\"),\n", " mode=\"min\",\n", " reducer=\"top_k_mean\",\n", " top_k=2,\n", ")" ] }, { "cell_type": "markdown", "id": "8841f8b7", "metadata": {}, "source": [ "The score config tells Optuna which validation value is the objective. Here, lower `valid/loss` is better." ] }, { "cell_type": "markdown", "id": "8f471131", "metadata": {}, "source": [ "## Minimal Optuna run\n", "\n", "We strongly suggest to set `disable_checkpointing=True`. During HPO, you usually want metrics, not hundreds of model files...\n", "\n", "The storage path is a SQLite database. Passing a simple file path such as `\"dice_yolo_hpo.db\"` is enough; deepvisiontools converts it to a SQLite URL." ] }, { "cell_type": "code", "execution_count": null, "id": "36d86eb8", "metadata": {}, "outputs": [], "source": [ "optuna_config = OptunaConfig(\n", " enabled=True,\n", " study_name=\"dice_yolo_hpo\",\n", " storage=\"dice_yolo_hpo.db\",\n", " load_if_exists=True,\n", " n_trials=4,\n", " n_jobs=1,\n", " mlflow_experiment_name=\"dice_hpo\",\n", " mlflow_run_name_template=\"trial_{trial_number:03d}\",\n", " register_study_in_mlflow=True,\n", " disable_checkpointing=True, # Important\n", " sampler=OptunaSamplerConfig(\n", " kind=\"tpe\",\n", " seed=42,\n", " n_startup_trials=2,\n", " ),\n", " pruner=OptunaPrunerConfig( # handles early optimization trial stoping\n", " kind=\"median\",\n", " n_startup_trials=2,\n", " n_warmup_steps=1,\n", " ),\n", " score=score_config,\n", " search_space=search_space,\n", ")\n", "\n", "hpo_config = build_base_config()\n", "hpo_config.optuna = optuna_config\n", "hpo_config.validate()\n", "\n", "print(hpo_config.optuna)" ] }, { "cell_type": "markdown", "id": "394edd52", "metadata": {}, "source": [ "\n", "This cell creates the actual study policy: where the SQLite database is stored, how many trials to run, which sampler/pruner to use, which objective to monitor, and which parameters to suggest. `disable_checkpointing=True` avoids producing heavy artifacts for every trial." ] }, { "cell_type": "code", "execution_count": null, "id": "e4543190", "metadata": {}, "outputs": [], "source": [ "# This cell starts the HPO study.\n", "# On GPU, the Dice demo should stay reasonably short with 4 tiny trials.\n", "\n", "study = run_optuna(hpo_config)\n", "\n", "print(\"Best trial:\", study.best_trial.number)\n", "print(\"Best value:\", study.best_value)\n", "print(\"Best params:\", study.best_params)" ] }, { "cell_type": "markdown", "id": "8f12b415", "metadata": {}, "source": [ "\n", "When this cell is run, deepvisiontools creates one cloned training config per trial, applies the suggested values, trains the model, reports intermediate values for pruning, and finally stores the objective value in the Optuna study." ] }, { "cell_type": "markdown", "id": "14b49847", "metadata": {}, "source": [ "## Inspect the study\n", "\n", "The returned object is a normal Optuna `Study`, so you can use the standard Optuna API." ] }, { "cell_type": "code", "execution_count": null, "id": "4c7a00f9", "metadata": {}, "outputs": [], "source": [ "trials_df = study.trials_dataframe()\n", "trials_df.sort_values(\"value\").head()" ] }, { "cell_type": "markdown", "id": "daaeaf67", "metadata": {}, "source": [ "\n", "The dataframe is the fastest way to inspect what happened. Each row is one trial, `value` is the objective, and the `params_*` columns contain the sampled hyper-parameters." ] }, { "cell_type": "code", "execution_count": null, "id": "6dbfc6dd", "metadata": {}, "outputs": [], "source": [ "trials_df.to_csv(\"dice_yolo_hpo_trials.csv\", index=False)" ] }, { "cell_type": "markdown", "id": "33dca61b", "metadata": {}, "source": [ "\n", "Saving the trial table gives you a lightweight experiment summary that can be compared across runs or archived with your final training config.\n", "\n", "Another way is to use optuna integrated dashboard to read the database created for the study. Note that ide like vscode have an integrated too to read optuna db via the dashboard. Here, we just use the same trick as we did for mlflow to display it in a jupyter notebook" ] }, { "cell_type": "code", "execution_count": null, "id": "f584323b", "metadata": {}, "outputs": [], "source": [ "from pathlib import Path\n", "import shutil\n", "import socket\n", "import subprocess\n", "import time\n", "\n", "from IPython.display import IFrame, display\n", "\n", "\n", "def free_port(start=8080):\n", " port = start\n", " while True:\n", " with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:\n", " is_free = sock.connect_ex((\"127.0.0.1\", port)) != 0\n", " if is_free:\n", " return port\n", " port += 1\n", "\n", "\n", "def as_optuna_storage_url(storage):\n", " storage = str(storage)\n", "\n", " if \"://\" in storage:\n", " return storage\n", "\n", " db_path = Path(storage).expanduser().resolve()\n", " return f\"sqlite:///{db_path.as_posix()}\"\n", "\n", "\n", "dashboard_port = free_port(8080)\n", "dashboard_url = f\"http://127.0.0.1:{dashboard_port}\"\n", "storage_url = as_optuna_storage_url(optuna_config.storage)\n", "\n", "cmd = [\n", " shutil.which(\"optuna-dashboard\") or \"optuna-dashboard\",\n", " storage_url,\n", " \"--host\",\n", " \"127.0.0.1\",\n", " \"--port\",\n", " str(dashboard_port),\n", "]\n", "\n", "optuna_dashboard_proc = subprocess.Popen(cmd)\n", "time.sleep(2)\n", "\n", "display(IFrame(dashboard_url, width=\"100%\", height=700))" ] }, { "cell_type": "markdown", "id": "d15cd3ac", "metadata": {}, "source": [ "## MLflow UI\n", "\n", "Each trial is logged as a distinct MLflow run. The study metadata is also registered in MLflow when `register_study_in_mlflow=True`." ] }, { "cell_type": "code", "execution_count": null, "id": "b55f4bcc", "metadata": {}, "outputs": [], "source": [ "from pathlib import Path\n", "import socket\n", "import subprocess\n", "import sys\n", "import time\n", "\n", "from IPython.display import IFrame, display\n", "\n", "db_path = (Path.cwd() / \"mlruns\" / \"mlflow.db\").resolve()\n", "backend_uri = f\"sqlite:///{db_path.as_posix()}\"\n", "port = 5000\n", "\n", "cmd = [\n", " sys.executable,\n", " \"-m\",\n", " \"mlflow\",\n", " \"server\",\n", " \"--backend-store-uri\",\n", " backend_uri,\n", " \"--host\",\n", " \"127.0.0.1\",\n", " \"--port\",\n", " str(port),\n", " \"--x-frame-options\",\n", " \"NONE\",\n", " \"--cors-allowed-origins\",\n", " \"http://127.0.0.1:8888,http://localhost:8888\",\n", "]\n", "\n", "proc = subprocess.Popen(\n", " cmd,\n", " stdout=subprocess.DEVNULL,\n", " stderr=subprocess.DEVNULL,\n", ")\n", "\n", "for _ in range(50):\n", " with socket.socket() as sock:\n", " if sock.connect_ex((\"127.0.0.1\", port)) == 0:\n", " break\n", " time.sleep(0.2)\n", "\n", "display(IFrame(src=f\"http://127.0.0.1:{port}\", width=\"100%\", height=700))" ] }, { "cell_type": "markdown", "id": "9f7b1a01", "metadata": {}, "source": [ "\n", "This launches a local MLflow server from the notebook and embeds it in an iframe. Use it to compare trial curves, logged parameters, and pruning behavior visually." ] }, { "cell_type": "code", "execution_count": null, "id": "1b9ade7a", "metadata": {}, "outputs": [], "source": [ "proc.terminate()" ] }, { "cell_type": "markdown", "id": "a8203714", "metadata": {}, "source": [ "\n", "This stops the local MLflow process started in the previous cell. It is good notebook hygiene when you are done inspecting the UI." ] }, { "cell_type": "markdown", "id": "8f9d6bf0", "metadata": {}, "source": [ "## Searching augmentation pipelines\n", "\n", "`augmentation_space` is useful when you want to explore trasnformation space.\n", "\n", "There are two helper objects:\n", "\n", "- `AugmentationTransformSpec`: one transform to instantiate.\n", "- `AugmentationChoiceSpec`: choose one transform among multiple options.\n", "\n", "Each transform is importable through a string target such as `\"torchvision.transforms.v2:ColorJitter\"`." ] }, { "cell_type": "code", "execution_count": null, "id": "217e9563", "metadata": {}, "outputs": [], "source": [ "hflip = AugmentationTransformSpec(\n", " target=\"torchvision.transforms.v2:RandomHorizontalFlip\",\n", " kwargs={\n", " \"p\": SearchSpaceSpec(\n", " name=\"hflip_p\",\n", " kind=\"float\",\n", " low=0.0,\n", " high=0.8,\n", " step=0.1,\n", " ),\n", " },\n", " name=\"horizontal_flip\",\n", ")\n", "\n", "color_jitter = AugmentationTransformSpec(\n", " target=\"torchvision.transforms.v2:ColorJitter\",\n", " kwargs={\n", " \"brightness\": 0.15,\n", " \"contrast\": 0.15,\n", " \"saturation\": 0.15,\n", " \"hue\": 0.05,\n", " },\n", " name=\"color_jitter\",\n", ")\n", "\n", "grayscale = AugmentationTransformSpec(\n", " target=\"torchvision.transforms.v2:RandomGrayscale\",\n", " kwargs={\"p\": 0.05},\n", " name=\"grayscale\",\n", ")\n", "\n", "color_choice = AugmentationChoiceSpec(\n", " name=\"color_aug\",\n", " allow_none=True,\n", " choices=[\n", " color_jitter,\n", " grayscale,\n", " ],\n", ")\n", "\n", "augmentation_pipeline = AugmentationPipelineSpec(\n", " target_loaders=(\"train\",),\n", " mode=\"replace\",\n", " items=[\n", " hflip,\n", " color_choice,\n", " ],\n", ")" ] }, { "cell_type": "markdown", "id": "2766368f", "metadata": {}, "source": [ "\n", "This defines an augmentation search space instead of a fixed transform list. Some transform parameters are sampled directly, and `AugmentationChoiceSpec` lets Optuna select between alternative transform families." ] }, { "cell_type": "code", "execution_count": null, "id": "e572827e", "metadata": {}, "outputs": [], "source": [ "aug_hpo_config = build_base_config()\n", "\n", "aug_hpo_config.optuna = OptunaConfig(\n", " enabled=True,\n", " study_name=\"dice_yolo_aug_hpo\",\n", " storage=\"dice_yolo_aug_hpo.db\",\n", " load_if_exists=True,\n", " n_trials=6,\n", " disable_checkpointing=True,\n", " plateau_stop=PlateauStopConfig(\n", " enabled=True,\n", " patience_trials=4,\n", " min_delta=1e-4,\n", " ),\n", " sampler=OptunaSamplerConfig(\n", " kind=\"tpe\",\n", " seed=123,\n", " n_startup_trials=2,\n", " ),\n", " pruner=OptunaPrunerConfig(\n", " kind=\"median\",\n", " n_startup_trials=2,\n", " n_warmup_steps=1,\n", " ),\n", " score=stable_score_config,\n", " search_space=[\n", " lr_space,\n", " weight_decay_space,\n", " ],\n", " augmentation_space=[augmentation_pipeline],\n", ")\n", "\n", "aug_hpo_config.validate()\n", "\n", "aug_study = run_optuna(aug_hpo_config)" ] }, { "cell_type": "markdown", "id": "bdce9dff", "metadata": {}, "source": [ "This is the same setup as before, but now the training loader augmentation pipeline is replaced per trial. The optional plateau stop can end the study early when recent trials stop improving." ] }, { "cell_type": "markdown", "id": "e5b56a12", "metadata": {}, "source": [ "## Custom trial mutator\n", "\n", "A simple `SearchSpaceSpec(path=...)` is enough most of the time but when you need maximal flexibility, use a trial mutator.\n", "\n", "The mutator must be importable from a Python module. In a real project, put it in your package. For this tutorial, we write a tiny `hpo_mutators.py` file next to the notebook." ] }, { "cell_type": "code", "execution_count": null, "id": "3099c7c5", "metadata": {}, "outputs": [], "source": [ "import torch\n", "\n", "from deepvisiontools.train.trainconfig import WarmupConfig\n", "\n", "\n", "def mutate_scheduler(trial, cfg):\n", " scheduler_name = trial.suggest_categorical(\n", " \"scheduler\",\n", " [\"none\", \"cosine_step\"],\n", " )\n", "\n", " if scheduler_name == \"none\":\n", " cfg.sched.scheduler = None\n", " cfg.sched.scheduler_args = {}\n", " cfg.sched.warmup = None\n", " return\n", "\n", " warmup_steps = trial.suggest_categorical(\n", " \"warmup_steps\",\n", " [0, 50, 100],\n", " )\n", "\n", " cfg.sched.scheduler = torch.optim.lr_scheduler.CosineAnnealingLR\n", " cfg.sched.scheduler_args = {\n", " \"T_max\": \"auto\",\n", " \"eta_min\": 1e-6,\n", " }\n", " cfg.sched.step_on = \"step\"\n", "\n", " if warmup_steps > 0:\n", " cfg.sched.warmup = WarmupConfig(\n", " steps=warmup_steps,\n", " steps_unit=\"step\",\n", " ratio=1.0,\n", " start_factor=0.001,\n", " )\n", " else:\n", " cfg.sched.warmup = None" ] }, { "cell_type": "markdown", "id": "8d4f455a", "metadata": {}, "source": [ "As you can see, the mutator pattern is completely free and you can play with both the trial and the TrainerConfig (which contains loaders, models, all training trciks etc.)." ] }, { "cell_type": "code", "execution_count": null, "id": "a8e3da4a", "metadata": {}, "outputs": [], "source": [ "mutator_hpo_config = build_base_config()\n", "\n", "mutator_hpo_config.optuna = OptunaConfig(\n", " enabled=True,\n", " study_name=\"dice_yolo_mutator_hpo\",\n", " storage=\"dice_yolo_mutator_hpo.db\",\n", " n_trials=4,\n", " disable_checkpointing=True,\n", " score=score_config,\n", " search_space=[\n", " lr_space,\n", " weight_decay_space,\n", " ],\n", " trial_mutator_target=mutate_scheduler,\n", ")\n", "\n", "mutator_hpo_config.validate()\n", "print(mutator_hpo_config.optuna.trial_mutator_target)\n", "\n", "mutator_study = run_optuna(mutator_hpo_config)" ] }, { "cell_type": "markdown", "id": "0dd0889c", "metadata": {}, "source": [ "\n", "This config combines normal search-space entries with the custom mutator. Use this pattern when one sampled value changes several config fields at once or when you need specific behaviour." ] }, { "cell_type": "markdown", "id": "6f67080e", "metadata": {}, "source": [ "## Distributed trials\n", "\n", "There are two different parallelism levels:\n", "\n", "1. `n_jobs`: multiple Optuna trials in parallel in the parent process.\n", "2. `distributed_trials=True`: one trial is launched as a DDP child job.\n", "\n", "For GPU training, the safest default is `n_jobs=1`. If you want each trial to use multiple GPUs, use `distributed_trials=True` and specify `trial_devices`.\n", "\n", "The parent process remains the only Optuna controller. Each trial is launched in a child `torch.distributed.run` process." ] }, { "cell_type": "code", "execution_count": null, "id": "828afe25", "metadata": {}, "outputs": [], "source": [ "ddp_trial_config = build_base_config()\n", "\n", "ddp_trial_config.devices.device = \"cuda\"\n", "ddp_trial_config.devices.strategy = \"auto\"\n", "\n", "ddp_trial_config.optuna = OptunaConfig(\n", " enabled=True,\n", " study_name=\"dice_yolo_ddp_trial_hpo\",\n", " storage=\"dice_yolo_ddp_trial_hpo.db\",\n", " n_trials=4,\n", " n_jobs=1,\n", " disable_checkpointing=True,\n", " distributed_trials=True,\n", " trial_devices=[0, 1],\n", " parent_poll_interval_seconds=0.5,\n", " decision_wait_seconds=20.0,\n", " child_exit_grace_seconds=60.0,\n", " keep_trial_workdirs=False,\n", " score=score_config,\n", " search_space=search_space,\n", ")\n", "\n", "ddp_trial_config.validate()\n", "print(ddp_trial_config.optuna)\n", "\n", "# Uncomment on a machine with at least two visible GPUs.\n", "# ddp_study = run_optuna(ddp_trial_config)" ] }, { "cell_type": "markdown", "id": "2fd64085", "metadata": {}, "source": [ "\n", "Distributed trials are useful when a single trial should use multiple GPUs. Keep `n_jobs=1` in that case so one Optuna controller launches one multi-process training trial at a time." ] }, { "cell_type": "markdown", "id": "676fcef8", "metadata": {}, "source": [ "## Final training with the best parameters\n", "\n", "After optimization, do a normal final training with checkpointing enabled and more epochs.\n", "\n", "Here we manually copy the parameters that were searched. This makes the final config explicit and easy to read." ] }, { "cell_type": "code", "execution_count": null, "id": "e1ce186f", "metadata": {}, "outputs": [], "source": [ "final_config = build_base_config()\n", "final_config.epochs = 20\n", "final_config.output_dir = \"dice_final_from_hpo\"\n", "\n", "best_params = study.best_params\n", "\n", "if \"lr\" in best_params:\n", " final_config.optim.optim_args[\"lr\"] = best_params[\"lr\"]\n", "\n", "if \"weight_decay\" in best_params:\n", " final_config.optim.weight_decay = best_params[\"weight_decay\"]\n", "\n", "if \"accumulate_steps\" in best_params:\n", " final_config.precision.accumulate_steps = best_params[\"accumulate_steps\"]\n", "\n", "if \"ema_decay\" in best_params:\n", " final_config.ema.decay = best_params[\"ema_decay\"]\n", "\n", "final_config.checkpoint.enable_checkpointing = True\n", "final_config.checkpoint.save_every_n_epochs = 1\n", "final_config.checkpoint.keep_last_n = 3\n", "final_config.checkpoint.export_model_artifact = True\n", "final_config.checkpoint.export_when = \"best\"\n", "\n", "final_config.logging.mlflow_experiment_name = \"dice_hpo_final\"\n", "final_config.logging.mlflow_run_name = \"best_params_final\"\n", "\n", "final_config.validate()\n", "print(final_config.optim)\n", "print(final_config.ema)" ] }, { "cell_type": "markdown", "id": "9a5c6f55", "metadata": {}, "source": [ "\n", "The final training config is intentionally explicit. Instead of hiding behind the study object, the selected best parameters are copied into a normal `TrainerConfig`, checkpointing is re-enabled, and artifact export is turned back on." ] }, { "cell_type": "code", "execution_count": null, "id": "14868cdf", "metadata": {}, "outputs": [], "source": [ "def main():\n", " Trainer(final_config).fit(resume=None)\n", "\n", "\n", "# Uncomment for the final training run.\n", "# launch(main, devices=\"auto\")" ] }, { "cell_type": "markdown", "id": "90de9384", "metadata": {}, "source": [ "\n", "This is a normal training run, not an Optuna run. It should usually use more epochs than the trials and save the best model artifact for inference/deployment." ] }, { "cell_type": "markdown", "id": "2a43b6eb", "metadata": {}, "source": [ "## Export the final config\n", "\n", "Export the final config after applying the best parameters. This gives you a clean record of what was actually trained." ] }, { "cell_type": "code", "execution_count": null, "id": "864c1098", "metadata": {}, "outputs": [], "source": [ "final_config.export_yaml(\n", " \"dice_final_from_hpo.yaml\",\n", " portable=True,\n", " include_meta=True,\n", ")" ] }, { "cell_type": "markdown", "id": "b2bdfcc1", "metadata": {}, "source": [ "\n", "The final YAML is the clean record of the experiment you actually want to keep: model spec, optimizer, scheduler, precision settings, EMA policy, checkpoint policy, and the best hyper-parameters copied from the study.\n", "Note that best augmentation budget if searched will need to be inserted manually in the dataset before launching the final Train." ] }, { "cell_type": "markdown", "id": "82206028", "metadata": {}, "source": [ "#### This concludes the Optuna tutorial.\n" ] } ], "metadata": { "kernelspec": { "display_name": "dvtv2", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.12.12" } }, "nbformat": 4, "nbformat_minor": 5 }