TLMHoang commited on
Commit
df5fe31
·
verified ·
1 Parent(s): 81a1d08

Upload folder using huggingface_hub

Browse files
mmdet_code/__pycache__/dala_runtime_sitecustomize.cpython-313.pyc ADDED
Binary file (4.55 kB). View file
 
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/models/task_modules/assigners/__pycache__/dala_assigner.cpython-313.pyc CHANGED
Binary files a/mmdet_code/mmdetection/mmdet/models/task_modules/assigners/__pycache__/dala_assigner.cpython-313.pyc and b/mmdet_code/mmdetection/mmdet/models/task_modules/assigners/__pycache__/dala_assigner.cpython-313.pyc differ
 
mmdet_code/mmdetection/mmdet/models/task_modules/assigners/dala_assigner.py CHANGED
@@ -163,39 +163,152 @@ class DalaPositiveQuota(nn.Module):
163
  training the per-call statistics are reduced across ranks by default.
164
  """
165
 
166
- def __init__(self, sync_stats: bool = True) -> None:
 
167
  super().__init__()
 
 
168
  self.sync_stats = sync_stats
 
169
  self.register_buffer('density_sum', torch.zeros((),
170
  dtype=torch.float64))
171
  self.register_buffer('density_count', torch.zeros((),
172
  dtype=torch.long))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
173
 
174
  @torch.no_grad()
175
  def forward(self, inside_counts: Tensor) -> Tensor:
176
- """Update the running density and return integer positive quotas."""
177
  if inside_counts.numel() == 0:
178
  return inside_counts.to(dtype=torch.long)
179
 
180
  stats = torch.stack((inside_counts.double().sum(),
181
  inside_counts.new_tensor(
182
  inside_counts.numel(), dtype=torch.float64)))
183
- if (self.sync_stats and dist.is_available() and dist.is_initialized()):
184
- dist.all_reduce(stats, op=dist.ReduceOp.SUM)
185
 
186
  self.density_sum.add_(stats[0].to(self.density_sum.device))
187
  self.density_count.add_(stats[1].to(
188
  device=self.density_count.device, dtype=torch.long))
189
  mean_density = (self.density_sum /
190
  self.density_count.clamp_min(1)).to(inside_counts)
 
191
 
192
- # Equation (4) produces a real value, while top-k requires an integer.
193
- # The reference implementation truncates toward zero (floor here,
194
- # because counts are non-negative).
195
- quotas = torch.floor(inside_counts / mean_density.clamp_min(1e-12))
196
- quotas = quotas.clamp_min(1).to(dtype=torch.long)
197
- # A GT with no point/anchor inside cannot receive a valid positive.
198
- return torch.minimum(quotas, inside_counts.to(dtype=torch.long))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
199
 
200
 
201
  @TASK_UTILS.register_module()
@@ -212,11 +325,14 @@ class DalaAssigner(nn.Module, BaseAssigner):
212
  sync_stats: bool = True,
213
  similarity_mode: str = 's0',
214
  nwd_normalizer: float = 32.0,
215
- level_lambda: float = 1.0) -> None:
 
216
  nn.Module.__init__(self)
217
  if similarity_mode not in {'s0', 's1', 's2', 's3'}:
218
  raise ValueError(
219
  'similarity_mode must be one of s0, s1, s2, or s3')
 
 
220
  if nwd_normalizer <= 0:
221
  raise ValueError('nwd_normalizer must be positive')
222
  if level_lambda < 0:
@@ -225,6 +341,7 @@ class DalaAssigner(nn.Module, BaseAssigner):
225
  self.similarity_mode = similarity_mode
226
  self.nwd_normalizer = nwd_normalizer
227
  self.level_lambda = level_lambda
 
228
  self.quota_tracker = DalaPositiveQuota(sync_stats=sync_stats)
229
  self.ignore_calculator = BboxOverlaps2D()
230
 
@@ -247,6 +364,53 @@ class DalaAssigner(nn.Module, BaseAssigner):
247
  level_ids,
248
  level_lambda=self.level_lambda)
249
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
250
  @torch.no_grad()
251
  def assign(self,
252
  pred_instances: InstanceData,
@@ -289,18 +453,27 @@ class DalaAssigner(nn.Module, BaseAssigner):
289
 
290
  similarities = self._calculate_similarity(priors, gt_bboxes,
291
  level_ids)
292
- quotas = self.quota_tracker(inside.sum(dim=0).to(similarities))
293
-
294
  selected_scores = similarities.new_full(similarities.shape, -torch.inf)
295
- for gt_idx, quota in enumerate(quotas.tolist()):
296
- if quota == 0:
297
- continue
298
- candidates = torch.nonzero(
299
- inside[:, gt_idx], as_tuple=False).squeeze(1)
300
- candidate_scores = similarities[candidates, gt_idx]
301
- top_indices = candidate_scores.topk(quota, largest=True).indices
302
- chosen = candidates[top_indices]
303
- selected_scores[chosen, gt_idx] = similarities[chosen, gt_idx]
 
 
 
 
 
 
 
 
 
 
 
304
 
305
  best_scores, best_gt = selected_scores.max(dim=1)
306
  positive = torch.isfinite(best_scores)
 
163
  training the per-call statistics are reduced across ranks by default.
164
  """
