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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
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
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
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
499
500
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
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
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
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
{
 "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": [
    "<!-- hpo-note-cuda -->\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": [
    "<!-- hpo-note-global-config -->\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": [
    "<!-- hpo-note-loaders -->\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": [
    "<!-- hpo-note-search-space -->\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": [
    "<!-- hpo-note-optuna-config -->\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": [
    "<!-- hpo-note-run-study -->\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": [
    "<!-- hpo-note-trials-df -->\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": [
    "<!-- hpo-note-trials-csv -->\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": [
    "<!-- hpo-note-mlflow-ui -->\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": [
    "<!-- hpo-note-mlflow-stop -->\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": [
    "<!-- hpo-note-aug-space -->\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": [
    "<!-- hpo-note-mutator-config -->\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": [
    "<!-- hpo-note-ddp-trials -->\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": [
    "<!-- hpo-note-final-config -->\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": [
    "<!-- hpo-note-final-train -->\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": [
    "<!-- hpo-note-final-yaml -->\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
}