TLMHoang commited on
Commit
a45cf0a
·
verified ·
1 Parent(s): 78b8903

Upload folder using huggingface_hub

Browse files
Files changed (21) hide show
  1. mmdet_code/__pycache__/train_dala.cpython-313.pyc +0 -0
  2. mmdet_code/mmdetection/mmdet/engine/hooks/__init__.py +2 -1
  3. mmdet_code/mmdetection/mmdet/engine/hooks/__pycache__/__init__.cpython-313.pyc +0 -0
  4. mmdet_code/mmdetection/mmdet/engine/hooks/__pycache__/ftsc_progress_hook.cpython-313.pyc +0 -0
  5. mmdet_code/mmdetection/mmdet/engine/hooks/ftsc_progress_hook.py +49 -0
  6. mmdet_code/mmdetection/mmdet/models/dense_heads/__pycache__/dala_heads.cpython-313.pyc +0 -0
  7. mmdet_code/mmdetection/mmdet/models/dense_heads/dala_heads.py +38 -3
  8. mmdet_code/mmdetection/mmdet/models/task_modules/__pycache__/ftsc_calibrator.cpython-313.pyc +0 -0
  9. mmdet_code/mmdetection/mmdet/models/task_modules/ftsc_calibrator.py +136 -18
  10. mmdet_code/mmdetection/projects/EfficientDet/README.md +14 -0
  11. mmdet_code/mmdetection/projects/EfficientDet/configs/__pycache__/efficientdet_effb0_bifpn_dala_ftsc_f4_soft_8xb16-crop512-100e_levir.cpython-313.pyc +0 -0
  12. mmdet_code/mmdetection/projects/EfficientDet/configs/__pycache__/efficientdet_effb0_bifpn_dala_ftsc_f5_learn_8xb16-crop512-100e_levir.cpython-313.pyc +0 -0
  13. mmdet_code/mmdetection/projects/EfficientDet/configs/efficientdet_effb0_bifpn_dala_ftsc_f4_soft_8xb16-crop512-100e_levir.py +28 -0
  14. mmdet_code/mmdetection/projects/EfficientDet/configs/efficientdet_effb0_bifpn_dala_ftsc_f5_learn_8xb16-crop512-100e_levir.py +17 -0
  15. mmdet_code/mmdetection/projects/EfficientDet/tests/__pycache__/test_dala_efficientdet_head.cpython-313.pyc +0 -0
  16. mmdet_code/mmdetection/projects/EfficientDet/tests/test_dala_efficientdet_head.py +43 -0
  17. mmdet_code/mmdetection/tests/test_engine/test_hooks/__pycache__/test_ftsc_progress_hook.cpython-313.pyc +0 -0
  18. mmdet_code/mmdetection/tests/test_engine/test_hooks/test_ftsc_progress_hook.py +26 -0
  19. mmdet_code/mmdetection/tests/test_models/test_task_modules/__pycache__/test_ftsc_calibrator.cpython-313.pyc +0 -0
  20. mmdet_code/mmdetection/tests/test_models/test_task_modules/test_ftsc_calibrator.py +64 -0
  21. mmdet_code/train_dala.py +16 -6
mmdet_code/__pycache__/train_dala.cpython-313.pyc CHANGED
Binary files a/mmdet_code/__pycache__/train_dala.cpython-313.pyc and b/mmdet_code/__pycache__/train_dala.cpython-313.pyc differ
 
mmdet_code/mmdetection/mmdet/engine/hooks/__init__.py CHANGED
@@ -1,5 +1,6 @@
1
  # Copyright (c) OpenMMLab. All rights reserved.
2
  from .checkloss_hook import CheckInvalidLossHook
 
3
  from .mean_teacher_hook import MeanTeacherHook
4
  from .memory_profiler_hook import MemoryProfilerHook
5
  from .num_class_check_hook import NumClassCheckHook
@@ -17,5 +18,5 @@ __all__ = [
17
  'SetEpochInfoHook', 'MemoryProfilerHook', 'DetVisualizationHook',
18
  'NumClassCheckHook', 'MeanTeacherHook', 'trigger_visualization_hook',
19
  'PipelineSwitchHook', 'TrackVisualizationHook',
20
- 'GroundingVisualizationHook'
21
  ]
 
1
  # Copyright (c) OpenMMLab. All rights reserved.
2
  from .checkloss_hook import CheckInvalidLossHook
3
+ from .ftsc_progress_hook import FtscProgressHook
4
  from .mean_teacher_hook import MeanTeacherHook
5
  from .memory_profiler_hook import MemoryProfilerHook
6
  from .num_class_check_hook import NumClassCheckHook
 
18
  'SetEpochInfoHook', 'MemoryProfilerHook', 'DetVisualizationHook',
19
  'NumClassCheckHook', 'MeanTeacherHook', 'trigger_visualization_hook',
20
  'PipelineSwitchHook', 'TrackVisualizationHook',
21
+ 'GroundingVisualizationHook', 'FtscProgressHook'
22
  ]
mmdet_code/mmdetection/mmdet/engine/hooks/__pycache__/__init__.cpython-313.pyc ADDED
Binary file (992 Bytes). View file
 
mmdet_code/mmdetection/mmdet/engine/hooks/__pycache__/ftsc_progress_hook.cpython-313.pyc ADDED
Binary file (2.66 kB). View file
 