165
 
166
+ def __init__(self, sync_stats: bool = True,
167
+ max_num_levels: int = 5) -> None:
168
  super().__init__()
169
+ if max_num_levels <= 0:
170
+ raise ValueError('max_num_levels must be positive')
171
  self.sync_stats = sync_stats
172
+ self.max_num_levels = max_num_levels
173
  self.register_buffer('density_sum', torch.zeros((),
174
  dtype=torch.float64))
175
  self.register_buffer('density_count', torch.zeros((),
176
  dtype=torch.long))
177
+ self.register_buffer('level_density_sum', torch.zeros(
178
+ (max_num_levels, ), dtype=torch.float64))
179
+ self.register_buffer('level_density_count', torch.zeros(
180
+ (max_num_levels, ), dtype=torch.long))
181
+
182
+ def _load_from_state_dict(self, state_dict, prefix, local_metadata, strict,
183
+ missing_keys, unexpected_keys, error_msgs):
184
+ for name in ('level_density_sum', 'level_density_count'):
185
+ key = prefix + name
186
+ current = getattr(self, name)
187
+ if key not in state_dict:
188
+ state_dict[key] = current.clone()
189
+ elif state_dict[key].shape != current.shape:
190
+ resized = current.clone()
191
+ length = min(resized.numel(), state_dict[key].numel())
192
+ resized[:length] = state_dict[key].reshape(-1)[:length].to(
193
+ resized)
194
+ state_dict[key] = resized
195
+ super()._load_from_state_dict(
196
+ state_dict, prefix, local_metadata, strict, missing_keys,
197
+ unexpected_keys, error_msgs)
198
+
199
+ @torch.no_grad()
200
+ def _sync_stats(self, stats: Tensor) -> Tensor:
201
+ if (self.sync_stats and dist.is_available() and dist.is_initialized()):
202
+ dist.all_reduce(stats, op=dist.ReduceOp.SUM)
203
+ return stats
204
+
205
+ @staticmethod
206
+ def _counts_to_quotas(counts: Tensor, mean_density: Tensor) -> Tensor:
207
+ quotas = torch.floor(counts / mean_density.clamp_min(1e-12))
208
+ quotas = quotas.clamp_min(1).to(dtype=torch.long)
209
+ return torch.minimum(quotas, counts.to(dtype=torch.long))
210
 
211
  @torch.no_grad()
212
  def forward(self, inside_counts: Tensor) -> Tensor:
213
+ """Update the global R0 density and return integer positive quotas."""
214
  if inside_counts.numel() == 0:
215
  return inside_counts.to(dtype=torch.long)
216
 
