File size: 76,302 Bytes
6bd1f02
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "277e99cb",
   "metadata": {},
   "source": [
    "# Deepvisiontools: Advanced usages\n",
    "\n",
    "**Tutorial time: about 1h30**\n",
    "\n",
    "Welcome to deepvisiontools' advanced usages tutorials.\n",
    "\n",
    "The required prior knowledge for this tutorial is basic knowledge about deepvisiontools. Average knowledge about python, while not required, might be helpful as well. To get started with deepvisiontools (installation and basic usages) we recommend that you first complete the getting_started tutorial.\n",
    "\n",
    "The difficulty of this tutorial is crescent, the easiest parts are covered first\n",
    "\n",
    "This tutorial will cover:\n",
    "1. Exhaustive global configuration capacities\n",
    "2. Exhaustive training configuration overview\n",
    "3. Inference customizable parameters\n",
    "4. Custom Reader/writers for DeepVisionDataset\n",
    "5. Custom Model implementation using DeepVisionModel\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",
    "For time considerations, this tutorial uses the Dice detection dataset.\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": "2ff02b20",
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch\n",
    "\n",
    "torch.cuda.is_available()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "54ce8463",
   "metadata": {},
   "source": [
    "<!-- adv-note-cuda -->\n",
    "The output is a quick environment check. If it prints `True`, the notebook can use `device=\"cuda\"`. If it prints `False`, the configuration cells still work, but training should either be skipped or switched to `\"cpu\"`.\n",
    "\n",
    "## Global configuration\n",
    "\n",
    "Let's start by having a deeper look at the global configuration in deepvisiontools. The global configuration must be considered as a generic fallback and most of the important elements can be directly controlled in the various part of the library. For example, you can default the device to \"cuda\" in the config, but when using `launch` to actually start training, you can pass \"cpu\" as argument and the whole training will occur in cpu. The behaviour is similar for amp (automatic mixed precision). If use_amp is enabled at the model or training level, no matter what the global configuration says, amp will be enabled.\n",
    "\n",
    "The global configuration remains important, and we strongly suggest that you parametrize it as close as you can from the actual expected behaviour as it will provides an additional safety in case you forget to explicitly state it somewhere in your scripts ...\n",
    "\n",
    "Let's have a look at what is currently available in the global config by creating one from scratch. Note that in most cases, you only need to use the default one and changes what you want to change by using the helpers. But it's worth having a deep look to exhibit all possible configuration options.\n",
    "\n",
    "The global config is handled by a specific object, `DVConfig` composed of multiple sub config dedicated to specific part of the library. Note that the classes are non mutable, to preserve stability when having distributed computation, therefore the easiest way of modifying it is by using the various helpers showed in the getting started tutorial.\n",
    "\n",
    "Here we display everything that is set by default in deepvisiontools, so you can understand on what you can play."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b91b22ab",
   "metadata": {},
   "outputs": [],
   "source": [
    "from deepvisiontools import current, set_current\n",
    "from deepvisiontools.config import VizCfg, LogCfg, DVConfig, BboxCfg, InstanceMaskCfg, SemanticMaskCfg\n",
    "import logging\n",
    "\n",
    "# The logging config allows to control the warning level.\n",
    "# To be fair, this is not fully exploited yet in deepvisiontools but might become in future releases\n",
    "\n",
    "log_config = LogCfg(\n",
    "    level=logging.WARNING,\n",
    "    enabled=True,\n",
    "    duplicate_filter=True\n",
    ")\n",
    "\n",
    "# This part controls the visualizations (from datasets / predictor / evaluator) created in deepvisiontools\n",
    "\n",
    "viz_config = VizCfg(\n",
    "    window_mode=\"dual\", # single or dual -> either produce a single window with only the visualization or concat with original image\n",
    "    desired_min_size=1200,  # deepvisiontools resize the visualizations produced. This is the resulting size of the smallest side of the image after resizing \n",
    "    mask_alpha=0.6, # transparency of the masks\n",
    "    box_line_width=3,\n",
    "    outline_width=2,\n",
    "    class_colors=None,  # you can pass custom colors\n",
    "    instance_colors=None,   # idem\n",
    "    show_scores=True,   \n",
    "    categories=None # you can name the categories you are considering to display them instead of numbers in visualizations. It must be a dict associating a label with the category name\n",
    ")\n",
    "\n",
    "# The following handles the BboxData behaviour + detection model post process\n",
    "# Note that the best way to handle postprocess is via the PredParams option directly in the model as we will see later, but this is a safety fallback\n",
    "\n",
    "box_config = BboxCfg(\n",
    "    type = \"bbox\",  # the name : don't touch it\n",
    "    num_classes=1,\n",
    "    min_size=5, # the minimal side of a box: if a box has shorted side, it will be removed by sanitize. This is particularly helpful when using augmentations / crops that can cut most of the object but leaves some tiny portion alive.\n",
    "    conf_threshold=0.5, # confidence threshold in inference\n",
    "    nms_threshold=0.5,  # nms threshold in inference\n",
    "    max_det=500 # maximum number of object per image in inference\n",
    ")\n",
    "\n",
    "# similar but for InstanceMaskData\n",
    "\n",
    "instance_config = InstanceMaskCfg(\n",
    "    type=\"instance_mask\",\n",
    "    num_classes=1,\n",
    "    min_size=5, # same as for bouding box but this is actually the number of pixel present in the mask.\n",
    "    conf_threshold=0.5,\n",
    "    nms_threshold=0.5,\n",
    "    mask_logits_threshold=0.5,  # instance segmentation produce also logits for the masks, you can decide at which threshold they should be kept or not\n",
    "    max_det=0.5\n",
    ")\n",
    "\n",
    "# similar but for SemanticMaskData\n",
    "\n",
    "semantic_config = SemanticMaskCfg(\n",
    "    type=\"semantic_mask\",\n",
    "    num_classes=1,  # remember that in binary task it must be set to 1, and in 2 or more target classes you must also add the background! (so num_classes=2 never exist)\n",
    "    min_size=0,\n",
    "    binary_logits_threshold=0.5,\n",
    "    logits_combine=\"avg\"    # This is the way we are merging multiple semantic masks when running sliding window inference. You can use max or min as well.\n",
    ")\n",
    "\n",
    "# The overall config \n",
    "\n",
    "config = DVConfig(\n",
    "    device=\"cpu\",\n",
    "    log=log_config,\n",
    "    viz=viz_config,\n",
    "    data_box=box_config,\n",
    "    data_instance_mask=instance_config,\n",
    "    data_semantic_mask=semantic_config,\n",
    "    amp=True    # torch automatic precision default setup. Can be overriden later in TrainerConfig\n",
    ")\n",
    "\n",
    "# set the config to current global config\n",
    "\n",
    "set_current(config)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "29312bae",
   "metadata": {},
   "source": [
    "As you can see, there is already a lot you can customize. The most important are of course the device and the data."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "62e56ee4",
   "metadata": {},
   "source": [
    "## Exhaustive Training configuration\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c4b03869",
   "metadata": {},
   "source": [
    "We are going to all training configuration capacities, built from scratch, to exhibit the whole set of parameters you can customize. In the various subsections we will cover in more detail each part so you can a complete overview on the advanced training tricks that are parametrizable in deepvisiontools.\n",
    "\n",
    "Let's start by defining the dataloaders, which are mandatory parts of the `TrainerConfig` (we will use the dice dataset as an example, cf. demo-datasets you used in getting_started tutorial)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e45bd59c",
   "metadata": {},
   "outputs": [],
   "source": [
    "from deepvisiontools import DeepVisionDataset, DeepVisionLoader\n",
    "import torchvision.transforms.v2 as v2\n",
    "\n",
    "def yolo_preprocessing(x):\n",
    "    return x / 255.0\n",
    "\n",
    "train_aug = [\n",
    "    v2.RandomHorizontalFlip(p=0.5),\n",
    "    v2.ColorJitter(\n",
    "        brightness=0.15,\n",
    "        contrast=0.15,\n",
    "        saturation=0.15,\n",
    "        hue=0.05,\n",
    "    ),\n",
    "]\n",
    "\n",
    "dice_dataset = DeepVisionDataset(\n",
    "    \"../demo_datasets/DiceDataset\",\n",
    "    reader=\"coco\",\n",
    "    data_type_reader=\"bbox\",\n",
    "    augmentation=train_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": "62b1b129",
   "metadata": {},
   "source": [
    "Let's build from scratch a first base TrainerConfig example"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "66f26ed7",
   "metadata": {},
   "outputs": [],
   "source": [
    "from deepvisiontools.train import TrainerConfig, ModelSpec\n",
    "\n",
    "def build_base_dice_config():\n",
    "    model_kwargs = {\n",
    "        \"arch\": \"yolo11n\",\n",
    "        \"pretrained\": True,\n",
    "        \"num_classes\": 1,\n",
    "        \"device\": None,\n",
    "        \"use_amp\": None,\n",
    "    }\n",
    "\n",
    "    # The minimum set for TrainerConfig is a) model b) train and valid dataloader\n",
    "\n",
    "    config = TrainerConfig(\n",
    "        model_spec=ModelSpec(\n",
    "            builder=\"yolo\",\n",
    "            kwargs=model_kwargs,\n",
    "        ),\n",
    "        train_loader=train_loader,\n",
    "        valid_loader=valid_loader,\n",
    "        epochs=3,\n",
    "        output_dir=\"advanced_dice_runs\",\n",
    "    )\n",
    "\n",
    "    # configuration of the device part\n",
    "\n",
    "    config.devices.device = \"cuda\"\n",
    "    config.devices.strategy = \"auto\"\n",
    "    config.devices.num_workers = 0\n",
    "    config.devices.pin_memory = True\n",
    "\n",
    "    # Optimization part\n",
    "\n",
    "    config.optim.optimizer = torch.optim.AdamW\n",
    "    config.optim.optim_args = {\n",
    "        \"lr\": 2e-4,\n",
    "        \"betas\": (0.9, 0.999),\n",
    "    }\n",
    "    config.optim.weight_decay = 1e-4\n",
    "\n",
    "    # scheduler\n",
    "\n",
    "    config.sched.scheduler = torch.optim.lr_scheduler.CosineAnnealingLR\n",
    "    config.sched.scheduler_args = {\n",
    "        \"T_max\": \"auto\",\n",
    "        \"eta_min\": 1e-6,\n",
    "    }\n",
    "    config.sched.step_on = \"epoch\"\n",
    "\n",
    "    # monitoring\n",
    "\n",
    "    config.logging.backends = [\"mlflow\"]\n",
    "    config.logging.mlflow_experiment_name = \"advanced_dice\"\n",
    "    config.logging.mlflow_run_name = \"baseline\"\n",
    "\n",
    "    # checkpoint\n",
    "\n",
    "    config.checkpoint.monitor = (\"valid/loss\", \"loss\")  # this part is important : it defines how deepvisiontools selects best models. Note that you should privilege metrics such as mAP, IoU etc. with the \"max\" argument\n",
    "    config.checkpoint.mode = \"min\"\n",
    "    config.checkpoint.save_every_n_epochs = 1\n",
    "    config.checkpoint.keep_last_n = 2\n",
    "    config.checkpoint.export_model_artifact = True\n",
    "    config.checkpoint.export_when = \"best\"\n",
    "\n",
    "    return config\n",
    "\n",
    "base_config = build_base_dice_config()\n",
    "base_config.validate()\n",
    "\n",
    "print(base_config)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "46edcb9b",
   "metadata": {},
   "source": [
    "<!-- adv-note-base-config -->\n",
    "This baseline config is the reference object for the rest of the tutorial. `ModelSpec` stores how to rebuild the model, `optim` and `sched` define optimization, `logging` defines the experiment metadata, and `checkpoint` decides what is saved."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "897503f8",
   "metadata": {},
   "source": [
    "### EMA: smoother weights for validation and export\n",
    "\n",
    "EMA means **Exponential Moving Average**. During training, deepvisiontools keeps a second copy of the model weights. After each optimizer step, the EMA copy is updated as:\n",
    "\n",
    "```text\n",
    "ema_weight = decay * ema_weight + (1 - decay) * current_weight\n",
    "```\n",
    "\n",
    "The idea is simple: the normal model weights can move a lot from one step to the next, while the EMA weights are smoother.\n",
    "\n",
    "```text\n",
    "optimizer step ──> model weights ──> next step\n",
    "                       │\n",
    "                       └──> EMA shadow weights ──> validation / best *_ema artifact\n",
    "```\n",
    "\n",
    "The main parameters are:\n",
    "\n",
    "- `enabled`: turn EMA on or off.\n",
    "- `decay`: smoothing strength. Higher values make EMA slower but smoother.\n",
    "- `update_every`: update EMA every N optimizer steps.\n",
    "- `warmup_steps`: ramp the effective decay at the beginning of training.\n",
    "- `eval_with_ema`: use EMA weights during validation."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8d25ba3a",
   "metadata": {},
   "outputs": [],
   "source": [
    "from copy import deepcopy\n",
    "\n",
    "ema_config = deepcopy(base_config)\n",
    "\n",
    "ema_config.ema.enabled = True\n",
    "ema_config.ema.decay = 0.995\n",
    "ema_config.ema.update_every = 1\n",
    "ema_config.ema.warmup_steps = 100\n",
    "ema_config.ema.eval_with_ema = True\n",
    "\n",
    "print(ema_config.ema)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e462dc0c",
   "metadata": {},
   "source": [
    "<!-- adv-note-ema -->\n",
    "You just enabled EMA and selected how the shadow weights are updated. `update_every=1` updates EMA after each optimizer step, while `eval_with_ema=True` means validation evaluates metrics with the smoother EMA weights."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "eb202cc5",
   "metadata": {},
   "source": [
    "A few practical rules:\n",
    "\n",
    "- For short demo trainings, `decay=0.95` or `0.99` reacts faster.\n",
    "- For longer trainings, `0.995` to `0.9998` is usually more stable.\n",
    "- If you validate with EMA, use the exported EMA model for inference too.\n",
    "\n",
    "You can of course disable EMA"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "adc89b5d",
   "metadata": {},
   "outputs": [],
   "source": [
    "no_ema_config = deepcopy(base_config)\n",
    "\n",
    "no_ema_config.ema.enabled = False\n",
    "no_ema_config.ema.eval_with_ema = False\n",
    "\n",
    "print(no_ema_config.ema)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5f19b5fd",
   "metadata": {},
   "source": [
    "Note that EMA is known to increase generalization capability and increasing performances. However, it often required a couple more epochs to actually see the model improving during training, which depend of course on the decay parameter."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4fc2842b",
   "metadata": {},
   "source": [
    "### LLRD: smaller learning rates in early layers\n",
    "\n",
    "LLRD means **Layer-wise Learning Rate Decay**. The key idea is to preserve earlier layer from loosing the often massive pretrained advantage while still fine-tuning the model.\n",
    "\n",
    "The intuition is:\n",
    "\n",
    "```text\n",
    "early backbone ──> middle backbone ──> late backbone ──> neck/head\n",
    " very small LR        small LR            medium LR        base LR\n",
    "```\n",
    "\n",
    "If `base_lr = 1e-4` and `layer_decay = 0.85`, deepvisiontools assigns lower learning rates to earlier units:\n",
    "\n",
    "```text\n",
    "head_lr      = base_lr\n",
    "previous_lr  = base_lr * 0.85\n",
    "older_lr     = base_lr * 0.85 ** 2\n",
    "...\n",
    "```\n",
    "\n",
    "The important parameters are:\n",
    "\n",
    "- `optim.param_groups=\"flat\"`: one parameter group, same LR everywhere.\n",
    "- `optim.param_groups=\"llrd\"`: generic LLRD grouping.\n",
    "- `optim.param_groups=\"layer_aware_llrd\"`: LLRD using semantic groups such as backbone, neck, head, encoder, decoder, etc.\n",
    "- `optim.layer_decay`: multiplier applied when moving from later layers to earlier layers.\n",
    "\n",
    "LLRD is especially useful for large backbones that were already pretrained. It is less important for very small YOLO demo runs, but the configuration is the same."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "eb3eef57",
   "metadata": {},
   "outputs": [],
   "source": [
    "llrd_config = deepcopy(base_config)\n",
    "\n",
    "llrd_config.optim.param_groups = \"layer_aware_llrd\"\n",
    "llrd_config.optim.layer_decay = 0.85\n",
    "llrd_config.optim.optim_args = {\n",
    "    \"lr\": 2e-4,\n",
    "    \"betas\": (0.9, 0.999),\n",
    "}\n",
    "llrd_config.optim.weight_decay = 0.05\n",
    "\n",
    "print(llrd_config.optim)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e21490c8",
   "metadata": {},
   "source": [
    "<!-- adv-note-llrd -->\n",
    "This asks the trainer to create several optimizer parameter groups instead of a single flat group. The head keeps the base learning rate and earlier backbone blocks receive smaller learning rates controlled by `layer_decay`."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "894ef75a",
   "metadata": {},
   "source": [
    "You can inspect the actual optimizer groups before running a full training. This is often useful to verify that the groups have names such as `backbone_*`, `neck_*`, or `head_*`.\n",
    "\n",
    "For big models, this print can be long. Here we only display a compact summary."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5d734f39",
   "metadata": {},
   "outputs": [],
   "source": [
    "from deepvisiontools.train.trainer import build_param_groups\n",
    "\n",
    "model_for_inspection = llrd_config.build_model()\n",
    "param_groups = build_param_groups(model_for_inspection, llrd_config)\n",
    "\n",
    "for group in param_groups[:8]:\n",
    "    name = group.get(\"name\", \"unnamed\")\n",
    "    lr = group.get(\"lr\", llrd_config.optim.optim_args[\"lr\"])\n",
    "    wd = group.get(\"weight_decay\", llrd_config.optim.weight_decay)\n",
    "    n_params = len(group[\"params\"])\n",
    "    print(f\"{name:35s} lr={lr:.3e} wd={wd} n={n_params}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c531fcd0",
   "metadata": {},
   "source": [
    "<!-- adv-note-param-groups -->\n",
    "The printed list is a preview of the optimizer groups that will be passed to `AdamW`. Seeing several different learning rates confirms that LLRD was actually applied to the model structure."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d586b670",
   "metadata": {},
   "source": [
    "### Backbone and BatchNorm freezing\n",
    "\n",
    "Freezing is useful when the dataset is small or when the first epochs are unstable. BatchNorm freezing is often quite important if you are training on multiple GPU while having a small micro-batch. Indeed, BatchNorm can become instable in case the number of samples per batch is not large enough.\n",
    "\n",
    "There are two different ideas:\n",
    "\n",
    "1. **Backbone freezing**: temporarily freeze backbone parameter groups at the beginning of training.\n",
    "2. **BatchNorm freezing**: keep BatchNorm statistics fixed, which is often safer with tiny batch sizes.\n",
    "\n",
    "For backbone freezing, deepvisiontools looks for optimizer parameter groups whose name is `backbone` or starts with `backbone_`. This means it works best together with LLRD / layer-aware LLRD groups.\n",
    "\n",
    "The parameters are:\n",
    "\n",
    "- `freezing.freeze_epochs`: number of first epochs during which backbone groups are frozen.\n",
    "- `freezing.backbone_group_name`: group-name prefix to freeze. Default is `\"backbone\"`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d0689383",
   "metadata": {},
   "outputs": [],
   "source": [
    "freeze_config = deepcopy(llrd_config)\n",
    "\n",
    "freeze_config.freezing.freeze_epochs = 2\n",
    "freeze_config.freezing.backbone_group_name = \"backbone\"\n",
    "\n",
    "print(freeze_config.freezing)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "99ab354d",
   "metadata": {},
   "source": [
    "<!-- adv-note-freezing -->\n",
    "Here, the backbone is frozen only during the first two epochs. The detection head adapts first, then the backbone is unfrozen for normal fine-tuning. This often stabilizes small-dataset training."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7c21a1e1",
   "metadata": {},
   "source": [
    "BatchNorm freezing is controlled by `normalization.policy`.\n",
    "\n",
    "The available policies are:\n",
    "\n",
    "- `\"auto\"`: freeze BatchNorm when the local micro-batch size is too small.\n",
    "- `\"none\"`: do not touch normalization layers.\n",
    "- `\"freeze_bn\"`: freeze BatchNorm / SyncBatchNorm layers.\n",
    "- `\"sync_bn\"`: convert BatchNorm to SyncBatchNorm under DDP + CUDA.\n",
    "- `\"sync_or_freeze_bn\"`: use SyncBatchNorm under DDP + CUDA, otherwise freeze BatchNorm.\n",
    "\n",
    "The two additional flags control what is frozen:\n",
    "\n",
    "- `freeze_affine=True`: freeze BatchNorm learnable `weight` and `bias`.\n",
    "- `freeze_running_stats=True`: keep running mean / variance fixed."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5cb83c91",
   "metadata": {},
   "outputs": [],
   "source": [
    "freeze_config.normalization.policy = \"sync_or_freeze_bn\"\n",
    "freeze_config.normalization.freeze_affine = True\n",
    "freeze_config.normalization.freeze_running_stats = True\n",
    "freeze_config.normalization.verbose = True\n",
    "\n",
    "print(freeze_config.normalization)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f8f0a737",
   "metadata": {},
   "source": [
    "### Precision, accumulation, gradient clipping, and warmup\n",
    "\n",
    "The `precision` block controls mixed precision and gradient handling.\n",
    "\n",
    "- `precision.amp=None`: fallback to `current().amp`.\n",
    "- `precision.amp=True`: request AMP explicitly.\n",
    "- `precision.amp=False`: force full precision.\n",
    "- `precision.amp_dtype`: `\"bf16\"`, `\"fp16\"`, or `\"fp32\"`.\n",
    "- `precision.accumulate_steps`: perform one optimizer step every N batches.\n",
    "- `precision.grad_clip`: clip gradients before the optimizer step.\n",
    "\n",
    "You can see the fallback logic of amp here: if precision.amp is set to None, it uses the one defined in global config. However, the TrainerConfig wins in case a clear information is passed. grad clipping impose a hard limit on the gradient norm. This can help in case of unstable training by limiting the impact of specific batchs that could make the optimization diverge if the gradient is too large. Typical values are within the 1 - 10 range.\n",
    "\n",
    "accumulate step is a nice simple trick, that allow to mimic larger batch on smaller GPU: if you're limited by GPU memory, you can optimize once for every n batch. So the effective batch size (in terms of gradient stability) is simply batch size x accumulate steps."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "28dae182",
   "metadata": {},
   "outputs": [],
   "source": [
    "from deepvisiontools.train import WarmupConfig\n",
    "\n",
    "precision_config = deepcopy(base_config)\n",
    "\n",
    "precision_config.precision.amp = True\n",
    "precision_config.precision.amp_dtype = \"bf16\"\n",
    "precision_config.precision.accumulate_steps = 2\n",
    "precision_config.precision.grad_clip = 5.0\n",
    "\n",
    "precision_config.sched.step_on = \"step\"\n",
    "precision_config.sched.warmup = WarmupConfig(\n",
    "    steps=100,\n",
    "    steps_unit=\"step\",\n",
    "    ratio=1.0,\n",
    "    start_factor=0.001,\n",
    ")\n",
    "\n",
    "precision_config.validate()\n",
    "print(precision_config.precision)\n",
    "print(precision_config.sched.warmup)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8d302770",
   "metadata": {},
   "source": [
    "\n",
    "Warmup lives in the scheduler config. If warmup is expressed in optimizer steps, the scheduler must follows. Warmup is progressively increasing the learning rate, starting really low, during the first steps/epochs of a training (typically 500 ish steps). This is particularly useful when you use optimizers that rely on momentum accumulation like Adam or AdamW."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6c01d751",
   "metadata": {},
   "source": [
    "<!-- adv-note-precision -->\n",
    "This configuration combines AMP, gradient accumulation, gradient clipping, and scheduler warmup. Because warmup is expressed in optimizer steps, the scheduler is also set to step mode so both mechanisms use the same unit."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ea5eaaa9",
   "metadata": {},
   "source": [
    "### Checkpoints and model artifacts\n",
    "\n",
    "Checkpointing has two different roles:\n",
    "\n",
    "1. Restartable training checkpoints: optimizer, scheduler, scaler, EMA state, etc.\n",
    "2. Portable model artifacts: model builder + kwargs + weights for inference.\n",
    "\n",
    "The master switch is `checkpoint.enable_checkpointing`. For normal training, keep it enabled. For large Optuna runs (hyperparameters optimization), disabling it avoids writing many heavy artifacts."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c1a15327",
   "metadata": {},
   "outputs": [],
   "source": [
    "checkpoint_config = deepcopy(base_config)\n",
    "\n",
    "checkpoint_config.checkpoint.enable_checkpointing = True\n",
    "checkpoint_config.checkpoint.monitor = (\"valid/loss\", \"loss\")\n",
    "checkpoint_config.checkpoint.mode = \"min\"\n",
    "checkpoint_config.checkpoint.filename = \"checkpoint\"\n",
    "checkpoint_config.checkpoint.save_every_n_epochs = 1\n",
    "checkpoint_config.checkpoint.keep_last_n = 2\n",
    "checkpoint_config.checkpoint.export_model_artifact = True\n",
    "checkpoint_config.checkpoint.export_when = \"best\"\n",
    "\n",
    "print(checkpoint_config.checkpoint)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9677de14",
   "metadata": {},
   "source": [
    "<!-- adv-note-checkpoint-on -->\n",
    "This is the normal experiment setup: restart checkpoints are written periodically, old checkpoints are pruned, and the best portable model artifact is exported according to the monitored validation loss."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c124567b",
   "metadata": {},
   "outputs": [],
   "source": [
    "no_checkpoint_config = deepcopy(base_config)\n",
    "\n",
    "no_checkpoint_config.checkpoint.enable_checkpointing = False\n",
    "no_checkpoint_config.checkpoint.save_every_n_epochs = 0\n",
    "no_checkpoint_config.checkpoint.export_model_artifact = False\n",
    "\n",
    "print(no_checkpoint_config.checkpoint)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4301a6a3",
   "metadata": {},
   "source": [
    "<!-- adv-note-checkpoint-off -->\n",
    "This disables artifact/checkpoint writing while keeping training, validation, and logging active. It is especially useful for quick experiments and large Optuna studies where hundreds of checkpoints would be wasteful."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "65c5ce7f",
   "metadata": {},
   "source": [
    "### Metrics configuration\n",
    "\n",
    "Loss is always monitored during validation. If you also want task metrics, provide a `MetricsSpec`.\n",
    "\n",
    "For this Dice example, the task is bounding box detection, so we use `kind=\"bbox\"` and `num_classes=1`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ad396c13",
   "metadata": {},
   "outputs": [],
   "source": [
    "from deepvisiontools.train import EvalConfig, MetricsSpec\n",
    "\n",
    "metrics_config = deepcopy(base_config)\n",
    "\n",
    "metrics_config.eval = EvalConfig(\n",
    "    eval_every_n_steps=0,\n",
    "    eval_on=\"valid\",\n",
    "    metrics=MetricsSpec(\n",
    "        kind=\"bbox\",\n",
    "        num_classes=1,\n",
    "    ),\n",
    ")\n",
    "\n",
    "metrics_config.validate()   # useful to check that the whole config is interpretable by deepvisiontools\n",
    "\n",
    "print(metrics_config.eval)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "10b4643f",
   "metadata": {},
   "source": [
    "<!-- adv-note-metrics -->\n",
    "The validation loop will now compute detection metrics in addition to loss. We still monitor `valid/loss` here, but the same monitor fields could point to a metric if that is the quantity you want to optimize.\n",
    "\n",
    "**If you use a registered TrainerConfig, metric will always be adapted to the model you've selected**"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1794f953",
   "metadata": {},
   "source": [
    "### Device and DDP strategy\n",
    "\n",
    "The most common setting is:\n",
    "\n",
    "```python\n",
    "config.devices.device = \"cuda\"\n",
    "config.devices.strategy = \"auto\"\n",
    "```\n",
    "\n",
    "With `strategy=\"auto\"`, deepvisiontools stays in a normal single process unless the training is launched through `launch(...)` / `torchrun` with more than one process.\n",
    "\n",
    "Use `launch(main, devices=\"auto\")` to let deepvisiontools use all visible GPUs, or pass a specific subset such as `[0, 1]`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "66ff2591",
   "metadata": {},
   "outputs": [],
   "source": [
    "ddp_config = deepcopy(base_config)\n",
    "\n",
    "ddp_config.devices.device = \"cuda\"\n",
    "ddp_config.devices.strategy = \"auto\"\n",
    "ddp_config.find_unused_parameters = False\n",
    "\n",
    "print(ddp_config.devices)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7c15e36e",
   "metadata": {},
   "source": [
    "<!-- adv-note-ddp-config -->\n",
    "The config is DDP-ready, but it does not force DDP by itself. The actual process layout is decided by `launch(...)`, so the same script can run on one GPU or several GPUs."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "acbcddd6",
   "metadata": {},
   "source": [
    "A minimal DDP-compatible training entry point looks like this:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "93089c16",
   "metadata": {},
   "outputs": [],
   "source": [
    "from deepvisiontools import Trainer, launch\n",
    "\n",
    "ddp_config.epochs = 1\n",
    "\n",
    "def main():\n",
    "    trainer = Trainer(ddp_config)\n",
    "    trainer.fit(resume=None)\n",
    "\n",
    "# Single GPU / CPU fallback, or one process per visible GPU depending on your hardware configuration.\n",
    "launch(main, devices=\"auto\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f8f60a0c",
   "metadata": {},
   "source": [
    "<!-- adv-note-ddp-main -->\n",
    "The important pattern is to create the `Trainer` inside `main()`. When `launch(...)` starts multiple processes, every process runs this function and the trainer binds itself to the correct rank/device."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2828bbce",
   "metadata": {},
   "source": [
    "### Portable YAML export and reload\n",
    "\n",
    "Deepvisiontools propose some possibilities to export/load your Config using yaml files. This guarantee maximal reproducibility of your setup. However this comes at at a minor price in terms of ergonomy: TrainerConfig parameters must be exportable to yaml (str, int etc.). For some specific parts deepvisiontools does the conversion itself.\n",
    "\n",
    "A portable YAML config needs importable objects. For optimizers and schedulers, deepvisiontools converts classes such as `torch.optim.AdamW` to import specs. For models, use `ModelSpec`. This is why in the base configuration we used ModelSpec and optimizer was defined by separating the class and the kwargs.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ff51da94",
   "metadata": {},
   "outputs": [],
   "source": [
    "yaml_config = deepcopy(base_config)\n",
    "\n",
    "yaml_config.export_yaml(\n",
    "    \"advanced_dice_config.yaml\",\n",
    "    portable=True,\n",
    "    include_meta=True,\n",
    ")\n",
    "\n",
    "reloaded_config = TrainerConfig.from_yaml(\n",
    "    \"advanced_dice_config.yaml\",\n",
    "    train_loader=train_loader,\n",
    "    valid_loader=valid_loader,\n",
    ")\n",
    "\n",
    "print(reloaded_config.model_spec)\n",
    "print(reloaded_config.optim.optimizer)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1cde4737",
   "metadata": {},
   "source": [
    "<!-- adv-note-yaml -->\n",
    "The YAML file contains portable import specs for the optimizer/scheduler and a portable `ModelSpec` for the model. The dataloaders are passed again at reload time because they are runtime objects, not YAML content."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "96313153",
   "metadata": {},
   "source": [
    "## 3. Direct model building and prediction parameters\n",
    "\n",
    "You can build a model directly with `ModelFactory`. This is useful for quick experiments or for inference scripts.\n",
    "\n",
    "Most detection / instance segmentation wrappers expose prediction parameters such as confidence threshold, NMS IoU, and maximum detections. These parameters are stored on the model and are used by `predict`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "57fc4cd9",
   "metadata": {},
   "outputs": [],
   "source": [
    "from deepvisiontools.models import ModelFactory\n",
    "\n",
    "model = ModelFactory(\n",
    "    \"yolo\",\n",
    "    arch=\"yolo11n\",\n",
    "    pretrained=True,\n",
    "    num_classes=1,\n",
    "    device=\"cuda\",\n",
    ")\n",
    "\n",
    "model.set_pred_params(\n",
    "    conf_threshold=0.30,\n",
    "    nms_iou=0.50,\n",
    "    max_det=100,\n",
    ")\n",
    "\n",
    "print(model.pred_params)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "86b7b553",
   "metadata": {},
   "source": [
    "<!-- adv-note-pred-params -->\n",
    "`set_pred_params` changes only inference decoding. The model weights are unchanged; predictions are simply filtered with the new confidence threshold, NMS IoU threshold, and maximum detection count.\n",
    "\n",
    "Note that the actual parameters depend on the model wrapper. You can check the documentation of the models to see which one are customizable.\n",
    "\n",
    "Finally, for a proper inference we always recommend to use the `Predictor` class instead. In that case, the safest way to handle postprocessing args is to pass the proper model wrapper's `PredParam`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "bac8c28c",
   "metadata": {},
   "outputs": [],
   "source": [
    "from deepvisiontools import Predictor\n",
    "from deepvisiontools.models.yolo import YoloPredParams\n",
    "\n",
    "params = YoloPredParams(conf_threshold=0.25, nms_iou=0.34, max_det=1000)\n",
    "\n",
    "predictor = Predictor(model=model, preprocessing=yolo_preprocessing, pred_params=params)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8c00fa25",
   "metadata": {},
   "source": [
    "Then use the standard `predictor.predict` method and the passed params will be used."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "904019b8",
   "metadata": {},
   "source": [
    "## 4. Custom dataset reader and writer\n",
    "\n",
    "DeepVisionDataset is intentionally format-agnostic. The registered COCO and\n",
    "semantic-mask-folder readers are convenient defaults, but they are not special\n",
    "inside the dataset class. A reader only needs to expose a small annotation API,\n",
    "and a writer only needs to know how to serialize one target at a time.\n",
    "\n",
    "In this section, we build a minimal YOLO-style detection format for the Dice\n",
    "dataset:\n",
    "\n",
    "```text\n",
    "yolo_dice_dataset/\n",
    "├── images/\n",
    "├── labels/\n",
    "│   ├── image_001.txt\n",
    "│   └── image_002.txt\n",
    "└── classes.txt\n",
    "```\n",
    "\n",
    "Each `.txt` file contains one box per line:\n",
    "\n",
    "```text\n",
    "class_id center_x center_y width height\n",
    "```\n",
    "\n",
    "The coordinates are normalized to `[0, 1]`, as in the usual YOLO layout.\n",
    "Inside deepvisiontools, however, the model-ready object remains a normal\n",
    "`BboxData` with pixel coordinates and a canvas size. The reader and writer are\n",
    "only responsible for converting between those two representations."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "357c6f52",
   "metadata": {},
   "outputs": [],
   "source": [
    "from pathlib import Path\n",
    "from shutil import rmtree\n",
    "\n",
    "from PIL import Image\n",
    "\n",
    "from deepvisiontools.data import BaseData, BboxData\n",
    "from deepvisiontools.datasets.base import AnnotationReader, AnnotationWriter\n",
    "\n",
    "\n",
    "YOLO_DICE_ROOT = Path(\"yolo_dice_dataset\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2ff4b031",
   "metadata": {},
   "source": [
    "We start with the writer because it gives us a simple way to create a\n",
    "YOLO-style copy of the existing Dice COCO dataset.\n",
    "\n",
    "The writer receives already-loaded targets from `DeepVisionDataset.export`.\n",
    "That means it does not need to know how the source dataset was stored. It only\n",
    "sees an image name, the image tensor, the current `BboxData`, and the category\n",
    "mapping.\n",
    "\n",
    "The important steps are:\n",
    "\n",
    "1. copy the target so we can change its box format without mutating the dataset,\n",
    "2. convert boxes to `CXCYWH`,\n",
    "3. normalize x/width by image width and y/height by image height,\n",
    "4. write one text file per image,\n",
    "5. write `classes.txt` once in `finalize`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f25c2985",
   "metadata": {},
   "outputs": [],
   "source": [
    "class YoloBBoxWriter(AnnotationWriter):\n",
    "    supported_types = {\"bbox\"}\n",
    "\n",
    "    def __init__(\n",
    "        self,\n",
    "        *,\n",
    "        labels_subdir: str = \"labels\",\n",
    "        classes_file: str = \"classes.txt\",\n",
    "    ) -> None:\n",
    "        self.labels_subdir = labels_subdir\n",
    "        self.classes_file = classes_file\n",
    "        self._records: list[tuple[str, list[str]]] = []\n",
    "        self._categories: dict[int, str] = {}\n",
    "\n",
    "    @property\n",
    "    def file_extension(self) -> str:\n",
    "        return \"txt\"\n",
    "\n",
    "    def write_item(\n",
    "        self,\n",
    "        image_name: str,\n",
    "        image: torch.Tensor,\n",
    "        target: BaseData,\n",
    "        categories: dict[int, str],\n",
    "    ) -> None:\n",
    "        if not isinstance(target, BboxData):\n",
    "            raise TypeError(\"YoloBBoxWriter expects BboxData targets.\")\n",
    "\n",
    "        self._categories.update({int(k): str(v) for k, v in categories.items()})\n",
    "\n",
    "        box_target = target._new_like()\n",
    "        box_target.boxformat = \"CXCYWH\"\n",
    "\n",
    "        height, width = int(image.shape[-2]), int(image.shape[-1])\n",
    "        boxes = torch.as_tensor(box_target.value).detach().cpu().float()\n",
    "        labels = box_target.labels.detach().cpu().long()\n",
    "\n",
    "        lines = []\n",
    "        for label, box in zip(labels.tolist(), boxes.tolist(), strict=False):\n",
    "            cx, cy, bw, bh = box\n",
    "            normalized = [\n",
    "                cx / width,\n",
    "                cy / height,\n",
    "                bw / width,\n",
    "                bh / height,\n",
    "            ]\n",
    "            values = \" \".join(f\"{v:.6f}\" for v in normalized)\n",
    "            lines.append(f\"{int(label)} {values}\")\n",
    "            self._categories.setdefault(int(label), f\"class_{int(label)}\")\n",
    "\n",
    "        label_name = Path(image_name).with_suffix(\".txt\").name\n",
    "        self._records.append((label_name, lines))\n",
    "\n",
    "    def finalize(self, destination_root: str | Path) -> None:\n",
    "        root = Path(destination_root)\n",
    "        labels_dir = root / self.labels_subdir\n",
    "        labels_dir.mkdir(parents=True, exist_ok=True)\n",
    "\n",
    "        for label_name, lines in self._records:\n",
    "            text = \"\\n\".join(lines)\n",
    "            if text:\n",
    "                text += \"\\n\"\n",
    "            (labels_dir / label_name).write_text(text, encoding=\"utf-8\")\n",
    "\n",
    "        max_class = max(self._categories, default=-1)\n",
    "        class_names = [\n",
    "            self._categories.get(i, f\"class_{i}\")\n",
    "            for i in range(max_class + 1)\n",
    "        ]\n",
    "        classes_text = \"\\n\".join(class_names)\n",
    "        if classes_text:\n",
    "            classes_text += \"\\n\"\n",
    "        (root / self.classes_file).write_text(classes_text, encoding=\"utf-8\")\n",
    "\n",
    "        self._records.clear()\n",
    "        self._categories.clear()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ac989c9f",
   "metadata": {},
   "source": [
    "Now we use the writer with the normal Dice COCO dataset.\n",
    "\n",
    "Two details matter here:\n",
    "\n",
    "- `preprocessing=None` keeps the exported images as normal image tensors. If we\n",
    "  kept ImageNet preprocessing, the exported images would be normalized model\n",
    "  inputs rather than ordinary images.\n",
    "- The source reader is still the built-in COCO reader. The custom part is only\n",
    "  the output format."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "417c476d",
   "metadata": {},
   "outputs": [],
   "source": [
    "if YOLO_DICE_ROOT.exists(): # remove if it already exists\n",
    "    rmtree(YOLO_DICE_ROOT)\n",
    "\n",
    "# load standard coco dice, but change the writer to be able to export as yolo format\n",
    "dice_source_for_export = DeepVisionDataset(\n",
    "    \"../demo_datasets/DiceDataset\",\n",
    "    reader=\"coco\",\n",
    "    data_type_reader=\"bbox\",\n",
    "    writer=YoloBBoxWriter(),\n",
    "    preprocessing=None,\n",
    ")\n",
    "\n",
    "# exporting to yolo format\n",
    "dice_source_for_export.export(\n",
    "    YOLO_DICE_ROOT,\n",
    "    num_visualizations=2,\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f2fe69fb",
   "metadata": {},
   "source": [
    "The custom writer produced a regular dataset folder that no longer depends on\n",
    "the original COCO annotations. To use this folder for training, we now need the\n",
    "opposite conversion: a reader that turns YOLO `.txt` annotations back into\n",
    "`BboxData`.\n",
    "\n",
    "A reader needs to implement the small `AnnotationReader` interface:\n",
    "\n",
    "- `scan()` returns the ordered image names,\n",
    "- `read_item(index)` returns `(image_name, target)`,\n",
    "- `category_ids` gives class names for visualization / validation,\n",
    "- `out_type` tells `DeepVisionDataset` which `BaseData` type is returned.\n",
    "\n",
    "Here we added the validation report that is optional but helpeful."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c01d933a",
   "metadata": {},
   "outputs": [],
   "source": [
    "class YoloBBoxReader(AnnotationReader):\n",
    "    def __init__(\n",
    "        self,\n",
    "        dataset_root: str | Path,\n",
    "        *,\n",
    "        labels_subdir: str = \"labels\",\n",
    "        classes_file: str = \"classes.txt\",\n",
    "    ) -> None:\n",
    "        self.root = Path(dataset_root)\n",
    "        self.image_dir = self.root / \"images\"\n",
    "        self.label_dir = self.root / labels_subdir\n",
    "        self.classes_path = self.root / classes_file\n",
    "        self._imgs = sorted(p.name for p in self.image_dir.iterdir())\n",
    "        self._cat_ids = self._read_categories()\n",
    "\n",
    "    @property\n",
    "    def category_ids(self) -> dict[int, str]:\n",
    "        return self._cat_ids\n",
    "\n",
    "    @property\n",
    "    def out_type(self) -> str:\n",
    "        return \"bbox\"\n",
    "\n",
    "    def __len__(self) -> int:\n",
    "        return len(self._imgs)\n",
    "\n",
    "    def scan(self) -> list[str]:\n",
    "        return self._imgs\n",
    "\n",
    "    def read_item(self, index: int) -> tuple[str, BboxData]:\n",
    "        image_name = self._imgs[index]\n",
    "        image_path = self.image_dir / image_name\n",
    "\n",
    "        with Image.open(image_path) as img:\n",
    "            width, height = img.size\n",
    "\n",
    "        label_path = self.label_dir / Path(image_name).with_suffix(\".txt\").name\n",
    "        rows = self._read_rows(label_path)\n",
    "\n",
    "        if not rows:\n",
    "            return image_name, BboxData.empty((height, width))\n",
    "\n",
    "        labels = torch.tensor([row[0] for row in rows], dtype=torch.long)\n",
    "        boxes = torch.tensor([row[1:] for row in rows], dtype=torch.float32)\n",
    "        boxes[:, [0, 2]] *= float(width)\n",
    "        boxes[:, [1, 3]] *= float(height)\n",
    "\n",
    "        target = BboxData(\n",
    "            value=boxes,\n",
    "            labels=labels,\n",
    "            canvas_size=(height, width),\n",
    "            boxformat=\"CXCYWH\",\n",
    "        )\n",
    "        return image_name, target\n",
    "\n",
    "    def validation_report(self, indices=None) -> dict[str, object]:\n",
    "        selected = range(len(self._imgs))\n",
    "        if indices is not None:\n",
    "            selected = [int(i) for i in indices]\n",
    "\n",
    "        selected_list = list(selected)\n",
    "        used_ids: set[int] = set()\n",
    "        num_annotations = 0\n",
    "\n",
    "        for i in selected_list:\n",
    "            image_name = self._imgs[i]\n",
    "            label_path = self.label_dir / Path(image_name).with_suffix(\".txt\").name\n",
    "            rows = self._read_rows(label_path)\n",
    "            num_annotations += len(rows)\n",
    "            used_ids.update(int(row[0]) for row in rows)\n",
    "\n",
    "        declared_ids = sorted(self._cat_ids)\n",
    "        used_ids_sorted = sorted(used_ids)\n",
    "\n",
    "        return {\n",
    "            \"reader\": \"custom_yolo_bbox\",\n",
    "            \"num_images\": len(selected_list),\n",
    "            \"num_annotations\": int(num_annotations),\n",
    "            \"declared_category_ids\": declared_ids,\n",
    "            \"declared_category_names\": dict(self._cat_ids),\n",
    "            \"used_category_ids\": used_ids_sorted,\n",
    "            \"unused_declared_category_ids\": [\n",
    "                i for i in declared_ids if i not in used_ids\n",
    "            ],\n",
    "            \"undeclared_used_category_ids\": [\n",
    "                i for i in used_ids_sorted if i not in self._cat_ids\n",
    "            ],\n",
    "        }\n",
    "\n",
    "    def _read_categories(self) -> dict[int, str]:\n",
    "        if self.classes_path.exists():\n",
    "            names = self.classes_path.read_text(encoding=\"utf-8\").splitlines()\n",
    "            return {i: name for i, name in enumerate(names) if name}\n",
    "\n",
    "        used_ids: set[int] = set()\n",
    "        for image_name in self._imgs:\n",
    "            label_path = self.label_dir / Path(image_name).with_suffix(\".txt\").name\n",
    "            rows = self._read_rows(label_path)\n",
    "            used_ids.update(int(row[0]) for row in rows)\n",
    "        return {i: f\"class_{i}\" for i in sorted(used_ids)}\n",
    "\n",
    "    @staticmethod\n",
    "    def _read_rows(label_path: Path) -> list[list[float]]:\n",
    "        if not label_path.exists():\n",
    "            return []\n",
    "\n",
    "        rows = []\n",
    "        for line in label_path.read_text(encoding=\"utf-8\").splitlines():\n",
    "            line = line.strip()\n",
    "            if not line:\n",
    "                continue\n",
    "            parts = line.split()\n",
    "            rows.append([int(parts[0]), *[float(v) for v in parts[1:5]]])\n",
    "        return rows"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5e0942ee",
   "metadata": {},
   "source": [
    "Finally, we instantiate `DeepVisionDataset` with the reader object directly.\n",
    "No registry entry is required: registries are convenient when you want a\n",
    "format to be available by name everywhere, but passing an object is enough for\n",
    "local project code and tutorials.\n",
    "\n",
    "The dataset below behaves like any other detection dataset in deepvisiontools.\n",
    "It returns image tensors, `BboxData` targets, and image names; therefore it can\n",
    "be used by `DeepVisionLoader`, the trainer, the evaluator, and visualization\n",
    "utilities."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "47f84039",
   "metadata": {},
   "outputs": [],
   "source": [
    "yolo_dice_reader = YoloBBoxReader(YOLO_DICE_ROOT)\n",
    "\n",
    "yolo_dice_dataset = DeepVisionDataset(\n",
    "    YOLO_DICE_ROOT,\n",
    "    reader=yolo_dice_reader,\n",
    "    writer=YoloBBoxWriter(),\n",
    "    preprocessing=yolo_preprocessing,\n",
    ")\n",
    "\n",
    "image, target, image_name = yolo_dice_dataset[0]\n",
    "\n",
    "print(image_name)\n",
    "print(image.shape)\n",
    "print(target)\n",
    "print(target.boxformat)\n",
    "print(yolo_dice_dataset.category_ids)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cc718ca3",
   "metadata": {},
   "source": [
    "A quick loader smoke test confirms that batching still works.\n",
    "\n",
    "`BatchData` pads annotations to a common canvas when needed, keeps the data\n",
    "type information, and exposes the same target API used by every model wrapper.\n",
    "From this point on, the training code does not care whether the annotations\n",
    "came from COCO JSON, YOLO text files, a database, or a fully custom layout."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "bc9e3e1e",
   "metadata": {},
   "outputs": [],
   "source": [
    "yolo_dice_loader = DeepVisionLoader(\n",
    "    yolo_dice_dataset,\n",
    "    batch_size=4,\n",
    "    shuffle=True,\n",
    ")\n",
    "\n",
    "images, targets, names = next(iter(yolo_dice_loader))\n",
    "\n",
    "print(images.shape)\n",
    "print(targets)\n",
    "print(names[:2])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c678a74e",
   "metadata": {},
   "source": [
    "The same custom writer can also be attached to the YOLO-backed dataset and used\n",
    "to re-export a subset. This is useful when you create train/valid/test splits,\n",
    "filter bad samples, or convert one custom layout into another.\n",
    "\n",
    "The example is left commented to avoid writing another copy every time the\n",
    "notebook is run."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "209054ec",
   "metadata": {},
   "outputs": [],
   "source": [
    "small_yolo_subset = yolo_dice_dataset.keep_indices(range(5))\n",
    "small_yolo_subset.set_writer(YoloBBoxWriter())\n",
    "small_yolo_subset.preprocessing = None\n",
    "\n",
    "small_yolo_subset.export(\n",
    "    \"yolo_dice_subset\",\n",
    "    num_visualizations=\"all\",\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "47e0460d",
   "metadata": {},
   "source": [
    "This is the complete dataset extension pattern.\n",
    "\n",
    "Use a **reader** when deepvisiontools needs to consume a new annotation layout,\n",
    "and use a **writer** when deepvisiontools needs to export to a new layout. For\n",
    "reusable library code, place the classes in a Python module and optionally\n",
    "register factories with `register_reader` / `register_writer`. For one-off\n",
    "project code, passing instantiated reader and writer objects is often cleaner."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "16161f85",
   "metadata": {},
   "source": [
    "## 5. Custom DeepVisionModel with torchvision Faster R-CNN\n",
    "\n",
    "In this section we will see how you actually write your own custome model wrappers suitable for deepvisiontools. This is done through implementing a specific `DeepVisionModel` object that contains all the minimal API to adapt the runs in deepvisiontools.\n",
    "\n",
    "A `DeepVisionModel` is a small façade around four parts:\n",
    "\n",
    "```text\n",
    "images, targets\n",
    "      │\n",
    "      v\n",
    "preprocessor ──> backend ──> loss\n",
    "                     │\n",
    "                     v\n",
    "               postprocessor ──> BatchData predictions\n",
    "```\n",
    "\n",
    "For a custom model, you generally need:\n",
    "\n",
    "- a backend: wraps the actual `torch.nn.Module`.\n",
    "- a preprocessor: converts deepvisiontools `BatchData` targets to the backend format. You can inforce resizing or padding here.\n",
    "- a postprocessor: converts backend predictions back to `BatchData`. It also must reverse the padding, resizing etc. performed by the preprocessor.\n",
    "- a loss adapter: converts backend losses into a dict containing at least `\"loss\"`.\n",
    "\n",
    "Here, we use torchvision Faster R-CNN as a detection backend. Note that torchvision detection labels reserve `0` for background, while deepvisiontools labels start at `0`, so the preprocessor adds `+1` and the postprocessor subtracts `1`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "34a7163d",
   "metadata": {},
   "outputs": [],
   "source": [
    "from dataclasses import dataclass\n",
    "from typing import Any\n",
    "\n",
    "import torch\n",
    "from torch import nn\n",
    "from torchvision.models.detection import (\n",
    "    FasterRCNN_MobileNet_V3_Large_FPN_Weights,\n",
    "    fasterrcnn_mobilenet_v3_large_fpn,\n",
    ")\n",
    "from torchvision.models.detection.faster_rcnn import FastRCNNPredictor\n",
    "from torchvision.ops import nms\n",
    "\n",
    "from deepvisiontools.data import BatchData, BboxData\n",
    "from deepvisiontools.models.base.basemodel import (\n",
    "    BaseLoss,\n",
    "    BasePredParams,\n",
    "    DeepVisionModel,\n",
    "    MODEL_REGISTRY,\n",
    ")\n",
    "from deepvisiontools.models.base.protocols import Capabilities\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "# first, declare a PredParam for customizable post processing.\n",
    "@dataclass\n",
    "class FasterRCNNPredParams(BasePredParams):\n",
    "    conf_threshold: float = 0.25\n",
    "    nms_iou: float = 0.50\n",
    "    max_det: int = 100\n",
    "\n",
    "    # this part is the default setup\n",
    "    @staticmethod\n",
    "    def default_from_config():\n",
    "        box_cfg = current().data_box\n",
    "        return FasterRCNNPredParams(\n",
    "            conf_threshold=float(box_cfg.conf_threshold),\n",
    "            nms_iou=float(box_cfg.nms_threshold),\n",
    "            max_det=int(box_cfg.max_det),\n",
    "        )\n",
    "    # this part is the metrics setup : typically, for mAP, you'd like to be quite low in threshold to not interfere with mAP (mAP formal definition uses all predictions, \n",
    "    # but a cut-off at 1e-2 usually does not affect the values and save a large amount of computing time)\n",
    "    def pred_params_for_metrics(self):\n",
    "        return FasterRCNNPredParams(\n",
    "            conf_threshold=1e-2,\n",
    "            nms_iou=0.95,\n",
    "            max_det=1000,\n",
    "        )"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4884aa48",
   "metadata": {},
   "source": [
    "<!-- adv-note-custom-predparams -->\n",
    "This object keeps the custom model compatible with the rest of the deepvisiontools inference API. The normal thresholds are used by `predict`, while the permissive metric thresholds avoid hiding low-confidence predictions before metric computation."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d989478a",
   "metadata": {},
   "outputs": [],
   "source": [
    "class FasterRCNNPre(nn.Module):\n",
    "    def images_only(self, images: torch.Tensor) -> torch.Tensor:\n",
    "        return images\n",
    "\n",
    "    def images_targets(\n",
    "        self,\n",
    "        images: torch.Tensor,\n",
    "        targets: BatchData,\n",
    "    ) -> tuple[torch.Tensor, list[dict[str, torch.Tensor]]]:\n",
    "        out_targets = []\n",
    "\n",
    "        for item in targets.datas:\n",
    "            if not isinstance(item, BboxData):\n",
    "                raise TypeError(\"Faster R-CNN expects BboxData targets.\")\n",
    "\n",
    "            box_item = item._new_like()\n",
    "            box_item.boxformat = \"XYXY\"\n",
    "\n",
    "            boxes = torch.as_tensor(\n",
    "                box_item.value,\n",
    "                dtype=torch.float32,\n",
    "                device=images.device,\n",
    "            )\n",
    "            labels = box_item.labels.to(images.device).long() + 1\n",
    "\n",
    "            out_targets.append(\n",
    "                {\n",
    "                    \"boxes\": boxes,\n",
    "                    \"labels\": labels,\n",
    "                }\n",
    "            )\n",
    "\n",
    "        return images, out_targets"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "98076a77",
   "metadata": {},
   "outputs": [],
   "source": [
    "class FasterRCNNBackend(nn.Module):\n",
    "    def __init__(\n",
    "        self,\n",
    "        *,\n",
    "        num_classes: int,\n",
    "        pretrained: bool = True,\n",
    "    ) -> None:\n",
    "        super().__init__()\n",
    "\n",
    "        weights = None\n",
    "        if pretrained:\n",
    "            weights = FasterRCNN_MobileNet_V3_Large_FPN_Weights.DEFAULT\n",
    "\n",
    "        self.model = fasterrcnn_mobilenet_v3_large_fpn(weights=weights)\n",
    "        in_features = self.model.roi_heads.box_predictor.cls_score.in_features\n",
    "\n",
    "        self.model.roi_heads.box_predictor = FastRCNNPredictor(\n",
    "            in_features,\n",
    "            num_classes + 1,\n",
    "        )\n",
    "\n",
    "    def forward(\n",
    "        self,\n",
    "        x: torch.Tensor,\n",
    "        *,\n",
    "        extra_args: dict[str, Any] | None = None,\n",
    "    ) -> dict[str, Any]:\n",
    "        images = [img for img in x]\n",
    "        targets = None\n",
    "\n",
    "        if isinstance(extra_args, dict):\n",
    "            targets = extra_args.get(\"targets\")\n",
    "\n",
    "        if self.training:\n",
    "            losses = self.model(images, targets)\n",
    "            return {\"losses\": losses, \"predictions\": None}\n",
    "\n",
    "        predictions = self.model(images)\n",
    "\n",
    "        if targets is None:\n",
    "            return {\"losses\": None, \"predictions\": predictions}\n",
    "\n",
    "        self.model.train()\n",
    "        losses = self.model(images, targets)\n",
    "        self.model.eval()\n",
    "\n",
    "        return {\"losses\": losses, \"predictions\": predictions}"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "25262d52",
   "metadata": {},
   "source": [
    "<!-- adv-note-custom-backend -->\n",
    "The backend isolates the torchvision-specific calling convention. It converts the input batch to `list[Tensor]`, calls Faster R-CNN, and returns a simple raw dictionary containing losses and/or predictions."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "13f86988",
   "metadata": {},
   "outputs": [],
   "source": [
    "class FasterRCNNLoss(BaseLoss):\n",
    "    def forward(\n",
    "        self,\n",
    "        raw_outputs: dict[str, Any],\n",
    "        targets: Any,\n",
    "    ) -> dict[str, torch.Tensor]:\n",
    "        losses = raw_outputs[\"losses\"]\n",
    "        total = sum(losses.values())\n",
    "\n",
    "        out = {\"loss\": total}\n",
    "        for name, value in losses.items():\n",
    "            out[f\"loss_{name}\"] = value\n",
    "\n",
    "        return out"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a4cb8eff",
   "metadata": {},
   "source": [
    "<!-- adv-note-custom-loss -->\n",
    "The loss adapter turns torchvision's loss dictionary into the format expected by the trainer. The key `\"loss\"` is the global value used for backpropagation and monitoring; the other keys (loss details) remain available for logging."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a52a09fe",
   "metadata": {},
   "outputs": [],
   "source": [
    "# the post processing converts the raw backend output to proper deepvisiontools' BatchData\n",
    "# Note that this is typically the place to run nms\n",
    "\n",
    "class FasterRCNNPost(nn.Module):\n",
    "    def preds_from_raw(\n",
    "        self,\n",
    "        raw_outputs: dict[str, Any],\n",
    "        aux: Any | None = None,\n",
    "    ) -> BatchData:\n",
    "        pred_params = FasterRCNNPredParams.default_from_config()\n",
    "        canvas_size = None\n",
    "\n",
    "        if isinstance(aux, dict):\n",
    "            canvas_size = aux.get(\"canvas_size\")\n",
    "            if aux.get(\"pred\") is not None:\n",
    "                pred_params = aux[\"pred\"]\n",
    "\n",
    "        predictions = raw_outputs[\"predictions\"]\n",
    "        out_items = []\n",
    "\n",
    "        for pred in predictions:\n",
    "            boxes = pred[\"boxes\"].to(dtype=torch.float32)\n",
    "            scores = pred[\"scores\"].to(dtype=torch.float32)\n",
    "            labels = pred[\"labels\"].to(dtype=torch.long) - 1\n",
    "\n",
    "            keep = scores >= float(pred_params.conf_threshold)\n",
    "            boxes = boxes[keep]\n",
    "            scores = scores[keep]\n",
    "            labels = labels[keep]\n",
    "\n",
    "            if boxes.numel() > 0:\n",
    "                keep_idx = nms(\n",
    "                    boxes,\n",
    "                    scores,\n",
    "                    float(pred_params.nms_iou),\n",
    "                )\n",
    "                keep_idx = keep_idx[: int(pred_params.max_det)]\n",
    "                boxes = boxes[keep_idx]\n",
    "                scores = scores[keep_idx]\n",
    "                labels = labels[keep_idx]\n",
    "\n",
    "            if canvas_size is None:\n",
    "                canvas_size = (0, 0)\n",
    "\n",
    "            if boxes.numel() == 0:\n",
    "                item = BboxData.empty(\n",
    "                    canvas_size=canvas_size,\n",
    "                    boxformat=\"XYXY\",\n",
    "                    device=boxes.device,\n",
    "                )\n",
    "            else:\n",
    "                item = BboxData(\n",
    "                    value=boxes,\n",
    "                    labels=labels,\n",
    "                    scores=scores,\n",
    "                    canvas_size=canvas_size,\n",
    "                    boxformat=\"XYXY\",\n",
    "                    device=boxes.device,\n",
    "                )\n",
    "\n",
    "            out_items.append(item)\n",
    "\n",
    "        device = predictions[0][\"boxes\"].device if predictions else \"cpu\"\n",
    "        return BatchData(out_items, device=device)\n",
    "\n",
    "    def undo_preproc(\n",
    "        self,\n",
    "        preds: BatchData,\n",
    "        *,\n",
    "        original_hw: tuple[int, int] | None = None,\n",
    "    ) -> BatchData:\n",
    "        return preds"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5876327b",
   "metadata": {},
   "source": [
    "<!-- adv-note-custom-post -->\n",
    "The postprocessor converts torchvision predictions back to `BatchData[BboxData]`. It reverses the label shift with `-1`, applies the custom confidence/NMS/max-det parameters, and returns empty `BboxData` objects when an image has no remaining detections."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "03b1b197",
   "metadata": {},
   "outputs": [],
   "source": [
    "def build_torchvision_fasterrcnn(\n",
    "    *,\n",
    "    num_classes: int = 1,\n",
    "    pretrained: bool = True,\n",
    "    device: str | torch.device | None = None,\n",
    "    use_amp: bool | None = None,\n",
    ") -> DeepVisionModel:\n",
    "    backend = FasterRCNNBackend(\n",
    "        num_classes=num_classes,\n",
    "        pretrained=pretrained,\n",
    "    )\n",
    "\n",
    "    model = DeepVisionModel(\n",
    "        backend=backend,\n",
    "        pre=FasterRCNNPre(),\n",
    "        post=FasterRCNNPost(),\n",
    "        loss_fn=FasterRCNNLoss(),\n",
    "        pred_params=FasterRCNNPredParams.default_from_config(),\n",
    "        caps=Capabilities(\n",
    "            task=\"bbox\",\n",
    "            supports_amp=True,\n",
    "            description=\"torchvision Faster R-CNN demo backend\",\n",
    "        ),\n",
    "        device=device,\n",
    "        use_amp=use_amp,\n",
    "    )\n",
    "\n",
    "    export_kwargs = {\n",
    "        \"num_classes\": int(num_classes),\n",
    "        \"pretrained\": False,\n",
    "        \"device\": device,\n",
    "        \"use_amp\": use_amp,\n",
    "    }\n",
    "    model.set_export_spec(\"torchvision_fasterrcnn_demo\", export_kwargs)\n",
    "\n",
    "    return model"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "16b43df4",
   "metadata": {},
   "source": [
    "<!-- adv-note-custom-builder -->\n",
    "The builder now attaches an export spec to the returned `DeepVisionModel`. This is the metadata needed by portable artifacts and YAML export: a builder name plus YAML-safe kwargs. Notice that `pretrained=False` is used in the export spec because a saved artifact already contains trained weights; reloading should rebuild the architecture, then load the saved state dict."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3dc36860",
   "metadata": {},
   "source": [
    "We can now build the custom model and run a single batch through `train_step`,\n",
    "`eval_step`, and `predict`.\n",
    "\n",
    "The builder attaches an export spec, so the model knows how it should be rebuilt\n",
    "for portable artifacts. In this notebook the builder is local, which is enough to\n",
    "inspect/export the spec. To reload a saved artifact or a YAML config in a fresh\n",
    "Python process, the builder must also be importable and registered under the same\n",
    "name."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8cd2a5ad",
   "metadata": {},
   "outputs": [],
   "source": [
    "custom_model = build_torchvision_fasterrcnn(\n",
    "    num_classes=1,\n",
    "    pretrained=True,\n",
    "    device=\"cuda\",\n",
    ")\n",
    "\n",
    "images, targets, names = next(iter(train_loader))\n",
    "\n",
    "train_output = custom_model.train_step(images, targets)\n",
    "eval_output = custom_model.eval_step(images, targets)\n",
    "pred_output = custom_model.predict(images)\n",
    "\n",
    "print(train_output.lossesdict())\n",
    "print(eval_output.preds)\n",
    "print(pred_output.preds)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d6c5c051",
   "metadata": {},
   "source": [
    "<!-- adv-note-custom-smoke-test -->\n",
    "This smoke test checks the three public `DeepVisionModel` paths. `train_step`\n",
    "returns a loss dictionary, `eval_step` returns losses plus decoded predictions,\n",
    "and `predict` returns decoded predictions only. The same wrapper can therefore be\n",
    "used by the trainer, evaluator, and predictor-style inference code."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0916547d",
   "metadata": {},
   "source": [
    "The export spec can be inspected directly. It is just a tuple:\n",
    "\n",
    "```text\n",
    "(builder_name, builder_kwargs)\n",
    "```\n",
    "\n",
    "For a custom model, this is the most important piece of metadata to keep portable\n",
    "training configs and saved model artifacts reproducible."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ca942811",
   "metadata": {},
   "outputs": [],
   "source": [
    "builder_name, builder_kwargs = custom_model.export_spec()\n",
    "\n",
    "print(builder_name)\n",
    "print(builder_kwargs)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ced40997",
   "metadata": {},
   "source": [
    "<!-- adv-note-custom-export-output -->\n",
    "The printed kwargs are intentionally simple: integers, booleans, strings, or `None`. Avoid storing runtime objects such as instantiated modules, datasets, loss objects, or lambdas in an export spec, because they cannot be represented cleanly in YAML or checkpoint metadata."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "62ba7459",
   "metadata": {},
   "source": [
    "The custom model can also be used by the `Trainer`. Because the model already has\n",
    "an export spec, the config can be exported to YAML and model artifacts can be\n",
    "saved.\n",
    "\n",
    "For artifact reload in a fresh process, register the builder under the same name.\n",
    "In a real project this should live in a normal Python module imported before\n",
    "loading the artifact. The small guard below keeps the notebook cell rerunnable."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b8baf4b4",
   "metadata": {},
   "outputs": [],
   "source": [
    "if \"torchvision_fasterrcnn_demo\" not in MODEL_REGISTRY.available():\n",
    "    MODEL_REGISTRY.register(\"torchvision_fasterrcnn_demo\")(build_torchvision_fasterrcnn)\n",
    "\n",
    "custom_train_config = TrainerConfig(\n",
    "    model=custom_model,\n",
    "    train_loader=train_loader,\n",
    "    valid_loader=valid_loader,\n",
    "    epochs=2,\n",
    "    output_dir=\"custom_fasterrcnn_runs\",\n",
    ")\n",
    "\n",
    "custom_train_config.devices.device = \"cuda\"\n",
    "custom_train_config.optim.optimizer = torch.optim.AdamW\n",
    "custom_train_config.optim.optim_args = {\"lr\": 1e-4}\n",
    "custom_train_config.optim.weight_decay = 1e-4\n",
    "custom_train_config.sched.scheduler = None\n",
    "\n",
    "custom_train_config.checkpoint.enable_checkpointing = True\n",
    "custom_train_config.checkpoint.save_every_n_epochs = 1\n",
    "custom_train_config.checkpoint.export_model_artifact = True\n",
    "custom_train_config.checkpoint.export_when = \"best\"\n",
    "\n",
    "custom_train_config.logging.backends = [\"mlflow\"]\n",
    "custom_train_config.logging.mlflow_experiment_name = \"custom_fasterrcnn\"\n",
    "custom_train_config.logging.mlflow_run_name = \"demo\"\n",
    "\n",
    "custom_train_config.validate()\n",
    "custom_train_config.export_yaml(\n",
    "    \"custom_fasterrcnn_config.yaml\",\n",
    "    portable=True,\n",
    "    include_meta=True,\n",
    ")\n",
    "\n",
    "print(custom_train_config.model_spec)\n",
    "\n",
    "# Uncomment to train the custom model.\n",
    "Trainer(custom_train_config).fit(resume=None)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "52bc36bc",
   "metadata": {},
   "source": [
    "<!-- adv-note-custom-trainer-export -->\n",
    "`TrainerConfig(model=custom_model, ...)` automatically captured the model export spec into `model_spec`. The exported YAML therefore contains the custom builder name and kwargs. The small registration block is only needed for reload/build workflows, because `ModelFactory` must know how to map that builder name back to Python code."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "70177270",
   "metadata": {},
   "source": [
    "#### This concludes the advanced usage tutorial."
   ]
  }
 ],
 "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
}