mmdet_code/mmdetection/mmdet/engine/hooks/ftsc_progress_hook.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) OpenMMLab. All rights reserved.
2
+ """Training-progress hook for FTSC residual warmup."""
3
+
4
+ from mmengine.hooks import Hook
5
+ from mmengine.model.wrappers import is_model_wrapper
6
+
7
+ from mmdet.registry import HOOKS
8
+
9
+
10
+ @HOOKS.register_module()
11
+ class FtscProgressHook(Hook):
12
+ """Propagate the current epoch to every FTSC calibrator in the model.
13
+
14
+ The hook uses a marker attribute instead of importing the calibrator class,
15
+ which keeps engine registration independent from model import order.
16
+
17
+ Args:
18
+ strict: Raise when the configured model contains no FTSC calibrator.
19
+ """
20
+
21
+ priority = 'VERY_HIGH'
22
+
23
+ def __init__(self, strict: bool = True) -> None:
24
+ self.strict = strict
25
+
26
+ @staticmethod
27
+ def _unwrap_model(model):
28
+ return model.module if is_model_wrapper(model) else model
29
+
30
+ def _set_epoch(self, runner) -> int:
31
+ model = self._unwrap_model(runner.model)
32
+ updated = 0
33
+ for module in model.modules():
34
+ if getattr(module, 'is_ftsc_calibrator', False):
35
+ module.set_epoch(runner.epoch)
36
+ updated += 1
37
+ if self.strict and updated == 0:
38
+ raise RuntimeError(
39
+ 'FtscProgressHook found no FpnTinySupervisionCalibrator')
40
+ return updated
41
+
42
+ def before_train(self, runner) -> None:
43
+ self._set_epoch(runner)
44
+
45
+ def before_train_epoch(self, runner) -> None:
46
+ self._set_epoch(runner)
47
+
48
+
49
+ __all__ = ['FtscProgressHook']
mmdet_code/mmdetection/mmdet/models/dense_heads/__pycache__/dala_heads.cpython-313.pyc CHANGED
Binary files a/mmdet_code/mmdetection/mmdet/models/dense_heads/__pycache__/dala_heads.cpython-313.pyc and b/mmdet_code/mmdetection/mmdet/models/dense_heads/__pycache__/dala_heads.cpython-313.pyc differ
 
mmdet_code/mmdetection/mmdet/models/dense_heads/dala_heads.py CHANGED
@@ -39,6 +39,14 @@ class DalaAnchorTargetMixin:
39
  ftsc_weight_min: float = 0.25,
40
  ftsc_weight_max: float = 2.0,
41
  ftsc_normalize: bool = True,
 
 
 
 
 
 
 
 
42
  **kwargs) -> None:
43
  self.use_dwl = use_dwl
44
  self.use_ftsc = use_ftsc
@@ -58,6 +66,18 @@ class DalaAnchorTargetMixin:
58
  self.ftsc_weight_min = ftsc_weight_min
59
  self.ftsc_weight_max = ftsc_weight_max
60
  self.ftsc_normalize = ftsc_normalize
 
 
 
 
 
 
 
 
 
 
 
 
61
  self.ftsc_calibrator = FpnTinySupervisionCalibrator(
62
  mode=ftsc_mode,
63
  lambda_level=ftsc_lambda_level,
@@ -66,17 +86,32 @@ class DalaAnchorTargetMixin:
66
  weight_min=ftsc_weight_min,
67
  weight_max=ftsc_weight_max,
68
  normalize=ftsc_normalize,
 
 
 
 
 
 
 
 
69
  )
70
- super().__init__(**kwargs)
71
 
72
- @torch.no_grad()
73
  def _ftsc_positive_weights(self, anchors: Tensor, level_ids: Tensor,
74
  gt_bboxes: Tensor, pos_inds: Tensor,
75
  pos_assigned_gt_inds: Tensor) -> Tensor:
76
- """Delegate FTSC-v1 computation to the standalone calibrator."""
77
  return self.ftsc_calibrator(
78
  anchors, level_ids, gt_bboxes, pos_inds, pos_assigned_gt_inds)
79
 
 
 
 
 
 
 
 
 
 
80
  def get_targets(self,
81
  anchor_list: List[List[Tensor]],
82
  valid_flag_list: List[List[Tensor]],
 
39
  ftsc_weight_min: float = 0.25,
40
  ftsc_weight_max: float = 2.0,
41
  ftsc_normalize: bool = True,
42
+ ftsc_residual_blend: bool = False,
43
+ ftsc_warmup_epochs: int = 0,
44
+ ftsc_ramp_epochs: int = 0,
45
+ ftsc_learnable_strength: bool = False,
46
+ ftsc_strength_max: float = 2.0,
47
+ ftsc_strength_init_level: float = 1.0,
48
+ ftsc_strength_init_quality: float = 1.0,
49
+ ftsc_strength_reg_weight: float = 0.0,
50
  **kwargs) -> None:
51
  self.use_dwl = use_dwl
52
  self.use_ftsc = use_ftsc
 
66
  self.ftsc_weight_min = ftsc_weight_min
67
  self.ftsc_weight_max = ftsc_weight_max
68
  self.ftsc_normalize = ftsc_normalize
69
+ self.ftsc_residual_blend = ftsc_residual_blend
70
+ self.ftsc_warmup_epochs = ftsc_warmup_epochs
71
+ self.ftsc_ramp_epochs = ftsc_ramp_epochs
72
+ self.ftsc_learnable_strength = ftsc_learnable_strength
73
+ self.ftsc_strength_max = ftsc_strength_max
74
+ self.ftsc_strength_init_level = ftsc_strength_init_level
75
+ self.ftsc_strength_init_quality = ftsc_strength_init_quality
76
+ self.ftsc_strength_reg_weight = ftsc_strength_reg_weight
77
+ # ``FpnTinySupervisionCalibrator`` becomes an ``nn.Module`` for the
78
+ # learnable variant, so the base head must initialize ``nn.Module``
79
+ # before the calibrator can be registered as a child module.
80
+ super().__init__(**kwargs)
81
  self.ftsc_calibrator = FpnTinySupervisionCalibrator(
82
  mode=ftsc_mode,
83
  lambda_level=ftsc_lambda_level,
 
86
  weight_min=ftsc_weight_min,
87
  weight_max=ftsc_weight_max,
88
  normalize=ftsc_normalize,
89
+ residual_blend=ftsc_residual_blend,
90
+ warmup_epochs=ftsc_warmup_epochs,
91
+ ramp_epochs=ftsc_ramp_epochs,
92
+ learnable_strength=ftsc_learnable_strength,
93
+ strength_max=ftsc_strength_max,
94
+ strength_init_level=ftsc_strength_init_level,
95
+ strength_init_quality=ftsc_strength_init_quality,
96
+ strength_reg_weight=ftsc_strength_reg_weight,
97
  )
 