217
  stats = torch.stack((inside_counts.double().sum(),
218
  inside_counts.new_tensor(
219
  inside_counts.numel(), dtype=torch.float64)))
220
+ stats = self._sync_stats(stats)
 
221
 
222
  self.density_sum.add_(stats[0].to(self.density_sum.device))
223
  self.density_count.add_(stats[1].to(
224
  device=self.density_count.device, dtype=torch.long))
225
  mean_density = (self.density_sum /
226
  self.density_count.clamp_min(1)).to(inside_counts)
227
+ return self._counts_to_quotas(inside_counts, mean_density)
228
 
229
+ @torch.no_grad()
230
+ def level_means(self, inside_counts_by_level: Tensor) -> Tensor:
231
+ """Update per-level R statistics and return current level means."""
232
+ if inside_counts_by_level.ndim != 2:
233
+ raise ValueError('inside_counts_by_level must have shape (G, L)')
234
+ num_levels = inside_counts_by_level.shape[1]
235
+ if num_levels == 0:
236
+ return inside_counts_by_level.new_zeros((0, ))
237
+ if num_levels > self.max_num_levels:
238
+ raise ValueError(
239
+ 'Number of FPN levels exceeds DALA quota buffer size')
240
+
241
+ level_sum = inside_counts_by_level.double().sum(dim=0)
242
+ level_count = inside_counts_by_level.new_full(
243
+ (num_levels, ), inside_counts_by_level.shape[0],
244
+ dtype=torch.float64)
245
+ stats = torch.stack((level_sum, level_count), dim=0)
246
+ stats = self._sync_stats(stats)
247
+ level_sum_buffer = self.level_density_sum[:num_levels]
248
+ level_count_buffer = self.level_density_count[:num_levels]
249
+ level_sum_buffer.add_(stats[0].to(level_sum_buffer.device))
250
+ level_count_buffer.add_(stats[1].to(
251
+ device=level_count_buffer.device, dtype=torch.long))
252
+ return (level_sum_buffer /
253
+ level_count_buffer.clamp_min(1)).to(
254
+ inside_counts_by_level)
255
+
256
+ @torch.no_grad()
257
+ def per_level_quotas(self, inside_counts_by_level: Tensor) -> Tensor:
258
+ """R1: independent quota for each GT and FPN level."""
259
+ means = self.level_means(inside_counts_by_level)
260
+ quotas = self._counts_to_quotas(inside_counts_by_level, means[None, :])
261
+ quotas[inside_counts_by_level <= 0] = 0
262
+ return quotas
263
+
264
+ @torch.no_grad()
265
+ def budget_preserving_level_quotas(self, inside_counts_by_level: Tensor,
266
+ level_scores: Tensor) -> Tensor:
267
+ """R2: allocate the R0 budget across levels by relative evidence."""
268
+ if inside_counts_by_level.shape != level_scores.shape:
269
+ raise ValueError('level_scores must match inside_counts_by_level')
270
+ total_counts = inside_counts_by_level.sum(dim=1)
271
+ global_quotas = self(total_counts)
272
+ means = self.level_means(inside_counts_by_level)
273
+ evidence = torch.where(
274
+ inside_counts_by_level > 0,
275
+ inside_counts_by_level / means[None, :].clamp_min(1e-12),
276
+ inside_counts_by_level.new_zeros(inside_counts_by_level.shape))
277
+ evidence_sum = evidence.sum(dim=1, keepdim=True)
278
+ allocation = (
279
+ global_quotas.to(evidence)[:, None] * evidence /
280
+ evidence_sum.clamp_min(1e-12))
281
+ base = torch.minimum(
282
+ torch.floor(allocation).to(dtype=torch.long),
283
+ inside_counts_by_level.to(dtype=torch.long))
284
+ remaining = global_quotas - base.sum(dim=1)
285
+ fractions = allocation - torch.floor(allocation)
286
+ result = base.clone()
287
+ for gt_idx in range(result.shape[0]):
288
+ slots = int(remaining[gt_idx].item())
289
+ while slots > 0:
290
+ capacity = inside_counts_by_level[gt_idx].to(
291
+ dtype=torch.long) - result[gt_idx]
292
+ available = capacity > 0
293
+ if not available.any():
294
+ break
295
+ sortable = torch.stack((
296
+ fractions[gt_idx],
297
+ level_scores[gt_idx],
298
+ -torch.arange(
299
+ result.shape[1],
300
+ device=result.device,
301
+ dtype=fractions.dtype),
302
+ ), dim=1)
303
+ sortable[~available] = -torch.inf
304
+ tie_break_score = (
305
+ sortable[:, 0] * 1e6 + sortable[:, 1] * 1e3 +
306
+ sortable[:, 2])
307
+ level = int(torch.argmax(tie_break_score).item())
308
+ result[gt_idx, level] += 1
309
+ slots -= 1
310
+ result[inside_counts_by_level <= 0] = 0
311
+ return result
312
 
