-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathtrain.py
More file actions
3822 lines (3674 loc) · 177 KB
/
train.py
File metadata and controls
3822 lines (3674 loc) · 177 KB
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
import argparse
import glob
import json
import os
import random
import math
from copy import deepcopy
from typing import Dict, Sequence, Optional, Tuple, List, Set
import numpy as np
import torch
import torch.nn.functional as F
import yaml
from PIL import Image, ImageDraw, ImageFont
from torch.nn.utils import clip_grad_norm_
from torch.optim.lr_scheduler import CosineAnnealingLR
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter
from tqdm import tqdm
from faster_coco_eval import COCO, COCOeval_faster
from uhd.data import YoloDataset, detection_collate
from uhd.losses import anchor_loss, anchor_attr_loss, centernet_loss, detr_loss
from uhd.metrics import decode_anchor, decode_centernet, decode_detr, evaluate_map
from uhd.backbones import load_dinov3_backbone
from uhd.models import build_model
from uhd.utils import default_device, ensure_dir, move_targets, set_seed
from uhd.resize import (
Y_BIN_RESIZE_MODE,
Y_ONLY_RESIZE_MODE,
Y_TRI_RESIZE_MODE,
YUV422_RESIZE_MODE,
normalize_resize_mode,
rgb_to_y,
y_to_bin,
y_to_tri,
)
class ModelEma:
"""Exponential Moving Average of model parameters/buffers."""
def __init__(self, model: torch.nn.Module, decay: float = 0.9998, device: torch.device = None) -> None:
self.decay = decay
self.device = device
self.ema = deepcopy(model)
self.ema.eval()
self.updates = 0
if self.device is not None:
self.ema.to(self.device)
def _get_decay(self) -> float:
# Warmup EMA decay to let early steps catch up; similar to timm/yolo practice.
self.updates += 1
warmup = (1 + self.updates) / (10 + self.updates)
return min(self.decay, warmup)
@torch.no_grad()
def update(self, model: torch.nn.Module) -> None:
d = self._get_decay()
ema_params = dict(self.ema.named_parameters())
model_params = dict(model.named_parameters())
for k, ema_v in ema_params.items():
model_v = model_params[k].detach()
if self.device is not None:
model_v = model_v.to(self.device)
ema_v.mul_(d).add_(model_v, alpha=1.0 - d)
ema_buffers = dict(self.ema.named_buffers())
model_buffers = dict(model.named_buffers())
for k, ema_b in ema_buffers.items():
model_b = model_buffers.get(k)
if model_b is None:
continue
if ema_b.shape != model_b.shape:
if not hasattr(self, "_warned_shape_mismatch"):
print("[WARN] EMA skipped buffers with shape mismatch (likely QAT observers).")
self._warned_shape_mismatch = True
continue
if model_b.dtype.is_floating_point:
if self.device is not None:
model_b = model_b.to(self.device)
ema_b.mul_(d).add_(model_b, alpha=1.0 - d)
else:
ema_b.copy_(model_b)
@torch.no_grad()
def apply_to(self, model: torch.nn.Module) -> None:
model.load_state_dict(self.ema.state_dict())
def prepare_qat(model: torch.nn.Module, backend: str, fuse: bool) -> None:
import torch.ao.quantization as quant
torch.backends.quantized.engine = backend
if fuse:
if hasattr(model, "fuse_model"):
model.fuse_model(qat=True)
else:
print("[WARN] Requested QAT fusion, but fuse_model is not implemented for this architecture.")
model.qconfig = quant.get_default_qat_qconfig(backend)
quant.prepare_qat(model, inplace=True)
def freeze_bn_stats(model: torch.nn.Module) -> None:
for module in model.modules():
if isinstance(module, torch.nn.modules.batchnorm._BatchNorm):
module.eval()
def step_qat_schedule(model: torch.nn.Module, epoch: int, disable_obs_epoch: int, freeze_bn_epoch: int) -> None:
import torch.ao.quantization as quant
if disable_obs_epoch and (epoch + 1) == disable_obs_epoch:
quant.disable_observer(model)
if freeze_bn_epoch and (epoch + 1) == freeze_bn_epoch:
if hasattr(quant, "freeze_bn_stats"):
quant.freeze_bn_stats(model)
else:
freeze_bn_stats(model)
model._qat_freeze_bn = True
def parse_args():
parser = argparse.ArgumentParser(description="Ultra-lightweight detection trainer (CNN/Transformer).")
parser.add_argument("--arch", choices=["cnn", "transformer", "ultratinyod"], default="cnn")
parser.add_argument(
"--image-dir",
default=None,
help="Directory with images and YOLO txt labels (required when not using --train-list/--val-list).",
)
parser.add_argument(
"--train-list",
default=None,
help="Optional train list file (one image path per line). Requires --val-list and ignores split ratios.",
)
parser.add_argument(
"--val-list",
default=None,
help="Optional validation list file (one image path per line). Requires --train-list and ignores split ratios.",
)
parser.add_argument("--train-split", type=float, default=0.8, help="Fraction of data for training.")
parser.add_argument("--val-split", type=float, default=0.2, help="Fraction of data for validation.")
parser.add_argument(
"--img-size",
default="64x64",
help="Input size as HxW, e.g., 64x64. If single int, applies to both sides.",
)
parser.set_defaults(resize_mode="torch_bilinear")
resize_group = parser.add_mutually_exclusive_group()
resize_group.add_argument(
"--resize-mode",
choices=[
"torch_bilinear",
"torch_nearest",
"opencv_inter_linear",
"opencv_inter_nearest",
"opencv_inter_nearest_y_bin",
"opencv_inter_nearest_y",
"opencv_inter_nearest_y_tri",
"opencv_inter_nearest_yuv422",
],
dest="resize_mode",
help="Resize mode used during training preprocessing.",
)
resize_group.add_argument(
"--torch_bilinear",
dest="resize_mode",
action="store_const",
const="torch_bilinear",
help="Shortcut for --resize-mode torch_bilinear.",
)
resize_group.add_argument(
"--torch_nearest",
dest="resize_mode",
action="store_const",
const="torch_nearest",
help="Shortcut for --resize-mode torch_nearest.",
)
resize_group.add_argument(
"--opencv_inter_linear",
dest="resize_mode",
action="store_const",
const="opencv_inter_linear",
help="Shortcut for --resize-mode opencv_inter_linear.",
)
resize_group.add_argument(
"--opencv_inter_nearest",
dest="resize_mode",
action="store_const",
const="opencv_inter_nearest",
help="Shortcut for --resize-mode opencv_inter_nearest.",
)
resize_group.add_argument(
"--opencv_inter_nearest_y",
dest="resize_mode",
action="store_const",
const="opencv_inter_nearest_y",
help="Shortcut for --resize-mode opencv_inter_nearest_y.",
)
resize_group.add_argument(
"--opencv_inter_nearest_y_bin",
dest="resize_mode",
action="store_const",
const="opencv_inter_nearest_y_bin",
help="Shortcut for --resize-mode opencv_inter_nearest_y_bin.",
)
resize_group.add_argument(
"--opencv_inter_nearest_y_tri",
dest="resize_mode",
action="store_const",
const="opencv_inter_nearest_y_tri",
help="Shortcut for --resize-mode opencv_inter_nearest_y_tri.",
)
resize_group.add_argument(
"--opencv_inter_nearest_yuv422",
dest="resize_mode",
action="store_const",
const="opencv_inter_nearest_yuv422",
help="Shortcut for --resize-mode opencv_inter_nearest_yuv422.",
)
parser.add_argument("--exp-name", default="default", help="Experiment name; logs will be saved under runs/<exp-name>.")
parser.add_argument("--batch-size", type=int, default=64)
parser.add_argument("--epochs", type=int, default=100)
parser.add_argument("--resume", default=None, help="Path to checkpoint to resume training.")
parser.add_argument("--ckpt", default=None, help="Path to checkpoint to initialize weights (no optimizer state).")
parser.add_argument("--ckpt-non-strict", action="store_true", help="Load --ckpt weights with strict=False (ignore missing/unexpected keys).")
parser.add_argument("--teacher-ckpt", default=None, help="Path to teacher checkpoint for distillation.")
parser.add_argument("--teacher-arch", default=None, help="Teacher architecture override (default: checkpoint arch or student arch).")
parser.add_argument("--teacher-num-queries", type=int, default=None, help="Teacher num-queries (defaults to student).")
parser.add_argument("--teacher-d-model", type=int, default=None, help="Teacher d-model (defaults to student).")
parser.add_argument("--teacher-heads", type=int, default=None, help="Teacher heads (defaults to student).")
parser.add_argument("--teacher-layers", type=int, default=None, help="Teacher layers (defaults to student).")
parser.add_argument("--teacher-dim-feedforward", type=int, default=None, help="Teacher FFN dim (defaults to student).")
parser.add_argument("--teacher-use-skip", action="store_true", help="Force teacher use-skip on (otherwise checkpoint/student default).")
parser.add_argument("--teacher-activation", choices=["relu", "swish"], default=None, help="Teacher activation (defaults to checkpoint or student).")
parser.add_argument("--teacher-use-fpn", action="store_true", help="Force teacher use-fpn on (otherwise checkpoint/student default).")
parser.add_argument("--teacher-backbone", default=None, help="Path to teacher backbone checkpoint for feature distillation (e.g., DINOv3).")
parser.add_argument("--teacher-backbone-arch", default=None, help="Teacher backbone architecture hint (e.g., dinov3_vits16, dinov3_vitb16).")
parser.add_argument("--teacher-backbone-norm", default="imagenet", choices=["imagenet", "none"], help="Normalization applied to teacher backbone input.")
parser.add_argument(
"--override-from-teacher-anchors",
action="store_true",
help="When distilling, override student anchors with teacher anchors (requires --teacher-ckpt).",
)
parser.add_argument(
"--distill-kl",
type=float,
default=0.0,
help="Weight for KL distillation loss (anchor/centernet/transformer).",
)
parser.add_argument(
"--distill-box-l1",
type=float,
default=0.0,
help="Weight for box L1 distillation (anchor/centernet/transformer).",
)
parser.add_argument("--distill-obj", type=float, default=0.0, help="Weight for objectness distillation (anchor head).")
parser.add_argument("--distill-quality", type=float, default=0.0, help="Weight for quality-score distillation (anchor head).")
parser.add_argument("--distill-cosine", action="store_true", help="Use cosine ramp-up of distill weights over epochs.")
parser.add_argument("--distill-temperature", type=float, default=1.0, help="Temperature for teacher logits in distillation.")
parser.add_argument(
"--distill-feat",
type=float,
default=0.0,
help="Weight for feature-map distillation from teacher backbone/model (CNN only).",
)
parser.add_argument("--lr", type=float, default=1e-3)
parser.add_argument("--weight-decay", type=float, default=1e-4)
parser.add_argument("--optimizer", choices=["adamw", "sgd"], default="adamw", help="Optimizer to use (UltraTinyOD can benefit from SGD).")
parser.add_argument("--grad-clip-norm", type=float, default=5.0, help="Global gradient norm clip value (0 to disable).")
parser.add_argument("--num-workers", type=int, default=8)
parser.add_argument("--device", default=None, help="cuda or cpu. Defaults to cuda if available.")
parser.add_argument("--seed", type=int, default=42)
parser.add_argument("--log-interval", type=int, default=10)
parser.add_argument("--eval-interval", type=int, default=1)
parser.add_argument("--conf-thresh", type=float, default=0.15)
parser.add_argument("--topk", type=int, default=50, help="Top-K for CNN decoding.")
parser.add_argument("--use-amp", action="store_true", help="Enable automatic mixed precision training.")
parser.add_argument("--qat", action="store_true", help="Enable QAT via torch.ao.quantization.")
parser.add_argument("--qat-backend", choices=["fbgemm", "qnnpack"], default="fbgemm", help="Quantization backend for QAT.")
parser.add_argument("--qat-fuse", action="store_true", help="Fuse Conv+BN(+ReLU) before QAT.")
parser.add_argument("--qat-disable-observer-epoch", type=int, default=2, help="Epoch (1-based) to disable observers (0 to skip).")
parser.add_argument("--qat-freeze-bn-epoch", type=int, default=3, help="Epoch (1-based) to freeze BN stats (0 to skip).")
parser.add_argument("--w-bits", type=int, default=0, help="Fake-quant bits for weights (UltraTinyOD only, 0 disables).")
parser.add_argument("--a-bits", type=int, default=0, help="Fake-quant bits for activations (UltraTinyOD only, 0 disables).")
parser.add_argument(
"--quant-target",
choices=["backbone", "head", "both", "none"],
default="both",
help="Quantization target for UltraTinyOD (default: both).",
)
parser.add_argument(
"--lowbit-quant-target",
choices=["backbone", "head", "both", "none"],
default=None,
help="Low-bit quantization target (defaults to --quant-target).",
)
parser.add_argument("--lowbit-w-bits", type=int, default=None, help="Low-bit weight bits (defaults to --w-bits).")
parser.add_argument("--lowbit-a-bits", type=int, default=None, help="Low-bit activation bits (defaults to --a-bits).")
parser.add_argument(
"--highbit-quant-target",
choices=["backbone", "head", "both", "none"],
default="none",
help="High-bit quantization target (default: none).",
)
parser.add_argument("--highbit-w-bits", type=int, default=8, help="High-bit weight bits (default: 8).")
parser.add_argument("--highbit-a-bits", type=int, default=8, help="High-bit activation bits (default: 8).")
parser.add_argument("--aug-config", default="uhd/aug.yaml", help="Path to YAML file specifying data augmentations.")
parser.add_argument("--val-aug-config", default=None, help="Optional YAML file for validation-time augmentations.")
parser.add_argument("--use-ema", action="store_true", help="Enable EMA of model weights for evaluation/checkpointing.")
parser.add_argument("--ema-decay", type=float, default=0.9998, help="EMA decay factor (ignored if EMA disabled).")
parser.add_argument("--coco-eval", action="store_true", help="Run COCO-style evaluation (requires faster-coco-eval or pycocotools).")
parser.add_argument("--coco-per-class", action="store_true", help="Log per-class COCO AP when COCO eval is enabled.")
parser.add_argument("--val-only", action="store_true", help="Run validation only using --ckpt or --resume weights and exit.")
parser.add_argument("--val-count", type=int, default=None, help="Limit number of validation images when using --val-only.")
heatmap_group = parser.add_mutually_exclusive_group()
heatmap_group.add_argument(
"--with-heatmap-mean",
dest="heatmap_mode",
action="store_const",
const="mean",
help="Save per-layer heatmap visualizations (channel mean) for sampled validation images.",
)
heatmap_group.add_argument(
"--with-heatmap-sum",
dest="heatmap_mode",
action="store_const",
const="sum",
help="Save per-layer heatmap visualizations (channel sum) for sampled validation images.",
)
parser.add_argument(
"--use-improved-head",
action="store_true",
help="Enable enhanced UltraTinyOD head (quality-aware obj, learnable WH scale, extra context, IoU/quality scoring).",
)
parser.add_argument(
"--use-iou-aware-head",
action="store_true",
help="UltraTinyOD head: task-aligned IoU-aware scoring (quality*cls) with split towers; keeps legacy path when off.",
)
parser.add_argument(
"--classes",
default="0",
help="Comma-separated list of target class ids to train on (e.g., '0,1,3').",
)
parser.add_argument("--activation", choices=["relu", "swish"], default="swish", help="Activation function to use.")
# CNN params
parser.add_argument("--cnn-width", type=int, default=32)
parser.add_argument("--use-skip", action="store_true", help="Enable skip connections in the CNN model.")
parser.add_argument("--utod-residual", action="store_true", help="Enable residual skips inside the UltraTinyOD backbone.")
parser.add_argument("--utod-head-ese", action="store_true", help="UltraTinyOD head: apply lightweight eSE on shared features.")
parser.add_argument(
"--utod-conv",
choices=["dw", "std"],
default="dw",
help="UltraTinyOD conv mode: dw=depthwise separable (default), std=standard conv (remove depthwise).",
)
parser.add_argument(
"--utod-sppf-scale",
choices=["none", "bn", "conv"],
default="none",
help="UltraTinyOD SPPF-min: per-branch scale matching before concat (none/bn/conv).",
)
parser.add_argument(
"--utod-context-rfb",
action="store_true",
help="UltraTinyOD head: add a receptive-field block (dilated + wide depthwise) before prediction layers.",
)
parser.add_argument(
"--utod-context-dilation",
type=int,
default=2,
help="Dilation used in UltraTinyOD receptive-field block (only when --utod-context-rfb).",
)
parser.add_argument(
"--utod-large-obj-branch",
action="store_true",
help="UltraTinyOD head: add a downsampled large-object refinement branch (no FPN).",
)
parser.add_argument(
"--utod-large-obj-depth",
type=int,
default=2,
help="Number of depthwise blocks in the large-object branch (only when --utod-large-obj-branch).",
)
parser.add_argument(
"--utod-large-obj-ch-scale",
type=float,
default=1.0,
help="Channel scale for the large-object branch (relative to head channels).",
)
parser.add_argument(
"--utod-quant-arch",
type=int,
choices=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11],
default=0,
help=(
"UltraTinyOD quantization-robust architecture mode: "
"0=off, 1=box stage2 residual gain, 2=box stage2 low-rank pw, "
"3=split box_out (xy/wh), 4=box activation clip (ReLU6), "
"5=gated large-object fusion, 6=(1+5), 7=(1+3), 8=(2+3), "
"9=box stage1+stage2 residual gain, 10=backbone stage1+stage2(+stage3/4) residualized, "
"11=(1+10)."
),
)
parser.add_argument(
"--backbone",
default=None,
choices=["microcspnet", "ultratinyresnet", "enhanced-shufflenet", "none", None],
help="Optional lightweight CNN backbone. Default: None (built-in tiny CNN).",
)
parser.add_argument("--backbone-channels", default=None, help="Comma-separated channels for ultratinyresnet (e.g., '16,24,32,48').")
parser.add_argument("--backbone-blocks", default=None, help="Comma-separated residual block counts per stage for ultratinyresnet (e.g., '1,1,2,1').")
parser.add_argument("--backbone-se", choices=["none", "se", "ese"], default="none", help="Apply SE/eSE on backbone output (custom backbones only).")
parser.add_argument("--backbone-skip", action="store_true", help="Add long skip fusion across custom backbone stages (ultratinyresnet).")
parser.add_argument("--backbone-skip-cat", action="store_true", help="Use concat+1x1 fusion for long skips (ultratinyresnet); implies --backbone-skip.")
parser.add_argument(
"--backbone-skip-shuffle-cat",
action="store_true",
help="Use stride+shuffle concat fusion for long skips (ultratinyresnet); implies --backbone-skip.",
)
parser.add_argument(
"--backbone-skip-s2d-cat",
action="store_true",
help="Use space-to-depth concat fusion for long skips (ultratinyresnet); implies --backbone-skip.",
)
parser.add_argument("--backbone-fpn", action="store_true", help="Enable a tiny FPN fusion inside custom backbones (ultratinyresnet).")
parser.add_argument("--backbone-out-stride", type=int, default=None, help="Override custom backbone output stride (e.g., 8 or 16).")
parser.add_argument("--use-anchor", action="store_true", help="Use anchor-based head for CNN (YOLO-style).")
parser.add_argument(
"--output-stride",
type=int,
default=None,
help="Final feature stride for CNN (4, 8, or 16). Defaults: CNN/Transformer=16, UltraTinyOD=8.",
)
parser.add_argument(
"--anchors",
default="",
help='Anchor sizes as normalized "w,h w,h ..." (e.g., "0.08,0.10 0.15,0.20 0.30,0.35").',
)
parser.add_argument("--auto-anchors", action="store_true", help="Compute anchors from training labels when using anchor head.")
parser.add_argument(
"--auto-anchors-alg",
choices=["kmeans", "logkmeans", "stratified", "stratified_large", "sml_fixed"],
default="kmeans",
help="Auto-anchors algorithm (kmeans/logkmeans/stratified/stratified_large/sml_fixed).",
)
parser.add_argument(
"--auto-anchors-bias",
type=float,
default=0.20,
help="Bias for stratified_large auto-anchors (larger favors larger boxes).",
)
parser.add_argument("--num-anchors", type=int, default=3, help="Number of anchors to use when auto-computing.")
parser.add_argument(
"--auto-anchors-plot",
action="store_true",
help="Save a width/height distribution plot used for auto-anchors.",
)
parser.add_argument(
"--auto-anchors-plot-path",
default=None,
help="Output path for the auto-anchors plot (default: runs/EXP/auto_anchors_wh.png).",
)
parser.add_argument("--iou-loss", choices=["iou", "giou", "ciou"], default="giou", help="IoU loss type for anchor head.")
parser.add_argument("--anchor-assigner", choices=["legacy", "simota"], default="legacy", help="Anchor assigner strategy.")
parser.add_argument(
"--anchor-cls-loss",
choices=["bce", "vfl", "ce"],
default="bce",
help="Classification loss for anchor head.",
)
parser.add_argument("--loss-weight-box", type=float, default=1.0, help="Loss weight for anchor box regression.")
parser.add_argument("--loss-weight-obj", type=float, default=1.0, help="Loss weight for anchor objectness.")
parser.add_argument("--loss-weight-cls", type=float, default=1.0, help="Loss weight for anchor classification.")
parser.add_argument("--loss-weight-quality", type=float, default=1.0, help="Loss weight for anchor quality head.")
parser.add_argument("--disable-cls", action="store_true", help="Disable cls branch entirely (classless anchor head).")
parser.add_argument(
"--obj-loss",
choices=["bce", "smoothl1"],
default="bce",
help="Objectness loss type for anchor head.",
)
parser.add_argument(
"--obj-target",
choices=["auto", "binary", "iou"],
default="auto",
help="Objectness target for anchor head (auto uses IoU when quality head is enabled).",
)
parser.add_argument(
"--multi-label-mode",
choices=["none", "single", "separate"],
default="none",
help="Multi-label mode for anchor heads: none, single (one head), or separate (attr head).",
)
parser.add_argument(
"--multi-label-det-classes",
default=None,
help="Comma-separated class ids for detection head when --multi-label-mode separate.",
)
parser.add_argument(
"--multi-label-attr-classes",
default=None,
help="Comma-separated class ids for attribute head when --multi-label-mode separate.",
)
parser.add_argument(
"--multi-label-attr-weight",
type=float,
default=1.0,
help="Loss weight for attribute head when --multi-label-mode separate.",
)
parser.add_argument("--simota-topk", type=int, default=10, help="Top-K IoUs for dynamic-k in SimOTA.")
parser.add_argument("--last-se", choices=["none", "se", "ese"], default="none", help="Apply SE/eSE only on the last CNN block.")
parser.add_argument("--use-batchnorm", action="store_true", help="Enable BatchNorm layers (default: off).")
parser.add_argument("--last-width-scale", type=float, default=1.0, help="Channel scale for last CNN block (e.g., 1.25).")
parser.add_argument("--quality-power", type=float, default=1.0, help="Exponent for quality score when using IoU-aware head scoring.")
parser.add_argument(
"--score-mode",
choices=["obj_quality_cls", "quality_cls", "obj_cls", "obj_quality", "quality", "obj"],
default=None,
help="Score composition mode for anchor head (overrides defaults when set).",
)
# Transformer params
parser.add_argument("--num-queries", type=int, default=10)
parser.add_argument("--d-model", type=int, default=64)
parser.add_argument("--heads", type=int, default=4)
parser.add_argument("--layers", type=int, default=3)
parser.add_argument("--dim-feedforward", type=int, default=128)
parser.add_argument("--use-fpn", action="store_true", help="Enable simple FPN for transformer backbone.")
return parser.parse_args()
def parse_img_size(arg: str):
if isinstance(arg, (tuple, list)):
if len(arg) != 2:
raise ValueError("img-size tuple/list must have length 2 (H, W).")
return int(arg[0]), int(arg[1])
s = str(arg).lower().replace(" ", "")
if "x" in s:
parts = s.split("x")
if len(parts) != 2:
raise ValueError("img-size must be HxW, e.g., 64x64.")
return int(parts[0]), int(parts[1])
val = int(float(s))
return val, val
def parse_classes(arg: str):
if arg is None:
return [0]
if isinstance(arg, (list, tuple)):
return [int(x) for x in arg]
parts = str(arg).replace(" ", "").split(",")
return [int(p) for p in parts if p != ""]
def parse_int_list(arg):
if arg is None:
return None
if isinstance(arg, (list, tuple)):
return [int(x) for x in arg]
s = str(arg).replace(" ", "")
if s == "":
return None
return [int(p) for p in s.split(",") if p != ""]
def parse_anchors_str(arg: str):
anchors = []
if not arg:
return anchors
for part in str(arg).split():
nums = part.split(",")
if len(nums) != 2:
continue
try:
w = float(nums[0])
h = float(nums[1])
except ValueError:
continue
anchors.append((w, h))
return anchors
def _wh_iou(boxes: np.ndarray, anchors: np.ndarray) -> np.ndarray:
"""IoU using only w/h (no center), boxes: N x 2, anchors: K x 2."""
inter = np.minimum(boxes[:, None, :], anchors[None, :, :]).prod(axis=2)
union = (boxes[:, 0] * boxes[:, 1])[:, None] + (anchors[:, 0] * anchors[:, 1])[None, :] - inter + 1e-9
return inter / union
def _pad_boxes(boxes: np.ndarray, k: int, rng: np.random.Generator) -> np.ndarray:
n = boxes.shape[0]
if n >= k:
return boxes
extra = boxes[rng.choice(n, k - n, replace=True)]
return np.concatenate([boxes, extra], axis=0)
def _kmeans_iou(boxes: np.ndarray, k: int, iters: int, rng: np.random.Generator) -> np.ndarray:
n = boxes.shape[0]
centers = boxes[rng.choice(n, k, replace=False)]
for _ in range(iters):
ious = _wh_iou(boxes, centers)
assignments = ious.argmax(axis=1)
new_centers = []
for ki in range(k):
mask = assignments == ki
if mask.sum() == 0:
new_centers.append(centers[ki])
else:
new_centers.append(boxes[mask].mean(axis=0))
new_centers = np.stack(new_centers, axis=0)
if np.allclose(new_centers, centers):
break
centers = new_centers
return centers
def _kmeans_euclid(data: np.ndarray, k: int, iters: int, rng: np.random.Generator) -> np.ndarray:
n = data.shape[0]
centers = data[rng.choice(n, k, replace=False)]
for _ in range(iters):
diff = data[:, None, :] - centers[None, :, :]
dist = (diff * diff).sum(axis=2)
assignments = dist.argmin(axis=1)
new_centers = []
for ki in range(k):
mask = assignments == ki
if mask.sum() == 0:
new_centers.append(centers[ki])
else:
new_centers.append(data[mask].mean(axis=0))
new_centers = np.stack(new_centers, axis=0)
if np.allclose(new_centers, centers):
break
centers = new_centers
return centers
def _stratified_by_area(boxes: np.ndarray, k: int) -> np.ndarray:
areas = boxes[:, 0] * boxes[:, 1]
order = np.argsort(areas)
boxes_sorted = boxes[order]
bins = np.array_split(boxes_sorted, k)
centers = []
for chunk in bins:
if chunk.size == 0:
centers.append(boxes_sorted[0])
else:
centers.append(np.median(chunk, axis=0))
return np.stack(centers, axis=0)
def _stratified_by_area_bias(boxes: np.ndarray, k: int, bias: float) -> np.ndarray:
areas = boxes[:, 0] * boxes[:, 1]
order = np.argsort(areas)
boxes_sorted = boxes[order]
n = boxes_sorted.shape[0]
if n == 0:
return np.zeros((k, 2), dtype=np.float32)
bias = float(bias)
if bias <= 0:
bias = 1.0
edges = [0]
for i in range(1, k):
q = (i / k) ** bias
idx = int(round(q * n))
idx = max(idx, edges[-1] + 1)
idx = min(idx, n - (k - i))
edges.append(idx)
edges.append(n)
centers = []
for i in range(k):
start, end = edges[i], edges[i + 1]
if end <= start:
chunk = boxes_sorted[start:start + 1]
else:
chunk = boxes_sorted[start:end]
centers.append(np.median(chunk, axis=0))
return np.stack(centers, axis=0)
def _split_sml_by_area(boxes: np.ndarray) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
areas = boxes[:, 0] * boxes[:, 1]
if areas.size == 0:
return boxes, boxes, boxes
q1, q2 = np.quantile(areas, [1.0 / 3.0, 2.0 / 3.0])
small = boxes[areas <= q1]
medium = boxes[(areas > q1) & (areas <= q2)]
large = boxes[areas > q2]
if small.size == 0:
small = boxes
if medium.size == 0:
medium = boxes
if large.size == 0:
large = boxes
return small, medium, large
def _sml_fixed_anchors(boxes: np.ndarray, k: int, iters: int, rng: np.random.Generator) -> np.ndarray:
if k <= 0:
return np.zeros((0, 2), dtype=np.float32)
small, medium, large = _split_sml_by_area(boxes)
fixed: List[np.ndarray] = []
if k == 1:
fixed.append(np.median(boxes, axis=0))
elif k == 2:
fixed.append(np.median(small, axis=0))
fixed.append(np.median(large, axis=0))
else:
fixed.append(np.median(small, axis=0))
fixed.append(np.median(medium, axis=0))
fixed.append(np.median(large, axis=0))
remaining = k - len(fixed)
if remaining > 0:
groups = [small, medium, large]
sizes = np.array([g.shape[0] for g in groups], dtype=np.float32)
if sizes.sum() <= 0:
sizes[:] = 1.0
raw = remaining * sizes / sizes.sum()
alloc = np.floor(raw).astype(int)
while alloc.sum() < remaining:
idx = int(np.argmax(raw - alloc))
alloc[idx] += 1
for group, n_extra in zip(groups, alloc):
if n_extra <= 0:
continue
if group.size == 0:
group = boxes
group = _pad_boxes(group, n_extra, rng)
extra = _kmeans_iou(group, n_extra, iters, rng)
for row in extra:
fixed.append(row)
centers = np.stack(fixed, axis=0)
centers = centers[np.argsort(centers.prod(axis=1))]
return centers
def auto_compute_anchors(
boxes: np.ndarray,
k: int = 3,
iters: int = 20,
alg: str = "kmeans",
bias: float = 0.20,
) -> np.ndarray:
"""Compute anchors from normalized (w,h) with selectable algorithm."""
if boxes.size == 0:
return np.zeros((k, 2), dtype=np.float32)
boxes = boxes[(boxes[:, 0] > 0) & (boxes[:, 1] > 0)]
if boxes.size == 0:
return np.zeros((k, 2), dtype=np.float32)
rng = np.random.default_rng(0)
boxes = _pad_boxes(boxes, k, rng)
alg = str(alg or "kmeans").lower()
if alg == "logkmeans":
eps = 1e-6
log_boxes = np.log(np.clip(boxes, eps, None))
centers = _kmeans_euclid(log_boxes, k, iters, rng)
centers = np.exp(centers)
elif alg in ("sml_fixed", "sml-fixed", "smlfixed"):
centers = _sml_fixed_anchors(boxes, k, iters, rng)
elif alg == "stratified":
centers = _stratified_by_area(boxes, k)
elif alg in ("stratified_large", "stratified-large", "stratifiedlarge"):
centers = _stratified_by_area_bias(boxes, k, bias=bias)
else:
centers = _kmeans_iou(boxes, k, iters, rng)
centers = centers[np.argsort(centers.prod(axis=1))] # sort by area
return centers.astype(np.float32, copy=False)
def load_aug_config(path: str):
if not path:
return None
with open(path, "r") as f:
return yaml.safe_load(f)
def _find_horizontal_flip_cfg(augment_cfg: Dict):
if not isinstance(augment_cfg, dict):
return None
hf_cfg = augment_cfg.get("HorizontalFlip")
if hf_cfg is None:
da_cfg = augment_cfg.get("data_augment")
if isinstance(da_cfg, dict):
hf_cfg = da_cfg.get("HorizontalFlip")
return hf_cfg
def resolve_class_swap_map(augment_cfg: Dict, class_ids):
raw_map: Dict[int, int] = {}
internal_map: Dict[int, int] = {}
if not isinstance(class_ids, (list, tuple)):
return raw_map, internal_map
hf_cfg = _find_horizontal_flip_cfg(augment_cfg)
if isinstance(hf_cfg, dict):
raw_cfg = hf_cfg.get("class_swap_map")
if isinstance(raw_cfg, dict):
for k, v in raw_cfg.items():
try:
k_int = int(k)
v_int = int(v)
except (ValueError, TypeError):
continue
raw_map[k_int] = v_int
if raw_map:
class_to_idx = {int(cid): i for i, cid in enumerate(class_ids)}
for k, v in raw_map.items():
if k in class_to_idx and v in class_to_idx:
internal_map[class_to_idx[k]] = class_to_idx[v]
return raw_map, internal_map
def log_scalars(writer: SummaryWriter, prefix: str, values: Dict[str, float], ordered_keys, step: int):
"""Log scalars with forced ordering by prefixing numeric indices."""
logged = set()
idx = 0
for k in ordered_keys:
if k in values:
writer.add_scalar(f"{prefix}/{idx:02d}_{k}", values[k], step)
logged.add(k)
idx += 1
for k in sorted(values.keys()):
if k not in logged:
writer.add_scalar(f"{prefix}/{idx:02d}_{k}", values[k], step)
idx += 1
def _parse_best_filename(path: str):
"""Parse best checkpoint filename to extract (arch, epoch, map)."""
base = os.path.splitext(os.path.basename(path))[0] # without .pt
if not base.startswith("best_") or "_map_" not in base:
return None
try:
prefix, map_part = base.split("_map_", 1) # e.g., best_cnn_0001 , 0.12345
parts = prefix.split("_")
if len(parts) < 3:
return None
arch = parts[1]
epoch = int(parts[2])
map_val = float(map_part)
return arch, epoch, map_val
except ValueError:
return None
def _parse_last_filename(path: str):
base = os.path.splitext(os.path.basename(path))[0]
if not base.startswith("last_"):
return None
try:
epoch = int(base.split("_")[1])
return epoch
except (IndexError, ValueError):
return None
def _prune_best(run_dir: str, arch_tag: str, keep: int = 10):
pattern = os.path.join(run_dir, f"best_{arch_tag}_*_map_*.pt")
entries = []
for p in glob.glob(pattern):
try:
mtime = os.path.getmtime(p)
except OSError:
continue
entries.append((mtime, p))
entries.sort(key=lambda x: x[0], reverse=True) # keep most recent
for _, path in entries[keep:]:
try:
os.remove(path)
except OSError:
pass
def _prune_last(run_dir: str, keep: int = 10):
pattern = os.path.join(run_dir, "last_*.pt")
entries = []
for p in glob.glob(pattern):
epoch = _parse_last_filename(p)
if epoch is not None:
entries.append((epoch, p))
entries.sort(key=lambda x: x[0], reverse=True)
for _, path in entries[keep:]:
try:
os.remove(path)
except OSError:
pass
def _remove_dir(path: str):
try:
for root, _, files in os.walk(path, topdown=False):
for f in files:
os.remove(os.path.join(root, f))
os.rmdir(root)
except OSError:
pass
def _collect_best_epochs(run_dir: str, arch_tag: str, keep: int = 10) -> Set[int]:
pattern = os.path.join(run_dir, f"best_{arch_tag}_*_map_*.pt")
epochs = []
for p in glob.glob(pattern):
parsed = _parse_best_filename(p)
if parsed is None:
continue
_, epoch, _ = parsed
epochs.append(epoch)
epochs = sorted(set(epochs), reverse=True)
return set(epochs[:keep])
def _prune_epoch_dirs(run_dir: str, keep: int = 10, best_epochs: Optional[Set[int]] = None):
best_dirs = []
other_dirs = []
for name in os.listdir(run_dir):
full = os.path.join(run_dir, name)
if not (os.path.isdir(full) and name.isdigit()):
continue
try:
epoch = int(name)
except ValueError:
continue
if best_epochs is not None and epoch in best_epochs:
best_dirs.append((epoch, full))
else:
other_dirs.append((epoch, full))
other_dirs.sort(key=lambda x: x[0], reverse=True) # newest epoch first
for _, path in other_dirs[keep:]:
try:
for root, _, files in os.walk(path, topdown=False):
for f in files:
os.remove(os.path.join(root, f))
os.rmdir(root)
except OSError:
pass
def _default_split_list_paths(image_dir: str) -> tuple[str, str]:
base_dir = os.path.dirname(os.path.normpath(image_dir))
return os.path.join(base_dir, "train.txt"), os.path.join(base_dir, "val.txt")
def _write_split_list(path: str, items: List[Tuple[str, str]]) -> None:
list_dir = os.path.dirname(path)
if list_dir:
os.makedirs(list_dir, exist_ok=True)
with open(path, "w") as f:
for img_path, _ in items:
f.write(f"{img_path}\n")
def make_datasets(args, class_ids, aug_cfg, val_aug_cfg, resize_mode: str):
img_h, img_w = parse_img_size(args.img_size)
if args.train_list or args.val_list:
if not (args.train_list and args.val_list):
raise ValueError("--train-list and --val-list must be provided together.")
image_dir = args.image_dir or ""
train_ds = YoloDataset(
image_dir=image_dir,
list_path=args.train_list,
split="all",
val_split=0.0,
seed=args.seed,
img_size=(img_h, img_w),
resize_mode=resize_mode,
augment=True,
class_ids=class_ids,
augment_cfg=aug_cfg,
)
val_ds = YoloDataset(
image_dir=image_dir,
list_path=args.val_list,
split="all",
val_split=0.0,
seed=args.seed,
img_size=(img_h, img_w),
resize_mode=resize_mode,
augment=bool(val_aug_cfg),
class_ids=class_ids,
augment_cfg=val_aug_cfg or aug_cfg,
)
# When running val-only, optionally cap validation set size for quick checks.
if getattr(args, "val_only", False) and getattr(args, "val_count", None):
val_cap = max(0, int(args.val_count))
if val_cap > 0:
val_ds.items = val_ds.items[:val_cap]
if not val_ds.items:
raise ValueError("val-count reduced validation set to zero samples.")
print(f"val-only: restricting validation set to {len(val_ds.items)} samples (val-count={val_cap}).")
return train_ds, val_ds
if not args.image_dir:
raise ValueError("--image-dir is required when not using --train-list/--val-list.")
base = YoloDataset(
image_dir=args.image_dir,
list_path=None,
split="all",