98
 
 
99
  def _ftsc_positive_weights(self, anchors: Tensor, level_ids: Tensor,
100
  gt_bboxes: Tensor, pos_inds: Tensor,
101
  pos_assigned_gt_inds: Tensor) -> Tensor:
102
+ """Delegate FTSC computation while retaining learnable-strength grad."""
103
  return self.ftsc_calibrator(
104
  anchors, level_ids, gt_bboxes, pos_inds, pos_assigned_gt_inds)
105
 
106
+ def loss_by_feat(self, *args, **kwargs) -> dict:
107
+ """Add the optional learned-strength prior to the base head losses."""
108
+ losses = super().loss_by_feat(*args, **kwargs)
109
+ if (self.use_ftsc and self.ftsc_learnable_strength and
110
+ self.ftsc_strength_reg_weight > 0):
111
+ losses['loss_ftsc_strength'] = (
112
+ self.ftsc_calibrator.strength_regularization_loss())
113
+ return losses
114
+
115
  def get_targets(self,
116
  anchor_list: List[List[Tensor]],
117
  valid_flag_list: List[List[Tensor]],
mmdet_code/mmdetection/mmdet/models/task_modules/__pycache__/ftsc_calibrator.cpython-313.pyc CHANGED
Binary files a/mmdet_code/mmdetection/mmdet/models/task_modules/__pycache__/ftsc_calibrator.cpython-313.pyc and b/mmdet_code/mmdetection/mmdet/models/task_modules/__pycache__/ftsc_calibrator.cpython-313.pyc differ
 
mmdet_code/mmdetection/mmdet/models/task_modules/ftsc_calibrator.py CHANGED
@@ -10,6 +10,7 @@ box-regression loss.
10
  from __future__ import annotations
11
 
12
  import torch
 
13
  from torch import Tensor
14
 
15
 
@@ -33,8 +34,8 @@ def simd_quality(priors: Tensor,
33
  return torch.exp(-(location + shape)).clamp_min(eps)
34
 
35
 
36
- class FpnTinySupervisionCalibrator:
37
- """Compute FTSC-v1 weights for positives after hard assignment.
38
 
39
  Args:
40
  mode: ``level``, ``quality`` or ``level_quality``.
@@ -44,8 +45,20 @@ class FpnTinySupervisionCalibrator:
44
  weight_min: Lower clamp for raw positive weights.
45
  weight_max: Upper clamp for raw positive weights.
46
  normalize: If true, normalize positive weights to mean one.
 
 
 
 
 
 
 
 
 
 
47
  """
48
 
 
 
49
  def __init__(self,
50
  mode: str = 'level_quality',
51
  lambda_level: float = 1.0,
@@ -53,16 +66,39 @@ class FpnTinySupervisionCalibrator:
53
  beta_quality: float = 1.0,
54
  weight_min: float = 0.25,
55
  weight_max: float = 2.0,
56
- normalize: bool = True) -> None:
 
 
 
 
 
 
 
 
 
57
  if mode not in {'level', 'quality', 'level_quality'}:
58
  raise ValueError(
59
  'FTSC mode must be one of level, quality, or level_quality')
60
  if lambda_level < 0:
61
  raise ValueError('lambda_level must be non-negative')
 
 
62
  if weight_min <= 0 or weight_max <= 0:
63
  raise ValueError('FTSC weight clamps must be positive')
64
  if weight_min > weight_max:
65
  raise ValueError('weight_min must not exceed weight_max')
 
 
 
 
 
 
 
 
 
 
 
 
66
  self.mode = mode
67
  self.lambda_level = lambda_level
68
  self.alpha_level = alpha_level
@@ -70,10 +106,82 @@ class FpnTinySupervisionCalibrator:
70
  self.weight_min = weight_min
71
  self.weight_max = weight_max
72
  self.normalize = normalize
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73
 
74
- @torch.no_grad()
75
- def __call__(self, anchors: Tensor, level_ids: Tensor, gt_bboxes: Tensor,
76
- pos_inds: Tensor, pos_assigned_gt_inds: Tensor) -> Tensor:
77
  """Return one FTSC weight per positive index."""
78
  if len(pos_inds) == 0:
79
  return anchors.new_zeros((0, ))
@@ -87,22 +195,32 @@ class FpnTinySupervisionCalibrator:
87
  weights = anchors.new_ones((len(pos_inds), ))
88
 
89
  if 'level' in self.mode:
90
- weights = weights * self._level_weights(
91
- anchors, level_ids.to(device=anchors.device,
92
- dtype=torch.long), pos_levels,
93
- pos_gt_bboxes)
 
 
 
94
 
95
  if 'quality' in self.mode:
96
- weights = weights * self._quality_weights(
97
- pos_anchors, gt_bboxes, pos_assigned_gt_inds)
 
 
 
98
 
99
  weights = weights.clamp(self.weight_min, self.weight_max)
100
  if self.normalize and weights.numel() > 0:
101
  weights = weights / weights.mean().clamp_min(1e-7)
 
 
 
102
  return weights
103
 
104
- def _level_weights(self, anchors: Tensor, level_ids: Tensor,
105
- pos_levels: Tensor, pos_gt_bboxes: Tensor) -> Tensor:
 
106
  prior_wh = (anchors[:, 2:] - anchors[:, :2]).clamp_min(1e-7)
107
  prior_scale = torch.sqrt(prior_wh.prod(dim=-1).clamp_min(1e-7))
108
  num_levels = int(level_ids.max().item()) + 1
@@ -119,10 +237,10 @@ class FpnTinySupervisionCalibrator:
119
  octave_gap = torch.abs(
120
  torch.log2(gt_scale / canonical[pos_levels].clamp_min(1e-7)))
121
  level_weight = torch.exp(-self.lambda_level * octave_gap)
122
- return level_weight.clamp_min(1e-7).pow(self.alpha_level)
123
 
124
- def _quality_weights(self, pos_anchors: Tensor, gt_bboxes: Tensor,
125
- pos_assigned_gt_inds: Tensor) -> Tensor:
126
  quality_matrix = simd_quality(pos_anchors, gt_bboxes)
127
  pos_quality = quality_matrix[
128
  torch.arange(pos_anchors.shape[0], device=pos_anchors.device),
@@ -137,7 +255,7 @@ class FpnTinySupervisionCalibrator:
137
  relative_quality = (
138
  pos_quality /
139
  gt_quality_mean[pos_assigned_gt_inds].clamp_min(1e-7))
140
- return relative_quality.clamp_min(1e-7).pow(self.beta_quality)
141
 
142
 
143
  __all__ = ['FpnTinySupervisionCalibrator', 'simd_quality']
 
10
  from __future__ import annotations
11
 
12
  import torch
13
+ import torch.nn as nn
14
  from torch import Tensor
15
 
16
 
 
34
  return torch.exp(-(location + shape)).clamp_min(eps)
35
 
36
 
37
+ class FpnTinySupervisionCalibrator(nn.Module):
38
+ """Compute FTSC weights for positives after hard assignment.
39
 
40
  Args:
41
  mode: ``level``, ``quality`` or ``level_quality``.
 
45
  weight_min: Lower clamp for raw positive weights.
46
  weight_max: Upper clamp for raw positive weights.
47
  normalize: If true, normalize positive weights to mean one.
48
+ residual_blend: Blend calibrated weights around one instead of applying
49
+ the full gate immediately.
50
+ warmup_epochs: Number of initial epochs with zero FTSC strength.
51
+ ramp_epochs: Number of epochs used to linearly ramp FTSC strength from
52
+ zero to one after warmup.
53
+ learnable_strength: Learn bounded level/quality exponents.
54
+ strength_max: Upper bound for each learned exponent.
55
+ strength_init_level: Initial learned level exponent.
56
+ strength_init_quality: Initial learned quality exponent.
57
+ strength_reg_weight: L2 regularization weight around initial strengths.
58
  """
59
 
60
+ is_ftsc_calibrator = True
61
+
62
  def __init__(self,
63
  mode: str = 'level_quality',
64
  lambda_level: float = 1.0,
 
66
  beta_quality: float = 1.0,
67
  weight_min: float = 0.25,
68
  weight_max: float = 2.0,
69
+ normalize: bool = True,
70
+ residual_blend: bool = False,
71
+ warmup_epochs: int = 0,
72
+ ramp_epochs: int = 0,
73
+ learnable_strength: bool = False,
74
+ strength_max: float = 2.0,
75
+ strength_init_level: float = 1.0,
76
+ strength_init_quality: float = 1.0,
77
+ strength_reg_weight: float = 0.0) -> None:
78
+ super().__init__()
79
  if mode not in {'level', 'quality', 'level_quality'}:
80
  raise ValueError(
81
  'FTSC mode must be one of level, quality, or level_quality')
82
  if lambda_level < 0:
83
  raise ValueError('lambda_level must be non-negative')
84
+ if alpha_level < 0 or beta_quality < 0:
85
+ raise ValueError('FTSC fixed exponents must be non-negative')
86
  if weight_min <= 0 or weight_max <= 0:
87
  raise ValueError('FTSC weight clamps must be positive')
88
  if weight_min > weight_max:
89
  raise ValueError('weight_min must not exceed weight_max')
90
+ if warmup_epochs < 0 or ramp_epochs < 0:
91
+ raise ValueError('FTSC warmup/ramp epochs must be non-negative')
92
+ if strength_max <= 0:
93
+ raise ValueError('FTSC strength_max must be positive')
94
+ if not 0 <= strength_init_level <= strength_max:
95
+ raise ValueError(
96
+ 'strength_init_level must be in [0, strength_max]')
97
+ if not 0 <= strength_init_quality <= strength_max:
98
+ raise ValueError(
99
+ 'strength_init_quality must be in [0, strength_max]')
100
+ if strength_reg_weight < 0:
101
+ raise ValueError('strength_reg_weight must be non-negative')
102
  self.mode = mode
103
  self.lambda_level = lambda_level
104
  self.alpha_level = alpha_level
 
106
  self.weight_min = weight_min
107
  self.weight_max = weight_max
108
  self.normalize = normalize
109
+ self.residual_blend = residual_blend
110
+ self.warmup_epochs = int(warmup_epochs)
111
+ self.ramp_epochs = int(ramp_epochs)
112
+ self.learnable_strength = learnable_strength
113
+ self.strength_max = float(strength_max)
114
+ self.strength_init_level = float(strength_init_level)
115
+ self.strength_init_quality = float(strength_init_quality)
116
+ self.strength_reg_weight = float(strength_reg_weight)
117
+ self._current_epoch = 0
118
+
119
+ if learnable_strength and 'level' in mode:
120
+ self.level_strength_logit = nn.Parameter(
121
+ self._bounded_value_to_logit(strength_init_level,
122
+ strength_max))
123
+ else:
124
+ self.register_parameter('level_strength_logit', None)
125
+ if learnable_strength and 'quality' in mode:
126
+ self.quality_strength_logit = nn.Parameter(
127
+ self._bounded_value_to_logit(strength_init_quality,
128
+ strength_max))
129
+ else:
130
+ self.register_parameter('quality_strength_logit', None)
131
+
132
+ @staticmethod
133
+ def _bounded_value_to_logit(value: float, maximum: float) -> Tensor:
134
+ ratio = torch.tensor(value / maximum, dtype=torch.float32)
135
+ ratio = ratio.clamp(1e-6, 1 - 1e-6)
136
+ return torch.logit(ratio)
137
+
138
+ def set_epoch(self, epoch: int) -> None:
139
+ """Set the zero-based training epoch used by residual warmup."""
140
+ if epoch < 0:
141
+ raise ValueError('FTSC epoch must be non-negative')
142
+ self._current_epoch = int(epoch)
143
+
144
+ def blend_strength(self) -> float:
145
+ """Return the current residual-blend coefficient in ``[0, 1]``."""
146
+ if not self.residual_blend:
147
+ return 1.0
148
+ if self._current_epoch < self.warmup_epochs:
149
+ return 0.0
150
+ if self.ramp_epochs == 0:
151
+ return 1.0
152
+ ramp_step = self._current_epoch - self.warmup_epochs + 1
153
+ return min(max(ramp_step / self.ramp_epochs, 0.0), 1.0)
154
+
155
+ def _level_exponent(self, reference: Tensor) -> Tensor:
156
+ if self.level_strength_logit is None:
157
+ return reference.new_tensor(self.alpha_level)
158
+ return (self.strength_max *
159
+ self.level_strength_logit.sigmoid()).to(reference)
160
+
161
+ def _quality_exponent(self, reference: Tensor) -> Tensor:
162
+ if self.quality_strength_logit is None:
163
+ return reference.new_tensor(self.beta_quality)
164
+ return (self.strength_max *
165
+ self.quality_strength_logit.sigmoid()).to(reference)
166
+
167
+ def strength_regularization_loss(self) -> Tensor:
168
+ """Regularize learned exponents around their configured initialization."""
169
+ losses = []
170
+ if self.level_strength_logit is not None:
171
+ level_strength = (
172
+ self.strength_max * self.level_strength_logit.sigmoid())
173
+ losses.append((level_strength - self.strength_init_level).square())
174
+ if self.quality_strength_logit is not None:
175
+ quality_strength = (
176
+ self.strength_max * self.quality_strength_logit.sigmoid())
177
+ losses.append(
178
+ (quality_strength - self.strength_init_quality).square())
179
+ if not losses:
180
+ return torch.zeros(())
181
+ return torch.stack(losses).mean() * self.strength_reg_weight
182
 
183
+ def forward(self, anchors: Tensor, level_ids: Tensor, gt_bboxes: Tensor,
184
+ pos_inds: Tensor, pos_assigned_gt_inds: Tensor) -> Tensor:
 
185
  """Return one FTSC weight per positive index."""
186
  if len(pos_inds) == 0:
187
  return anchors.new_zeros((0, ))
 
195
  weights = anchors.new_ones((len(pos_inds), ))
196
 
197
  if 'level' in self.mode:
198
+ with torch.no_grad():
199
+ level_compatibility = self._level_compatibility(
200
+ anchors, level_ids.to(device=anchors.device,
201
+ dtype=torch.long), pos_levels,
202
+ pos_gt_bboxes)
203
+ weights = weights * level_compatibility.pow(
204
+ self._level_exponent(level_compatibility))
205
 
206
  if 'quality' in self.mode:
207
+ with torch.no_grad():
208
+ relative_quality = self._relative_quality(
209
+ pos_anchors, gt_bboxes, pos_assigned_gt_inds)
210
+ weights = weights * relative_quality.pow(
211
+ self._quality_exponent(relative_quality))
212
 
213
  weights = weights.clamp(self.weight_min, self.weight_max)
214
  if self.normalize and weights.numel() > 0:
215
  weights = weights / weights.mean().clamp_min(1e-7)
216
+ if self.residual_blend:
217
+ strength = self.blend_strength()
218
+ weights = 1 + strength * (weights - 1)
219
  return weights
220
 
221
+ def _level_compatibility(self, anchors: Tensor, level_ids: Tensor,
222
+ pos_levels: Tensor,
223
+ pos_gt_bboxes: Tensor) -> Tensor:
224
  prior_wh = (anchors[:, 2:] - anchors[:, :2]).clamp_min(1e-7)
225
  prior_scale = torch.sqrt(prior_wh.prod(dim=-1).clamp_min(1e-7))
226
  num_levels = int(level_ids.max().item()) + 1
 
237
  octave_gap = torch.abs(
238
  torch.log2(gt_scale / canonical[pos_levels].clamp_min(1e-7)))
239
  level_weight = torch.exp(-self.lambda_level * octave_gap)
240
+ return level_weight.clamp_min(1e-7)
241
 
242
+ def _relative_quality(self, pos_anchors: Tensor, gt_bboxes: Tensor,
243
+ pos_assigned_gt_inds: Tensor) -> Tensor:
244
  quality_matrix = simd_quality(pos_anchors, gt_bboxes)
245
  pos_quality = quality_matrix[
246
  torch.arange(pos_anchors.shape[0], device=pos_anchors.device),
 
255
  relative_quality = (
256
  pos_quality /
257
  gt_quality_mean[pos_assigned_gt_inds].clamp_min(1e-7))
258
+ return relative_quality.clamp_min(1e-7)
259
 
260
 
261
  __all__ = ['FpnTinySupervisionCalibrator', 'simd_quality']
mmdet_code/mmdetection/projects/EfficientDet/README.md CHANGED
@@ -86,6 +86,20 @@ S3 requires per-prior FPN level IDs. `DalaAnchorTargetMixin` preserves those
86
  IDs before MMDetection flattens multi-level anchors. The original
87
  `dala_efficientdet_d0` remains the S0 control.
88
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89
  The repository runner accepts all three variants together:
90
 
91
  ```bash
 
86
  IDs before MMDetection flattens multi-level anchors. The original
87
  `dala_efficientdet_d0` remains the S0 control.
88
 
89
+ ### FTSC follow-up ablations on EfficientDet-D0
90
+
91
+ The FTSC configs keep DALA's hard assignment and inference unchanged:
92
+
93
+ | Case | Config | Change from F3 |
94
+ |---|---|---|
95
+ | F4 / Step 1 | `efficientdet_effb0_bifpn_dala_ftsc_f4_soft_8xb16-crop512-100e_levir.py` | Residual gate, 5-epoch warmup, 10-epoch linear ramp |
96
+ | F5 / Step 2 | `efficientdet_effb0_bifpn_dala_ftsc_f5_learn_8xb16-crop512-100e_levir.py` | F4 plus bounded learned level/quality exponents |
97
+
98
+ `FtscProgressHook` propagates the zero-based runner epoch to the calibrator.
99
+ F5 registers two scalar parameters under `bbox_head.ftsc_calibrator`, initializes
100
+ both at the F3 value `1.0`, bounds them to `[0, 2]`, and adds a weak L2 prior.
101
+ Both variants remain training-only and add no inference-time operations.
102
+
103
  The repository runner accepts all three variants together:
104
 
105
  ```bash
mmdet_code/mmdetection/projects/EfficientDet/configs/__pycache__/efficientdet_effb0_bifpn_dala_ftsc_f4_soft_8xb16-crop512-100e_levir.cpython-313.pyc ADDED
Binary file (1.09 kB). View file
 
mmdet_code/mmdetection/projects/EfficientDet/configs/__pycache__/efficientdet_effb0_bifpn_dala_ftsc_f5_learn_8xb16-crop512-100e_levir.cpython-313.pyc ADDED
Binary file (938 Bytes). View file
 
mmdet_code/mmdetection/projects/EfficientDet/configs/efficientdet_effb0_bifpn_dala_ftsc_f4_soft_8xb16-crop512-100e_levir.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """EfficientDet-D0 DALA + FTSC-F4 residual warmup (Step 1).
2
+
3
+ F4 keeps F3's level-quality gate but applies it as a residual around one. The
4
+ gate is disabled for five epochs and linearly ramps to full strength over the
5
+ next ten epochs. This adapts the gradient-stability/noise-robust motivation of
6
+ UGS and TOLF without changing assignment or inference.
7
+ """
8
+
9
+ _base_ = './efficientdet_effb0_bifpn_dala_ftsc_f3_level_quality_8xb16-crop512-100e_levir.py'
10
+
11
+ model = dict(
12
+ bbox_head=dict(
13
+ ftsc_residual_blend=True,
14
+ ftsc_warmup_epochs=5,
15
+ ftsc_ramp_epochs=10,
16
+ ftsc_learnable_strength=False))
17
+
18
+ # A derived list replaces the base list in MMEngine, so retain EfficientDet's
19
+ # EMA hook explicitly and add epoch propagation for the FTSC ramp.
20
+ custom_hooks = [
21
+ dict(
22
+ type='EMAHook',
23
+ ema_type='ExpMomentumEMA',
24
+ momentum=0.0002,
25
+ update_buffers=True,
26
+ priority=49),
27
+ dict(type='FtscProgressHook', strict=True),
28
+ ]
mmdet_code/mmdetection/projects/EfficientDet/configs/efficientdet_effb0_bifpn_dala_ftsc_f5_learn_8xb16-crop512-100e_levir.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """EfficientDet-D0 DALA + FTSC-F5 learned gate strength (Step 2).
2
+
3
+ F5 inherits F4's residual warmup and learns bounded level/quality exponents.
4
+ Both exponents initialize at 1.0, exactly matching the full F3 gate when the
5
+ ramp reaches one, so the ablation changes learnability rather than its starting
6
+ formulation. The weak prior only prevents unconstrained drift.
7
+ """
8
+
9
+ _base_ = './efficientdet_effb0_bifpn_dala_ftsc_f4_soft_8xb16-crop512-100e_levir.py'
10
+
11
+ model = dict(
12
+ bbox_head=dict(
13
+ ftsc_learnable_strength=True,
14
+ ftsc_strength_max=2.0,
15
+ ftsc_strength_init_level=1.0,
16
+ ftsc_strength_init_quality=1.0,
17
+ ftsc_strength_reg_weight=0.0001))
mmdet_code/mmdetection/projects/EfficientDet/tests/__pycache__/test_dala_efficientdet_head.cpython-313.pyc CHANGED
Binary files a/mmdet_code/mmdetection/projects/EfficientDet/tests/__pycache__/test_dala_efficientdet_head.cpython-313.pyc and b/mmdet_code/mmdetection/projects/EfficientDet/tests/__pycache__/test_dala_efficientdet_head.cpython-313.pyc differ
 
mmdet_code/mmdetection/projects/EfficientDet/tests/test_dala_efficientdet_head.py CHANGED
@@ -178,3 +178,46 @@ def test_dala_efficientdet_ftsc_quality_weight_prefers_better_simd():
178
  pos_assigned_gt_inds=torch.tensor([0, 0]))
179
 
180
  assert weights[0] > weights[1]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
178
  pos_assigned_gt_inds=torch.tensor([0, 0]))
179
 
180
  assert weights[0] > weights[1]
181
+
182
+
183
+ def test_dala_efficientdet_registers_learnable_ftsc_strength():
184
+ head = DalaEfficientDetSepBNHead(
185
+ num_classes=1,
186
+ num_ins=2,
187
+ in_channels=8,
188
+ feat_channels=8,
189
+ stacked_convs=1,
190
+ norm_cfg=dict(type='BN'),
191
+ use_ftsc=True,
192
+ ftsc_mode='level_quality',
193
+ ftsc_normalize=True,
194
+ ftsc_learnable_strength=True,
195
+ anchor_generator=dict(
196
+ type='AnchorGenerator',
197
+ scales=[1],
198
+ ratios=[1.0],
199
+ strides=[8, 16]),
200
+ train_cfg=dict(
201
+ assigner=dict(type='DalaAssigner', sync_stats=False),
202
+ sampler=dict(type='PseudoSampler'),
203
+ allowed_border=-1,
204
+ pos_weight=-1))
205
+
206
+ parameter_names = dict(head.named_parameters())
207
+ assert 'ftsc_calibrator.level_strength_logit' in parameter_names
208
+ assert 'ftsc_calibrator.quality_strength_logit' in parameter_names
209
+
210
+ weights = head._ftsc_positive_weights(
211
+ torch.tensor([
212
+ [0., 0., 10., 10.],
213
+ [2., 2., 12., 12.],
214
+ [-15., -15., 25., 25.],
215
+ ]),
216
+ torch.tensor([0, 0, 1]),
217
+ torch.tensor([[0., 0., 10., 10.]]),
218
+ pos_inds=torch.tensor([0, 1, 2]),
219
+ pos_assigned_gt_inds=torch.tensor([0, 0, 0]))
220
+ (weights * weights.new_tensor([1., 2., 4.])).sum().backward()
221
+
222
+ assert head.ftsc_calibrator.level_strength_logit.grad is not None
223
+ assert head.ftsc_calibrator.quality_strength_logit.grad is not None
mmdet_code/mmdetection/tests/test_engine/test_hooks/__pycache__/test_ftsc_progress_hook.cpython-313.pyc ADDED
Binary file (1.57 kB). View file
 
mmdet_code/mmdetection/tests/test_engine/test_hooks/test_ftsc_progress_hook.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) OpenMMLab. All rights reserved.
2
+ from unittest.mock import Mock
3
+
4
+ import torch.nn as nn
5
+
6
+ from mmdet.engine.hooks import FtscProgressHook
7
+ from mmdet.models.task_modules import FpnTinySupervisionCalibrator
8
+
9
+
10
+ class _ModelWithFtsc(nn.Module):
11
+
12
+ def __init__(self):
13
+ super().__init__()
14
+ self.ftsc = FpnTinySupervisionCalibrator(
15
+ residual_blend=True, warmup_epochs=2, ramp_epochs=2)
16
+
17
+
18
+ def test_ftsc_progress_hook_sets_epoch():
19
+ model = _ModelWithFtsc()
20
+ runner = Mock(model=model, epoch=3)
21
+ hook = FtscProgressHook(strict=True)
22
+
23
+ hook.before_train_epoch(runner)
24
+
25
+ assert model.ftsc._current_epoch == 3
26
+ assert model.ftsc.blend_strength() == 1.0
mmdet_code/mmdetection/tests/test_models/test_task_modules/__pycache__/test_ftsc_calibrator.cpython-313.pyc CHANGED
Binary files a/mmdet_code/mmdetection/tests/test_models/test_task_modules/__pycache__/test_ftsc_calibrator.cpython-313.pyc and b/mmdet_code/mmdetection/tests/test_models/test_task_modules/__pycache__/test_ftsc_calibrator.cpython-313.pyc differ
 
mmdet_code/mmdetection/tests/test_models/test_task_modules/test_ftsc_calibrator.py CHANGED
@@ -76,3 +76,67 @@ def test_ftsc_no_positive_returns_empty_weight_vector():
76
  pos_assigned_gt_inds=torch.empty((0, ), dtype=torch.long))