313
 
314
  @TASK_UTILS.register_module()
 
325
  sync_stats: bool = True,
326
  similarity_mode: str = 's0',
327
  nwd_normalizer: float = 32.0,
328
+ level_lambda: float = 1.0,
329
+ quota_mode: str = 'r0') -> None:
330
  nn.Module.__init__(self)
331
  if similarity_mode not in {'s0', 's1', 's2', 's3'}:
332
  raise ValueError(
333
  'similarity_mode must be one of s0, s1, s2, or s3')
334
+ if quota_mode not in {'r0', 'r1', 'r2'}:
335
+ raise ValueError('quota_mode must be one of r0, r1, or r2')
336
  if nwd_normalizer <= 0:
337
  raise ValueError('nwd_normalizer must be positive')
338
  if level_lambda < 0:
 
341
  self.similarity_mode = similarity_mode
342
  self.nwd_normalizer = nwd_normalizer
343
  self.level_lambda = level_lambda
344
+ self.quota_mode = quota_mode
345
  self.quota_tracker = DalaPositiveQuota(sync_stats=sync_stats)
346
  self.ignore_calculator = BboxOverlaps2D()
347
 
 
364
  level_ids,
365
  level_lambda=self.level_lambda)
366
 
367
+ @staticmethod
368
+ def _counts_and_scores_by_level(inside: Tensor, similarities: Tensor,
369
+ level_ids: Tensor) -> tuple[Tensor, Tensor]:
370
+ num_gts = inside.shape[1]
371
+ num_levels = int(level_ids.max().item()) + 1
372
+ counts = similarities.new_zeros((num_gts, num_levels))
373
+ scores = similarities.new_full((num_gts, num_levels), -torch.inf)
374
+ for level in range(num_levels):
375
+ level_mask = level_ids == level
376
+ if not level_mask.any():
377
+ continue
378
+ level_inside = inside[level_mask]
379
+ counts[:, level] = level_inside.sum(dim=0).to(similarities)
380
+ level_similarities = similarities[level_mask].masked_fill(
381
+ ~level_inside, -torch.inf)
382
+ scores[:, level] = level_similarities.max(dim=0).values
383
+ return counts, scores
384
+
385
+ def _select_global(self, selected_scores: Tensor, inside: Tensor,
386
+ similarities: Tensor, quotas: Tensor) -> None:
387
+ for gt_idx, quota in enumerate(quotas.tolist()):
388
+ if quota == 0:
389
+ continue
390
+ candidates = torch.nonzero(
391
+ inside[:, gt_idx], as_tuple=False).squeeze(1)
392
+ candidate_scores = similarities[candidates, gt_idx]
393
+ top_indices = candidate_scores.topk(quota, largest=True).indices
394
+ chosen = candidates[top_indices]
395
+ selected_scores[chosen, gt_idx] = similarities[chosen, gt_idx]
396
+
397
+ def _select_by_level(self, selected_scores: Tensor, inside: Tensor,
398
+ similarities: Tensor, level_ids: Tensor,
399
+ quotas_by_level: Tensor) -> None:
400
+ for gt_idx in range(quotas_by_level.shape[0]):
401
+ for level in range(quotas_by_level.shape[1]):
402
+ quota = int(quotas_by_level[gt_idx, level].item())
403
+ if quota == 0:
404
+ continue
405
+ candidates = torch.nonzero(
406
+ inside[:, gt_idx] & (level_ids == level),
407
+ as_tuple=False).squeeze(1)
408
+ candidate_scores = similarities[candidates, gt_idx]
409
+ top_indices = candidate_scores.topk(
410
+ quota, largest=True).indices
411
+ chosen = candidates[top_indices]
412
+ selected_scores[chosen, gt_idx] = similarities[chosen, gt_idx]
413
+
414
  @torch.no_grad()