77
 
78
  assert weights.numel() == 0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76
  pos_assigned_gt_inds=torch.empty((0, ), dtype=torch.long))
77
 
78
  assert weights.numel() == 0
79
+
80
+
81
+ def test_ftsc_residual_warmup_and_ramp():
82
+ calibrator = FpnTinySupervisionCalibrator(
83
+ mode='level_quality',
84
+ normalize=True,
85
+ residual_blend=True,
86
+ warmup_epochs=2,
87
+ ramp_epochs=2)
88
+ anchors = torch.tensor([
89
+ [0., 0., 10., 10.],
90
+ [2., 2., 12., 12.],
91
+ [-15., -15., 25., 25.],
92
+ ])
93
+ level_ids = torch.tensor([0, 0, 1])
94
+ gt_bboxes = torch.tensor([[0., 0., 10., 10.]])
95
+ kwargs = dict(
96
+ anchors=anchors,
97
+ level_ids=level_ids,
98
+ gt_bboxes=gt_bboxes,
99
+ pos_inds=torch.tensor([0, 1, 2]),
100
+ pos_assigned_gt_inds=torch.tensor([0, 0, 0]))
101
+
102
+ calibrator.set_epoch(0)
103
+ warmup_weights = calibrator(**kwargs)
104
+ assert torch.equal(warmup_weights, torch.ones_like(warmup_weights))
105
+
106
+ calibrator.set_epoch(2)
107
+ half_weights = calibrator(**kwargs)
108
+ calibrator.set_epoch(3)
109
+ full_weights = calibrator(**kwargs)
110
+ assert torch.allclose(
111
+ half_weights - 1, 0.5 * (full_weights - 1), atol=1e-6)
112
+ assert torch.allclose(full_weights.mean(), torch.ones(()), atol=1e-6)
113
+
114
+
115
+ def test_ftsc_learnable_strength_receives_gradient():
116
+ calibrator = FpnTinySupervisionCalibrator(
117
+ mode='level_quality',
118
+ normalize=True,
119
+ learnable_strength=True,
120
+ strength_max=2.0,
121
+ strength_init_level=1.0,
122
+ strength_init_quality=1.0)
123
+ anchors = torch.tensor([
124
+ [0., 0., 10., 10.],
125
+ [2., 2., 12., 12.],
126
+ [-15., -15., 25., 25.],
127
+ ])
128
+ weights = calibrator(
129
+ anchors,
130
+ torch.tensor([0, 0, 1]),
131
+ torch.tensor([[0., 0., 10., 10.]]),
132
+ pos_inds=torch.tensor([0, 1, 2]),
133
+ pos_assigned_gt_inds=torch.tensor([0, 0, 0]))
134
+ objective = (weights * weights.new_tensor([1., 2., 4.])).sum()
135
+ objective.backward()
136
+
137
+ assert calibrator.level_strength_logit.grad is not None
138
+ assert calibrator.quality_strength_logit.grad is not None
139
+ assert torch.isfinite(calibrator.level_strength_logit.grad)
140
+ assert torch.isfinite(calibrator.quality_strength_logit.grad)
141
+ assert calibrator.level_strength_logit.grad.abs() > 0
142
+ assert calibrator.quality_strength_logit.grad.abs() > 0
mmdet_code/train_dala.py CHANGED
@@ -27,7 +27,7 @@ from pathlib import Path
27
  from typing import Any, Mapping