415
  def assign(self,
416
  pred_instances: InstanceData,
 
453
 
454
  similarities = self._calculate_similarity(priors, gt_bboxes,
455
  level_ids)
 
 
456
  selected_scores = similarities.new_full(similarities.shape, -torch.inf)
457
+ if self.quota_mode == 'r0':
458
+ quotas = self.quota_tracker(inside.sum(dim=0).to(similarities))
459
+ self._select_global(selected_scores, inside, similarities, quotas)
460
+ else:
461
+ if level_ids is None:
462
+ raise ValueError(
463
+ 'R1/R2 require per-prior level_ids from a DALA anchor head')
464
+ level_ids = level_ids.to(device=priors.device, dtype=torch.long)
465
+ if level_ids.shape[0] != num_priors:
466
+ raise ValueError('level_ids must contain one entry per prior')
467
+ counts, level_scores = self._counts_and_scores_by_level(
468
+ inside, similarities, level_ids)
469
+ if self.quota_mode == 'r1':
470
+ quotas_by_level = self.quota_tracker.per_level_quotas(counts)
471
+ else:
472
+ quotas_by_level = (
473
+ self.quota_tracker.budget_preserving_level_quotas(
474
+ counts, level_scores))
475
+ self._select_by_level(selected_scores, inside, similarities,
476
+ level_ids, quotas_by_level)
477
 
478
  best_scores, best_gt = selected_scores.max(dim=1)
479
  positive = torch.isfinite(best_scores)
mmdet_code/mmdetection/projects/EfficientDet/configs/__pycache__/efficientdet_effb0_bifpn_dala_r1_per_level_8xb16-crop512-100e_levir.cpython-313.pyc ADDED
Binary file (790 Bytes). View file
 
mmdet_code/mmdetection/projects/EfficientDet/configs/__pycache__/efficientdet_effb0_bifpn_dala_r2_budget_level_aware_8xb16-crop512-100e_levir.cpython-313.pyc ADDED
Binary file (770 Bytes). View file
 
mmdet_code/mmdetection/projects/EfficientDet/configs/efficientdet_effb0_bifpn_dala_r1_per_level_8xb16-crop512-100e_levir.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """EfficientDet-D0 with DALA R1 independent per-level RLA.
2
+
3
+ R1 is a diagnostic quantity/allocation variant. It keeps S0 similarity and W0
4
+ DWL fixed, but requests quota independently inside each FPN level. This can
5
+ increase the total number of positives, so gains must be interpreted as a
6
+ quantity diagnostic rather than a clean allocation-only improvement.
7
+ """
8
+
9
+ _base_ = './efficientdet_effb0_bifpn_dala_s0_control_8xb16-crop512-100e_levir.py'
10
+
11
+ model = dict(train_cfg=dict(assigner=dict(quota_mode='r1')))
mmdet_code/mmdetection/projects/EfficientDet/configs/efficientdet_effb0_bifpn_dala_r2_budget_level_aware_8xb16-crop512-100e_levir.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """EfficientDet-D0 with DALA R2 budget-preserving level-aware RLA.
2
+
3
+ R2 keeps S0 similarity and W0 DWL fixed. It first computes the original R0
4
+ global quota per GT, then reallocates that same budget across FPN levels using
5
+ per-level density evidence. This isolates level allocation from total-positive
6
+ count as much as possible.
7
+ """
8
+
9
+ _base_ = './efficientdet_effb0_bifpn_dala_s0_control_8xb16-crop512-100e_levir.py'
10
+
11
+ model = dict(train_cfg=dict(assigner=dict(quota_mode='r2')))
mmdet_code/mmdetection/tests/test_models/test_task_modules/test_assigners/__pycache__/test_dala_assigner.cpython-313.pyc CHANGED
Binary files a/mmdet_code/mmdetection/tests/test_models/test_task_modules/test_assigners/__pycache__/test_dala_assigner.cpython-313.pyc and b/mmdet_code/mmdetection/tests/test_models/test_task_modules/test_assigners/__pycache__/test_dala_assigner.cpython-313.pyc differ
 
mmdet_code/mmdetection/tests/test_models/test_task_modules/test_assigners/test_dala_assigner.py CHANGED
@@ -74,6 +74,62 @@ def test_s3_assigner_requires_level_ids():
74
  raise AssertionError('S3 must reject priors without FPN level IDs')
75
 
76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77
  def test_dala_positive_quota_is_checkpointable():
78
  tracker = DalaPositiveQuota(sync_stats=False)
79
  quotas = tracker(torch.tensor([2., 8.]))
 
74
  raise AssertionError('S3 must reject priors without FPN level IDs')
75
 
76
 
77
+ def test_r1_assigner_selects_independent_per_level_positives():
78
+ assigner = DalaAssigner(quota_mode='r1', sync_stats=False)
79
+ pred_instances = InstanceData(
80
+ priors=torch.tensor([
81
+ [0., 0., 10., 10.],
82
+ [1., 1., 9., 9.],
83
+ [0., 0., 12., 12.],
84
+ [2., 2., 8., 8.],
85
+ ]),
86
+ level_ids=torch.tensor([0, 0, 1, 1]))
87
+ gt_instances = InstanceData(
88
+ bboxes=torch.tensor([[0., 0., 10., 10.]]), labels=torch.tensor([0]))
89
+
90
+ result = assigner.assign(pred_instances, gt_instances)
91
+
92
+ # Each level has two inside candidates, so R1 requests one positive per
93
+ # level. This intentionally changes the total positive count vs R0.
94
+ assert torch.equal(result.gt_inds, torch.tensor([1, -1, 1, -1]))
95
+
96
+
97
+ def test_r2_assigner_preserves_global_budget_across_levels():
98
+ assigner = DalaAssigner(quota_mode='r2', sync_stats=False)
99
+ pred_instances = InstanceData(
100
+ priors=torch.tensor([
101
+ [1., 1., 9., 9.],
102
+ [2., 2., 8., 8.],
103
+ [0., 0., 10., 10.],
104
+ [0., 0., 12., 12.],
105
+ ]),
106
+ level_ids=torch.tensor([0, 0, 1, 1]))
107
+ gt_instances = InstanceData(
108
+ bboxes=torch.tensor([[0., 0., 10., 10.]]), labels=torch.tensor([0]))
109
+
110
+ result = assigner.assign(pred_instances, gt_instances)
111
+
112
+ # R0's total quota is one for four inside candidates. R2 keeps that budget
113
+ # and allocates it to the level with the strongest candidate.
114
+ assert result.gt_inds.eq(1).sum().item() == 1
115
+ assert result.gt_inds[2].item() == 1
116
+
117
+
118
+ def test_r1_r2_assigners_require_level_ids():
119
+ gt_instances = InstanceData(
120
+ bboxes=torch.tensor([[0., 0., 10., 10.]]), labels=torch.tensor([0]))
121
+ pred_instances = InstanceData(
122
+ priors=torch.tensor([[0., 0., 10., 10.]]))
123
+ for quota_mode in ('r1', 'r2'):
124
+ assigner = DalaAssigner(quota_mode=quota_mode, sync_stats=False)
125
+ try:
126
+ assigner.assign(pred_instances, gt_instances)
127
+ except ValueError as error:
128
+ assert 'level_ids' in str(error)
129
+ else:
130
+ raise AssertionError(f'{quota_mode} must reject missing level IDs')
131
+
132
+
133
  def test_dala_positive_quota_is_checkpointable():
134
  tracker = DalaPositiveQuota(sync_stats=False)
135
  quotas = tracker(torch.tensor([2., 8.]))
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.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_-]*$")
@@ -116,6 +116,8 @@ def validate_plan(plan: Mapping[str, Any]) -> None:
116
  raise ValueError("training_seeds phải là danh sách không rỗng, không trùng")
117
  if int(plan["epochs"]) <= 0:
118
  raise ValueError("epochs phải > 0")
 
 
119
 
120
  ratios = {
121
  "train": float(plan.get("train_ratio", 0.70)),
@@ -313,6 +315,23 @@ class DalaAblationRunner:
313
  elif isinstance(current, (list, tuple)):
314
  pending.extend(current)
315
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
316
  def _patch_dataset(self, dataset: Any, split: str, test_mode: bool) -> None:
317
  cursor = dataset
318
  while isinstance(cursor, dict) and "dataset" in cursor:
@@ -350,6 +369,7 @@ class DalaAblationRunner:
350
  cfg = Config.fromfile(str(source))
351
  self._assert_effdet_d0(cfg, source, case)
352
  self._walk_and_patch(cfg._cfg_dict)
 
353
  self._patch_dataset(cfg.train_dataloader.dataset, "train", False)
354
  self._patch_dataset(cfg.val_dataloader.dataset, "val", True)
355
  self._patch_dataset(cfg.test_dataloader.dataset, "test", True)
 
27
  from typing import Any, Mapping
28
 
29
 
30
+ RUNNER_VERSION = "1.1.1"
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_-]*$")
 
116
  raise ValueError("training_seeds phải là danh sách không rỗng, không trùng")