28
 
29
 
30
- RUNNER_VERSION = "1.1.2"
31
  MODEL_FAMILY = "EfficientDet-D0"
32
  METRIC_NAME = "coco/bbox_mAP"
33
  ABLATION_IDENTIFIER_PATTERN = re.compile(r"^[A-Za-z][A-Za-z0-9_-]*$")
@@ -184,6 +184,14 @@ class DalaAblationRunner:
184
  self.generated_dir = self.output_root / "generated_configs"
185
  self.artifact_root = self.output_root / "artifacts"
186
  self.scheduler_mode = str(plan.get("lr_scheduler", "multistep")).lower()
 
 
 
 
 
 
 
 
187
  self.hf_uploader = (
188
  DalaHfUploader(self.plan, self.output_root, self.csv_path)
189
  if DalaHfUploader is not None else None
@@ -398,9 +406,10 @@ class DalaAblationRunner:
398
  cfg.optim_wrapper.optimizer.weight_decay = float(spec["weight_decay"])
399
  if "auto_scale_lr" in cfg:
400
  cfg.auto_scale_lr.enable = False
401
- cfg.randomness = {
402
- "seed": int(seed), "deterministic": bool(self.plan.get("deterministic", False))
403
- }
 
404
  run_dir = self.output_root / f"seed_{seed}" / variant
405
  cfg.work_dir = str(run_dir)
406
  cfg.default_hooks.checkpoint.update(
@@ -416,7 +425,8 @@ class DalaAblationRunner:
416
  patience = int(self.plan.get("early_stop_patience", 0))
417
  if patience > 0:
418
  hooks.append({
419
- "type": "EarlyStoppingHook", "monitor": METRIC_NAME, "rule": "greater",
 
420
  "patience": patience,
421
  "min_delta": float(self.plan.get("early_stop_min_delta", 0.001)),
422
  "strict": True, "check_finite": True,
@@ -454,7 +464,7 @@ class DalaAblationRunner:
454
  has_primary = True
455
  elif self.scheduler_mode == "plateau" and scheduler_type == "ReduceOnPlateauLR":
456
  scheduler.update(
457
- monitor=METRIC_NAME, rule="greater",
458
  factor=float(self.plan.get("plateau_factor", 0.5)),
459
  patience=int(self.plan.get("plateau_patience", 5)),
460
  threshold=float(self.plan.get("plateau_threshold", 0.001)),
 
27
  from typing import Any, Mapping
28
 
29
 
30
+ RUNNER_VERSION = "1.2.0"
31
  MODEL_FAMILY = "EfficientDet-D0"
32
  METRIC_NAME = "coco/bbox_mAP"
33
  ABLATION_IDENTIFIER_PATTERN = re.compile(r"^[A-Za-z][A-Za-z0-9_-]*$")
 
184
  self.generated_dir = self.output_root / "generated_configs"
185
  self.artifact_root = self.output_root / "artifacts"
186
  self.scheduler_mode = str(plan.get("lr_scheduler", "multistep")).lower()
187
+ self.monitor_metric = str(
188
+ plan.get(
189
+ "monitor_metric",
190
+ plan.get("save_best_metric", METRIC_NAME),
191
+ )
192
+ ).strip()
193
+ if not self.monitor_metric:
194
+ raise ValueError("monitor_metric/save_best_metric không được rỗng")
195
  self.hf_uploader = (
196
  DalaHfUploader(self.plan, self.output_root, self.csv_path)
197
  if DalaHfUploader is not None else None
 
406
  cfg.optim_wrapper.optimizer.weight_decay = float(spec["weight_decay"])
407
  if "auto_scale_lr" in cfg:
408
  cfg.auto_scale_lr.enable = False
409
+ deterministic = bool(self.plan.get("deterministic", False))
410
+ cfg.randomness = {"seed": int(seed), "deterministic": deterministic}
411
+ if deterministic:
412
+ cfg.env_cfg["cudnn_benchmark"] = False
413
  run_dir = self.output_root / f"seed_{seed}" / variant
414
  cfg.work_dir = str(run_dir)
415
  cfg.default_hooks.checkpoint.update(
 
425
  patience = int(self.plan.get("early_stop_patience", 0))
426
  if patience > 0:
427
  hooks.append({
428
+ "type": "EarlyStoppingHook", "monitor": self.monitor_metric,
429
+ "rule": "greater",
430
  "patience": patience,
431
  "min_delta": float(self.plan.get("early_stop_min_delta", 0.001)),
432
  "strict": True, "check_finite": True,
 
464
  has_primary = True
465
  elif self.scheduler_mode == "plateau" and scheduler_type == "ReduceOnPlateauLR":
466
  scheduler.update(
467
+ monitor=self.monitor_metric, rule="greater",
468
  factor=float(self.plan.get("plateau_factor", 0.5)),
469
  patience=int(self.plan.get("plateau_patience", 5)),
470
  threshold=float(self.plan.get("plateau_threshold", 0.001)),