117
  if int(plan["epochs"]) <= 0:
118
  raise ValueError("epochs phải > 0")
119
+ if float(plan.get("eval_score_thr", 0.0)) < 0:
120
+ raise ValueError("eval_score_thr phải không âm")
121
 
122
  ratios = {
123
  "train": float(plan.get("train_ratio", 0.70)),
 
315
  elif isinstance(current, (list, tuple)):
316
  pending.extend(current)
317
 
318
+ def _patch_eval_score_threshold(self, cfg: Any) -> None:
319
+ score_thr = float(self.plan.get("eval_score_thr", 0.0))
320
+ test_cfg = cfg.model.get("test_cfg", {})
321
+ pending = [test_cfg]
322
+ patched = False
323
+ while pending:
324
+ current = pending.pop()
325
+ if isinstance(current, dict):
326
+ if "score_thr" in current:
327
+ current["score_thr"] = score_thr
328
+ patched = True
329
+ pending.extend(current.values())
330
+ elif isinstance(current, (list, tuple)):
331
+ pending.extend(current)
332
+ if not patched:
333
+ raise ValueError("model.test_cfg không có score_thr để patch eval threshold")
334
+
335
  def _patch_dataset(self, dataset: Any, split: str, test_mode: bool) -> None:
336
  cursor = dataset
337
  while isinstance(cursor, dict) and "dataset" in cursor:
 
369
  cfg = Config.fromfile(str(source))
370
  self._assert_effdet_d0(cfg, source, case)
371
  self._walk_and_patch(cfg._cfg_dict)
372
+ self._patch_eval_score_threshold(cfg)
373
  self._patch_dataset(cfg.train_dataloader.dataset, "train", False)
374
  self._patch_dataset(cfg.val_dataloader.dataset, "val", True)
375
  self._patch_dataset(cfg.test_dataloader.dataset, "test", True)