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

Upload folder using huggingface_hub

Browse files
mmdet_code/__pycache__/dala_runtime_sitecustomize.cpython-314.pyc ADDED
Binary file (4.59 kB). View file
 
mmdet_code/__pycache__/train_dala.cpython-313.pyc ADDED
Binary file (53.7 kB). View file
 
mmdet_code/__pycache__/train_dala.cpython-314.pyc ADDED
Binary file (59 kB). View file
 
mmdet_code/dala_runtime_sitecustomize.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Compatibility patches loaded only inside DALA train/test subprocesses.
2
+
3
+ ``train_dala.py`` copies this module to the experiment runtime-support folder
4
+ under the special name ``sitecustomize.py``. Python then imports that copy at
5
+ subprocess startup through ``PYTHONPATH``. Do not rename this source file to
6
+ ``sitecustomize.py`` in the repository: that would make the patches apply to
7
+ unrelated Python processes that happen to include ``mmdet_code`` on their
8
+ import path.
9
+ """
10
+
11
+ import importlib.machinery
12
+ import sys
13
+ import types
14
+ from importlib.metadata import distribution
15
+ from pathlib import Path
16
+
17
+ import torch
18
+ from torchvision.ops import nms as torchvision_nms
19
+
20
+
21
+ mmcv_ext = types.ModuleType("mmcv._ext")
22
+ mmcv_ext.__file__ = "<torchvision-mmcv-fallback>"
23
+ mmcv_ext.__spec__ = importlib.machinery.ModuleSpec("mmcv._ext", loader=None)
24
+
25
+
26
+ def fallback_nms(boxes, scores, iou_threshold, offset=0, **kwargs):
27
+ """Use torchvision NMS when compiled MMCV operators are unavailable."""
28
+ if offset != 0:
29
+ raise RuntimeError("Torchvision NMS fallback only supports offset=0")
30
+ return torchvision_nms(boxes, scores, float(iou_threshold))
31
+
32
+
33
+ def unsupported_mmcv_op(name):
34
+ """Return a function that reports unsupported compiled MMCV operators."""
35
+ if name.startswith("__"):
36
+ raise AttributeError(name)
37
+
38
+ def raise_unsupported(*args, **kwargs):
39
+ raise RuntimeError(f"MMCV op '{name}' is unavailable in this mmcv-lite runtime.")
40
+
41
+ return raise_unsupported
42
+
43
+
44
+ mmcv_ext.nms = fallback_nms
45
+ mmcv_ext.get_compiler_version = lambda: "torchvision-ops fallback"
46
+ mmcv_ext.get_compiling_cuda_version = lambda: torch.version.cuda or "unknown"
47
+ mmcv_ext.__getattr__ = unsupported_mmcv_op
48
+ sys.modules["mmcv._ext"] = mmcv_ext
49
+
50
+ import mmdet
51
+
52
+ installed_mmdet = Path(distribution("mmdet").locate_file("mmdet"))
53
+ if str(installed_mmdet) not in mmdet.__path__:
54
+ mmdet.__path__.append(str(installed_mmdet))
55
+
56
+ import torch.nn.functional as F
57
+ from mmdet.models.losses import focal_loss as focal_module
58
+
59
+
60
+ def focal_forward(
61
+ self,
62
+ pred,
63
+ target,
64
+ weight=None,
65
+ avg_factor=None,
66
+ reduction_override=None,
67
+ ):
68
+ """Pure-PyTorch focal loss fallback for the mmcv-lite runtime."""
69
+ if reduction_override not in (None, "none", "mean", "sum"):
70
+ raise ValueError(f"Invalid reduction: {reduction_override}")
71
+ reduction = reduction_override or self.reduction
72
+ if not self.use_sigmoid:
73
+ raise NotImplementedError
74
+ if self.activated:
75
+ loss_function = focal_module.py_focal_loss_with_prob
76
+ else:
77
+ if pred.dim() != target.dim():
78
+ num_classes = pred.size(1)
79
+ target = F.one_hot(target, num_classes=num_classes + 1)
80
+ target = target[:, :num_classes]
81
+ loss_function = focal_module.py_sigmoid_focal_loss
82
+ return self.loss_weight * loss_function(
83
+ pred,
84
+ target,
85
+ weight,
86
+ gamma=self.gamma,
87
+ alpha=self.alpha,
88
+ reduction=reduction,
89
+ avg_factor=avg_factor,
90
+ )
91
+
92
+
93
+ focal_module.FocalLoss.forward = focal_forward
94
+
95
+ from mmdet.utils import register_all_modules
96
+
97
+ register_all_modules(init_default_scope=False)
mmdet_code/train_dala.py ADDED
@@ -0,0 +1,776 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Run notebook-defined LEVIR-Ship DALA ablations on EfficientDet-D0.
2
+
3
+ The notebook should own the experiment plan (cases and hyperparameters). This
4
+ module owns execution: dataset preparation, MMDetection runtime config
5
+ generation, training/testing, metric collection, CSV persistence, and export of
6
+ one ``best.pt`` artifact per ablation case.
7
+
8
+ The public entry point kept for notebook compatibility is
9
+ ``run_dala_benchmark(plan)``. ``run_ablation_suite(plan)`` is an equivalent,
10
+ more explicit name.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import csv
16
+ import json
17
+ import os
18
+ import re
19
+ import shutil
20
+ import statistics
21
+ import subprocess
22
+ import sys
23
+ import time
24
+ from datetime import datetime, timezone
25
+ from importlib.metadata import distribution
26
+ 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_-]*$")
34
+
35
+ CSV_FIELDS = [
36
+ "row_type", "runner_version", "model_family", "ablation_case", "variant",
37
+ "seed", "seeds_completed", "status", "mAP", "AP50", "AP75",
38
+ "mAP_mean", "mAP_std", "AP50_mean", "AP50_std", "AP75_mean",
39
+ "AP75_std", "gflops", "params_m", "epochs", "batch_size", "input_size",
40
+ "lr", "weight_decay", "warmup_iters", "warmup_start_factor",
41
+ "lr_scheduler", "lr_milestones", "lr_gamma", "plateau_factor",
42
+ "plateau_patience", "plateau_threshold", "plateau_cooldown", "min_lr",
43
+ "early_stop_patience", "early_stop_min_delta", "filter_empty_gt",
44
+ "split_seed", "config_path", "work_dir", "checkpoint", "best_pt",
45
+ "metric_source", "duration_sec", "finished_at_utc", "runtime_note", "error",
46
+ ]
47
+
48
+ RUNTIME_NOTE = (
49
+ "MMCV compiled ops unavailable: torchvision NMS/RoIAlign and pure-PyTorch "
50
+ "focal loss fallback; verify before treating numbers as official reproduction."
51
+ )
52
+
53
+ RUNTIME_SITECUSTOMIZE_SOURCE = Path(__file__).with_name(
54
+ "dala_runtime_sitecustomize.py"
55
+ )
56
+
57
+
58
+ def _as_path(value: Any) -> Path:
59
+ return Path(value).expanduser().resolve()
60
+
61
+
62
+ def _blank_row() -> dict[str, Any]:
63
+ return {field: "" for field in CSV_FIELDS}
64
+
65
+
66
+ def _to_float(value: Any) -> float | None:
67
+ try:
68
+ return float(value)
69
+ except (TypeError, ValueError):
70
+ return None
71
+
72
+
73
+ def _normalize_identifier(value: Any, field: str, *, uppercase: bool = False) -> str:
74
+ identifier = str(value).strip()
75
+ if not ABLATION_IDENTIFIER_PATTERN.fullmatch(identifier):
76
+ raise ValueError(
77
+ f"{field}={identifier!r} không hợp lệ; phải bắt đầu bằng chữ và chỉ "
78
+ "chứa chữ, số, '_' hoặc '-'."
79
+ )
80
+ return identifier.upper() if uppercase else identifier
81
+
82
+
83
+ def validate_plan(plan: Mapping[str, Any]) -> None:
84
+ """Fail before training if the notebook experiment plan is inconsistent."""
85
+ required = {
86
+ "project_root", "data_root", "preprocess_script", "output_root", "csv_path",
87
+ "split_seed", "group_level", "epochs", "batch_size", "input_size",
88
+ "num_workers", "training_seeds", "variants",
89
+ }
90
+ missing = sorted(required.difference(plan))
91
+ if missing:
92
+ raise KeyError(f"DALA plan thiếu keys: {missing}")
93
+
94
+ variants = {
95
+ name: spec for name, spec in plan["variants"].items()
96
+ if bool(spec.get("enabled", True))
97
+ }
98
+ if not variants:
99
+ raise ValueError("Không có DALA ablation case nào enabled")
100
+
101
+ seen_cases: set[str] = set()
102
+ for name, spec in variants.items():
103
+ _normalize_identifier(name, "variant")
104
+ for key in ("config", "lr"):
105
+ if key not in spec:
106
+ raise KeyError(f"Variant {name!r} thiếu {key!r}")
107
+ case = _normalize_identifier(
108
+ spec.get("ablation_case", name), "ablation_case", uppercase=True
109
+ )
110
+ if case in seen_cases:
111
+ raise ValueError(f"ablation_case bị lặp: {case}")
112
+ seen_cases.add(case)
113
+
114
+ seeds = [int(seed) for seed in plan["training_seeds"]]
115
+ if not seeds or len(seeds) != len(set(seeds)):
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)),
122
+ "val": float(plan.get("val_ratio", 0.15)),
123
+ "test": float(plan.get("test_ratio", 0.15)),
124
+ }
125
+ if any(value <= 0 for value in ratios.values()) or abs(sum(ratios.values()) - 1) > 1e-9:
126
+ raise ValueError(f"train/val/test ratios phải dương và có tổng bằng 1; nhận {ratios}")
127
+
128
+ warmup_iters = int(plan.get("warmup_iters", 100))
129
+ warmup_factor = float(plan.get("warmup_start_factor", 0.001))
130
+ constant_factor = float(plan.get("constant_warmup_factor", 1 / 3))
131
+ if warmup_iters < 0 or not 0 < warmup_factor <= 1 or not 0 < constant_factor <= 1:
132
+ raise ValueError("warmup không hợp lệ")
133
+
134
+ scheduler = str(plan.get("lr_scheduler", "multistep")).lower()
135
+ if scheduler == "multistep":
136
+ milestones = [int(value) for value in plan.get("lr_milestones", [])]
137
+ epochs = int(plan["epochs"])
138
+ if milestones != sorted(set(milestones)) or any(not 0 < value < epochs for value in milestones):
139
+ raise ValueError(f"lr_milestones không hợp lệ cho {epochs} epochs: {milestones}")
140
+ if not 0 < float(plan.get("lr_gamma", 0.1)) <= 1:
141
+ raise ValueError("lr_gamma phải thuộc (0, 1]")
142
+ elif scheduler == "plateau":
143
+ factor = float(plan.get("plateau_factor", 0.5))
144
+ patience = int(plan.get("plateau_patience", 5))
145
+ threshold = float(plan.get("plateau_threshold", 0.001))
146
+ cooldown = int(plan.get("plateau_cooldown", 2))
147
+ min_lr = float(plan.get("min_lr", 1e-6))
148
+ early_patience = int(plan.get("early_stop_patience", 0))
149
+ if not 0 < factor < 1:
150
+ raise ValueError("plateau_factor phải thuộc (0, 1)")
151
+ if min(patience, threshold, cooldown, min_lr) < 0:
152
+ raise ValueError("plateau patience/threshold/cooldown/min_lr phải không âm")
153
+ if early_patience and early_patience <= patience:
154
+ raise ValueError("early_stop_patience phải lớn hơn plateau_patience")
155
+ else:
156
+ raise ValueError(f"lr_scheduler không hỗ trợ: {scheduler!r}")
157
+
158
+
159
+ class DalaAblationRunner:
160
+ """Stateful executor for one notebook-defined DALA ablation suite."""
161
+
162
+ def __init__(self, plan: Mapping[str, Any]) -> None:
163
+ validate_plan(plan)
164
+ self.plan = dict(plan)
165
+ self.project_root = _as_path(plan["project_root"])
166
+ self.mmdet_root = self.project_root / "mmdetection"
167
+ self.data_root = _as_path(plan["data_root"])
168
+ self.preprocess_script = _as_path(plan["preprocess_script"])
169
+ self.output_root = _as_path(plan["output_root"])
170
+ self.csv_path = _as_path(plan["csv_path"])
171
+ self.split_seed = int(plan["split_seed"])
172
+ self.dataset_out = self.mmdet_root / "data" / f"levir_ship_coco_split_seed_{self.split_seed}"
173
+ self.annotation_dir = self.dataset_out / "annotations"
174
+ self.image_dir = self.data_root / "All Images"
175
+ self.label_dir = self.data_root / "All Annotations"
176
+ self.support_dir = self.output_root / "runtime_support"
177
+ self.generated_dir = self.output_root / "generated_configs"
178
+ self.artifact_root = self.output_root / "artifacts"
179
+ self.scheduler_mode = str(plan.get("lr_scheduler", "multistep")).lower()
180
+ self.variants = {
181
+ name: dict(spec) for name, spec in plan["variants"].items()
182
+ if bool(spec.get("enabled", True))
183
+ }
184
+ self.seeds = [int(seed) for seed in plan["training_seeds"]]
185
+ self.ratios = {
186
+ "train": float(plan.get("train_ratio", 0.70)),
187
+ "val": float(plan.get("val_ratio", 0.15)),
188
+ "test": float(plan.get("test_ratio", 0.15)),
189
+ }
190
+ self.env: dict[str, str] = {}
191
+
192
+ def prepare(self) -> None:
193
+ required = [
194
+ self.mmdet_root / "tools" / "train.py",
195
+ self.mmdet_root / "tools" / "test.py",
196
+ self.mmdet_root / "tools" / "analysis_tools" / "get_flops.py",
197
+ self.preprocess_script, self.image_dir, self.label_dir,
198
+ ]
199
+ required.extend(self.mmdet_root / spec["config"] for spec in self.variants.values())
200
+ missing = [str(path) for path in required if not path.exists()]
201
+ if missing:
202
+ raise FileNotFoundError("Thiếu input/code bắt buộc:\n- " + "\n- ".join(missing))
203
+
204
+ for directory in (
205
+ self.output_root, self.support_dir, self.generated_dir,
206
+ self.artifact_root, self.csv_path.parent,
207
+ ):
208
+ directory.mkdir(parents=True, exist_ok=True)
209
+ self._restore_coco_base_if_needed()
210
+ self._write_runtime_support()
211
+ self.env = os.environ.copy()
212
+ old_pythonpath = self.env.get("PYTHONPATH", "")
213
+ parts = [str(self.support_dir), str(self.mmdet_root)]
214
+ if old_pythonpath:
215
+ parts.append(old_pythonpath)
216
+ self.env["PYTHONPATH"] = os.pathsep.join(parts)
217
+ self.env["PYTHONUNBUFFERED"] = "1"
218
+ self.env["TORCH_FORCE_NO_WEIGHTS_ONLY_LOAD"] = "1"
219
+ cuda_devices = str(self.plan.get("cuda_visible_devices", "")).strip()
220
+ if cuda_devices:
221
+ self.env["CUDA_VISIBLE_DEVICES"] = cuda_devices
222
+
223
+ def _restore_coco_base_if_needed(self) -> None:
224
+ coco_base = self.mmdet_root / "configs" / "_base_" / "datasets" / "coco_detection.py"
225
+ if coco_base.exists():
226
+ return
227
+ installed_root = Path(distribution("mmdet").locate_file("mmdet"))
228
+ source = installed_root / ".mim" / "configs" / "_base_" / "datasets" / "coco_detection.py"
229
+ if not source.exists():
230
+ raise FileNotFoundError(f"Không thể phục hồi base config: {coco_base}")
231
+ coco_base.parent.mkdir(parents=True, exist_ok=True)
232
+ shutil.copy2(source, coco_base)
233
+
234
+ def _write_runtime_support(self) -> None:
235
+ target = self.support_dir / "sitecustomize.py"
236
+ temporary = target.with_suffix(".py.tmp")
237
+ if not RUNTIME_SITECUSTOMIZE_SOURCE.is_file():
238
+ raise FileNotFoundError(
239
+ "Thiếu DALA runtime compatibility module: "
240
+ f"{RUNTIME_SITECUSTOMIZE_SOURCE}"
241
+ )
242
+ shutil.copy2(RUNTIME_SITECUSTOMIZE_SOURCE, temporary)
243
+ temporary.replace(target)
244
+
245
+ def _stream_command(self, command: list[Any], log_path: Path, env: Mapping[str, str]) -> None:
246
+ log_path.parent.mkdir(parents=True, exist_ok=True)
247
+ print("\n$ " + " ".join(map(str, command)), flush=True)
248
+ with log_path.open("a", encoding="utf-8") as log:
249
+ process = subprocess.Popen(
250
+ [str(part) for part in command], cwd=str(self.mmdet_root), env=dict(env),
251
+ stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, bufsize=1,
252
+ )
253
+ assert process.stdout is not None
254
+ for line in process.stdout:
255
+ print(line, end="", flush=True)
256
+ log.write(line)
257
+ log.flush()
258
+ return_code = process.wait()
259
+ if return_code != 0:
260
+ raise RuntimeError(f"Command failed ({return_code}); log: {log_path}")
261
+
262
+ def _manifest_is_valid(self) -> bool:
263
+ manifest_path = self.dataset_out / "split_manifest.json"
264
+ if not manifest_path.exists():
265
+ return False
266
+ try:
267
+ manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
268
+ except (json.JSONDecodeError, OSError):
269
+ return False
270
+ return (
271
+ int(manifest.get("seed", -1)) == self.split_seed
272
+ and manifest.get("group_level") == self.plan["group_level"]
273
+ and all(
274
+ abs(float(manifest.get("ratios", {}).get(name, -1)) - ratio) <= 1e-12
275
+ for name, ratio in self.ratios.items()
276
+ )
277
+ and all(
278
+ (self.annotation_dir / f"{split}.json").is_file()
279
+ and (self.annotation_dir / f"{split}.json").stat().st_size > 0
280
+ for split in ("train", "val", "test")
281
+ )
282
+ )
283
+
284
+ def prepare_dataset(self) -> None:
285
+ if self._manifest_is_valid():
286
+ return
287
+ self._stream_command([
288
+ sys.executable, self.preprocess_script,
289
+ "--data-root", self.data_root,
290
+ "--dataset-out", self.dataset_out,
291
+ "--group-level", self.plan["group_level"],
292
+ "--seed", self.split_seed,
293
+ "--train-ratio", self.ratios["train"],
294
+ "--val-ratio", self.ratios["val"],
295
+ "--test-ratio", self.ratios["test"],
296
+ ], self.output_root / "preprocess.log", self.env)
297
+ if not self._manifest_is_valid():
298
+ raise RuntimeError("Preprocess kết thúc nhưng split manifest không hợp lệ")
299
+
300
+ def _walk_and_patch(self, node: Any) -> None:
301
+ pending = [node]
302
+ while pending:
303
+ current = pending.pop()
304
+ if isinstance(current, dict):
305
+ if "num_classes" in current:
306
+ current["num_classes"] = 1
307
+ if current.get("type") == "Resize" and "scale" in current:
308
+ current["scale"] = (int(self.plan["input_size"]),) * 2
309
+ current["keep_ratio"] = True
310
+ if current.get("type") == "RoIAlign":
311
+ current["use_torchvision"] = True
312
+ pending.extend(current.values())
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:
319
+ cursor = cursor["dataset"]
320
+ cursor["data_root"] = ""
321
+ cursor["ann_file"] = str(self.annotation_dir / f"{split}.json")
322
+ cursor["data_prefix"] = {"img": str(self.image_dir) + "/"}
323
+ cursor["metainfo"] = {"classes": ("ship",)}
324
+ cursor["test_mode"] = bool(test_mode)
325
+ if not test_mode:
326
+ cursor["filter_cfg"] = {
327
+ "filter_empty_gt": bool(self.plan.get("filter_empty_gt", False)),
328
+ "min_size": 1,
329
+ }
330
+
331
+ @staticmethod
332
+ def _assert_effdet_d0(cfg: Any, source: Path, case: str) -> None:
333
+ backbone = cfg.model.get("backbone", {})
334
+ backbone_type = str(backbone.get("type", ""))
335
+ architecture = str(backbone.get("arch", "")).lower()
336
+ if backbone_type != "EfficientNet" or architecture != "b0":
337
+ raise ValueError(
338
+ f"{case} phải chạy trên {MODEL_FAMILY}; config {source} resolve thành "
339
+ f"backbone type={backbone_type!r}, arch={architecture!r}"
340
+ )
341
+
342
+ def make_config(self, variant: str, seed: int) -> tuple[Path, Path]:
343
+ from mmengine.config import Config
344
+
345
+ spec = self.variants[variant]
346
+ case = _normalize_identifier(
347
+ spec.get("ablation_case", variant), "ablation_case", uppercase=True
348
+ )
349
+ source = self.mmdet_root / spec["config"]
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)
356
+ cfg.train_dataloader.batch_size = int(self.plan["batch_size"])
357
+ cfg.train_dataloader.num_workers = int(self.plan["num_workers"])
358
+ cfg.val_dataloader.batch_size = int(self.plan.get("test_batch_size", 1))
359
+ cfg.val_dataloader.num_workers = int(self.plan["num_workers"])
360
+ cfg.test_dataloader.batch_size = int(self.plan.get("test_batch_size", 1))
361
+ cfg.test_dataloader.num_workers = int(self.plan["num_workers"])
362
+ cfg.val_evaluator.ann_file = str(self.annotation_dir / "val.json")
363
+ cfg.test_evaluator.ann_file = str(self.annotation_dir / "test.json")
364
+ cfg.train_cfg.max_epochs = int(self.plan["epochs"])
365
+ cfg.train_cfg.val_interval = int(self.plan.get("val_interval", 1))
366
+ self._patch_schedulers(cfg, source)
367
+ cfg.optim_wrapper.optimizer.lr = float(spec["lr"])
368
+ if "weight_decay" in spec:
369
+ cfg.optim_wrapper.optimizer.weight_decay = float(spec["weight_decay"])
370
+ if "auto_scale_lr" in cfg:
371
+ cfg.auto_scale_lr.enable = False
372
+ cfg.randomness = {
373
+ "seed": int(seed), "deterministic": bool(self.plan.get("deterministic", False))
374
+ }
375
+ run_dir = self.output_root / f"seed_{seed}" / variant
376
+ cfg.work_dir = str(run_dir)
377
+ cfg.default_hooks.checkpoint.update(
378
+ interval=int(self.plan.get("checkpoint_interval", 1)),
379
+ save_best=str(self.plan.get("save_best_metric", METRIC_NAME)),
380
+ rule="greater", max_keep_ckpts=int(self.plan.get("max_keep_ckpts", 2)),
381
+ save_last=True,
382
+ )
383
+ hooks = [
384
+ hook for hook in list(cfg.get("custom_hooks", []))
385
+ if hook.get("type") != "EarlyStoppingHook"
386
+ ]
387
+ patience = int(self.plan.get("early_stop_patience", 0))
388
+ if patience > 0:
389
+ hooks.append({
390
+ "type": "EarlyStoppingHook", "monitor": METRIC_NAME, "rule": "greater",
391
+ "patience": patience,
392
+ "min_delta": float(self.plan.get("early_stop_min_delta", 0.001)),
393
+ "strict": True, "check_finite": True,
394
+ })
395
+ cfg.custom_hooks = hooks
396
+ config_path = self.generated_dir / f"{variant}_seed_{seed}.py"
397
+ cfg.dump(str(config_path))
398
+ return config_path, run_dir
399
+
400
+ def _patch_schedulers(self, cfg: Any, source: Path) -> None:
401
+ has_warmup = False
402
+ has_primary = False
403
+ for scheduler in cfg.param_scheduler:
404
+ scheduler_type = scheduler.get("type")
405
+ if scheduler_type == "LinearLR":
406
+ scheduler.update(
407
+ begin=0, end=int(self.plan.get("warmup_iters", 100)),
408
+ start_factor=float(self.plan.get("warmup_start_factor", 0.001)),
409
+ by_epoch=False,
410
+ )
411
+ has_warmup = True
412
+ elif scheduler_type == "ConstantLR":
413
+ scheduler.update(
414
+ begin=0, end=int(self.plan.get("warmup_iters", 100)),
415
+ factor=float(self.plan.get("constant_warmup_factor", 1 / 3)),
416
+ by_epoch=False,
417
+ )
418
+ has_warmup = True
419
+ elif self.scheduler_mode == "multistep" and scheduler_type == "MultiStepLR":
420
+ scheduler.update(
421
+ begin=0, end=int(self.plan["epochs"]),
422
+ milestones=[int(value) for value in self.plan["lr_milestones"]],
423
+ gamma=float(self.plan.get("lr_gamma", 0.1)), by_epoch=True,
424
+ )
425
+ has_primary = True
426
+ elif self.scheduler_mode == "plateau" and scheduler_type == "ReduceOnPlateauLR":
427
+ scheduler.update(
428
+ monitor=METRIC_NAME, rule="greater",
429
+ factor=float(self.plan.get("plateau_factor", 0.5)),
430
+ patience=int(self.plan.get("plateau_patience", 5)),
431
+ threshold=float(self.plan.get("plateau_threshold", 0.001)),
432
+ threshold_rule="abs", cooldown=int(self.plan.get("plateau_cooldown", 2)),
433
+ min_value=float(self.plan.get("min_lr", 1e-6)),
434
+ begin=1, end=int(self.plan["epochs"]), by_epoch=True,
435
+ )
436
+ has_primary = True
437
+ if not (has_warmup and has_primary):
438
+ raise ValueError(
439
+ f"Config {source} phải có warmup và scheduler {self.scheduler_mode!r}; "
440
+ f"nhận {cfg.param_scheduler}"
441
+ )
442
+
443
+ @staticmethod
444
+ def find_checkpoint(run_dir: Path) -> Path | None:
445
+ best = sorted(run_dir.glob("best_*.pth"), key=lambda path: path.stat().st_mtime)
446
+ if best:
447
+ return best[-1]
448
+ latest = run_dir / "latest.pth"
449
+ if latest.exists():
450
+ return latest
451
+ epochs = sorted(run_dir.glob("epoch_*.pth"), key=lambda path: path.stat().st_mtime)
452
+ return epochs[-1] if epochs else None
453
+
454
+ @staticmethod
455
+ def parse_metrics(test_dir: Path, log_path: Path) -> tuple[dict[str, float], str]:
456
+ aliases = {
457
+ "mAP": ("coco/bbox_mAP", "bbox_mAP"),
458
+ "AP50": ("coco/bbox_mAP_50", "bbox_mAP_50"),
459
+ "AP75": ("coco/bbox_mAP_75", "bbox_mAP_75"),
460
+ }
461
+ found: dict[str, float] = {}
462
+ source = ""
463
+ for scalar_path in sorted(test_dir.rglob("scalars.json")):
464
+ for line in scalar_path.read_text(encoding="utf-8", errors="replace").splitlines():
465
+ try:
466
+ payload = json.loads(line)
467
+ except json.JSONDecodeError:
468
+ continue
469
+ for metric, keys in aliases.items():
470
+ for key in keys:
471
+ if key in payload:
472
+ found[metric] = float(payload[key])
473
+ source = str(scalar_path)
474
+ if len(found) < 3 and log_path.exists():
475
+ text = log_path.read_text(encoding="utf-8", errors="replace")
476
+ for metric, keys in aliases.items():
477
+ for key in keys:
478
+ matches = re.findall(
479
+ rf"(?:{re.escape(key)})\s*[:=]\s*([0-9]*\.?[0-9]+)", text
480
+ )
481
+ if matches:
482
+ found[metric] = float(matches[-1])
483
+ source = str(log_path)
484
+ break
485
+ if set(found) != {"mAP", "AP50", "AP75"}:
486
+ raise RuntimeError(f"Không đọc đủ mAP/AP50/AP75 từ {test_dir}; found={found}")
487
+ return found, source
488
+
489
+ @staticmethod
490
+ def _parse_scaled_number(value: str, unit: str, target: str) -> float:
491
+ powers = {"": 1.0, "K": 1e3, "M": 1e6, "G": 1e9, "T": 1e12, "P": 1e15}
492
+ base = float(value) * powers[unit.upper()]
493
+ return base / (1e9 if target == "gflops" else 1e6)
494
+
495
+ @classmethod
496
+ def parse_complexity(cls, log_path: Path) -> tuple[float, float]:
497
+ text = log_path.read_text(encoding="utf-8", errors="replace")
498
+ flops = re.findall(r"Flops:\s*([0-9]*\.?[0-9]+)\s*([KMGTPE]?)", text, re.I)
499
+ params = re.findall(r"Params:\s*([0-9]*\.?[0-9]+)\s*([KMGTPE]?)", text, re.I)
500
+ if not flops or not params:
501
+ raise RuntimeError(f"Không parse được GFLOPs/params từ {log_path}")
502
+ return (
503
+ cls._parse_scaled_number(*flops[-1], "gflops"),
504
+ cls._parse_scaled_number(*params[-1], "params"),
505
+ )
506
+
507
+ def load_run_rows(self) -> dict[tuple[str, int], dict[str, Any]]:
508
+ if not self.csv_path.exists():
509
+ return {}
510
+ with self.csv_path.open("r", encoding="utf-8", newline="") as handle:
511
+ loaded = list(csv.DictReader(handle))
512
+ return {
513
+ (row["variant"], int(row["seed"])): row for row in loaded
514
+ if row.get("row_type") == "run" and str(row.get("seed", "")).isdigit()
515
+ }
516
+
517
+ def write_results(
518
+ self,
519
+ run_rows: Mapping[tuple[str, int], Mapping[str, Any]],
520
+ complexity: Mapping[str, tuple[float, float]],
521
+ ) -> None:
522
+ all_rows: list[dict[str, Any]] = []
523
+ for variant, spec in self.variants.items():
524
+ for seed in self.seeds:
525
+ row = run_rows.get((variant, seed))
526
+ if row is not None:
527
+ all_rows.append({**_blank_row(), **row})
528
+ successful = [
529
+ run_rows[(variant, seed)] for seed in self.seeds
530
+ if (variant, seed) in run_rows and run_rows[(variant, seed)].get("status") == "ok"
531
+ ]
532
+ summary = self._base_row(variant)
533
+ summary.update({
534
+ "row_type": "summary",
535
+ "seeds_completed": ";".join(str(row["seed"]) for row in successful),
536
+ "status": "complete" if len(successful) == len(self.seeds) else "partial",
537
+ })
538
+ if variant in complexity:
539
+ summary["gflops"], summary["params_m"] = complexity[variant]
540
+ for metric, mean_key, std_key in (
541
+ ("mAP", "mAP_mean", "mAP_std"),
542
+ ("AP50", "AP50_mean", "AP50_std"),
543
+ ("AP75", "AP75_mean", "AP75_std"),
544
+ ):
545
+ values = [_to_float(row.get(metric)) for row in successful]
546
+ clean = [value for value in values if value is not None]
547
+ if clean:
548
+ summary[mean_key] = sum(clean) / len(clean)
549
+ summary[std_key] = statistics.stdev(clean) if len(clean) > 1 else 0.0
550
+ all_rows.append(summary)
551
+ temporary = self.csv_path.with_suffix(self.csv_path.suffix + ".tmp")
552
+ with temporary.open("w", encoding="utf-8", newline="") as handle:
553
+ writer = csv.DictWriter(handle, fieldnames=CSV_FIELDS)
554
+ writer.writeheader()
555
+ writer.writerows(all_rows)
556
+ temporary.replace(self.csv_path)
557
+
558
+ def _base_row(self, variant: str) -> dict[str, Any]:
559
+ spec = self.variants[variant]
560
+ plateau = self.scheduler_mode == "plateau"
561
+ row = _blank_row()
562
+ row.update({
563
+ "runner_version": RUNNER_VERSION, "model_family": MODEL_FAMILY,
564
+ "ablation_case": _normalize_identifier(
565
+ spec.get("ablation_case", variant), "ablation_case", uppercase=True
566
+ ),
567
+ "variant": variant, "epochs": self.plan["epochs"],
568
+ "batch_size": self.plan["batch_size"], "input_size": self.plan["input_size"],
569
+ "lr": spec["lr"], "weight_decay": spec.get("weight_decay", ""),
570
+ "warmup_iters": self.plan.get("warmup_iters", 100),
571
+ "warmup_start_factor": self.plan.get("warmup_start_factor", 0.001),
572
+ "lr_scheduler": self.scheduler_mode,
573
+ "lr_milestones": ";".join(str(value) for value in self.plan.get("lr_milestones", [])),
574
+ "lr_gamma": self.plan.get("lr_gamma", "") if not plateau else "",
575
+ "plateau_factor": self.plan.get("plateau_factor", 0.5) if plateau else "",
576
+ "plateau_patience": self.plan.get("plateau_patience", 5) if plateau else "",
577
+ "plateau_threshold": self.plan.get("plateau_threshold", 0.001) if plateau else "",
578
+ "plateau_cooldown": self.plan.get("plateau_cooldown", 2) if plateau else "",
579
+ "min_lr": self.plan.get("min_lr", 1e-6) if plateau else "",
580
+ "early_stop_patience": self.plan.get("early_stop_patience", 0),
581
+ "early_stop_min_delta": self.plan.get("early_stop_min_delta", 0.001),
582
+ "filter_empty_gt": bool(self.plan.get("filter_empty_gt", False)),
583
+ "split_seed": self.split_seed, "runtime_note": RUNTIME_NOTE,
584
+ })
585
+ return row
586
+
587
+ def measure_complexity(
588
+ self,
589
+ configs: Mapping[tuple[str, int], tuple[Path, Path]],
590
+ run_rows: Mapping[tuple[str, int], Mapping[str, Any]],
591
+ ) -> dict[str, tuple[float, float]]:
592
+ result: dict[str, tuple[float, float]] = {}
593
+ for variant in self.variants:
594
+ cached = next((
595
+ row for (name, _), row in run_rows.items()
596
+ if name == variant and _to_float(row.get("gflops")) is not None
597
+ and _to_float(row.get("params_m")) is not None
598
+ ), None)
599
+ if cached:
600
+ result[variant] = (float(cached["gflops"]), float(cached["params_m"]))
601
+ continue
602
+ config_path, _ = configs[(variant, self.seeds[0])]
603
+ log_path = self.output_root / "complexity" / f"{variant}.log"
604
+ self._stream_command([
605
+ sys.executable,
606
+ self.mmdet_root / "tools" / "analysis_tools" / "get_flops.py",
607
+ config_path, "--num-images", "1",
608
+ ], log_path, self.env)
609
+ result[variant] = self.parse_complexity(log_path)
610
+ return result
611
+
612
+ def run_case(
613
+ self,
614
+ variant: str,
615
+ seed: int,
616
+ config_path: Path,
617
+ run_dir: Path,
618
+ complexity: tuple[float, float],
619
+ ) -> dict[str, Any]:
620
+ run_dir.mkdir(parents=True, exist_ok=True)
621
+ row = self._base_row(variant)
622
+ row.update({
623
+ "row_type": "run", "seed": seed, "status": "running",
624
+ "gflops": complexity[0], "params_m": complexity[1],
625
+ "config_path": str(config_path), "work_dir": str(run_dir),
626
+ })
627
+ started = time.monotonic()
628
+ run_env = self.env.copy()
629
+ run_env["PYTHONHASHSEED"] = str(seed)
630
+ checkpoint = self.find_checkpoint(run_dir)
631
+ marker = run_dir / ".train_complete"
632
+ if not marker.exists():
633
+ command: list[Any] = [
634
+ sys.executable, self.mmdet_root / "tools" / "train.py", config_path,
635
+ "--work-dir", run_dir,
636
+ ]
637
+ if self.plan.get("resume_from_existing", True) and checkpoint is not None:
638
+ command.append("--resume")
639
+ if self.plan.get("amp", False):
640
+ command.append("--amp")
641
+ self._stream_command(command, run_dir / "train.log", run_env)
642
+ marker.write_text(datetime.now(timezone.utc).isoformat(), encoding="utf-8")
643
+ checkpoint = self.find_checkpoint(run_dir)
644
+ if checkpoint is None:
645
+ raise FileNotFoundError(f"Không có checkpoint trong {run_dir}")
646
+
647
+ case = _normalize_identifier(
648
+ self.variants[variant].get("ablation_case", variant),
649
+ "ablation_case",
650
+ uppercase=True,
651
+ )
652
+ artifact_dir = self.artifact_root / case
653
+ if len(self.seeds) > 1:
654
+ artifact_dir = artifact_dir / f"seed_{seed}"
655
+ artifact_dir.mkdir(parents=True, exist_ok=True)
656
+ best_pt = artifact_dir / "best.pt"
657
+ temporary = best_pt.with_suffix(".pt.tmp")
658
+ shutil.copy2(checkpoint, temporary)
659
+ temporary.replace(best_pt)
660
+
661
+ test_dir = run_dir / "test_results"
662
+ test_log = run_dir / "test.log"
663
+ try:
664
+ metrics, metric_source = self.parse_metrics(test_dir, test_log)
665
+ except RuntimeError:
666
+ self._stream_command([
667
+ sys.executable, self.mmdet_root / "tools" / "test.py",
668
+ config_path, checkpoint, "--work-dir", test_dir,
669
+ ], test_log, run_env)
670
+ metrics, metric_source = self.parse_metrics(test_dir, test_log)
671
+ row.update({
672
+ "status": "ok", **metrics, "checkpoint": str(checkpoint),
673
+ "best_pt": str(best_pt), "metric_source": metric_source,
674
+ "duration_sec": round(time.monotonic() - started, 2),
675
+ "finished_at_utc": datetime.now(timezone.utc).isoformat(), "error": "",
676
+ })
677
+ return row
678
+
679
+ def run(self) -> Any:
680
+ self.prepare()
681
+ self.prepare_dataset()
682
+ configs = {
683
+ (variant, seed): self.make_config(variant, seed)
684
+ for variant in self.variants for seed in self.seeds
685
+ }
686
+ run_rows = self.load_run_rows()
687
+ complexity = self.measure_complexity(configs, run_rows)
688
+ self.write_results(run_rows, complexity)
689
+
690
+ for variant in self.variants:
691
+ for seed in self.seeds:
692
+ existing = run_rows.get((variant, seed))
693
+ if self.plan.get("skip_completed", True) and existing and existing.get("status") == "ok":
694
+ print(f"SKIP {variant} seed={seed}: đã có metric hợp lệ", flush=True)
695
+ continue
696
+ running = self._base_row(variant)
697
+ running.update({
698
+ "row_type": "run", "seed": seed, "status": "running",
699
+ "gflops": complexity[variant][0], "params_m": complexity[variant][1],
700
+ "config_path": str(configs[(variant, seed)][0]),
701
+ "work_dir": str(configs[(variant, seed)][1]),
702
+ })
703
+ run_rows[(variant, seed)] = running
704
+ self.write_results(run_rows, complexity)
705
+ started = time.monotonic()
706
+ try:
707
+ row = self.run_case(
708
+ variant, seed, *configs[(variant, seed)], complexity[variant]
709
+ )
710
+ except Exception as exc:
711
+ running.update({
712
+ "status": "failed",
713
+ "duration_sec": round(time.monotonic() - started, 2),
714
+ "finished_at_utc": datetime.now(timezone.utc).isoformat(),
715
+ "error": f"{type(exc).__name__}: {exc}",
716
+ })
717
+ row = running
718
+ run_rows[(variant, seed)] = row
719
+ self.write_results(run_rows, complexity)
720
+ if not self.plan.get("continue_on_error", False):
721
+ raise
722
+ run_rows[(variant, seed)] = row
723
+ self.write_results(run_rows, complexity)
724
+
725
+ try:
726
+ import pandas as pd
727
+ except ImportError:
728
+ with self.csv_path.open("r", encoding="utf-8", newline="") as handle:
729
+ return list(csv.DictReader(handle))
730
+ return pd.read_csv(self.csv_path)
731
+
732
+
733
+ def run_ablation_case(plan: Mapping[str, Any], ablation_case: str) -> Any:
734
+ """Run one enabled case while preserving the same output/CSV contract."""
735
+ target = _normalize_identifier(
736
+ ablation_case, "ablation_case", uppercase=True
737
+ )
738
+ selected = {
739
+ name: dict(spec) for name, spec in plan["variants"].items()
740
+ if _normalize_identifier(
741
+ spec.get("ablation_case", name), "ablation_case", uppercase=True
742
+ ) == target
743
+ }
744
+ if len(selected) != 1:
745
+ raise ValueError(f"Plan phải chứa đúng một variant cho {target}; found={list(selected)}")
746
+ case_plan = dict(plan)
747
+ case_plan["variants"] = selected
748
+ return DalaAblationRunner(case_plan).run()
749
+
750
+
751
+ def run_ablation_suite(plan: Mapping[str, Any]) -> Any:
752
+ """Run all enabled DALA variants defined by the notebook plan."""
753
+ return DalaAblationRunner(plan).run()
754
+
755
+
756
+ def run_dala_benchmark(plan: Mapping[str, Any]) -> Any:
757
+ """Backward-compatible notebook entry point."""
758
+ return run_ablation_suite(plan)
759
+
760
+
761
+ def load_results(csv_path: str | os.PathLike[str]) -> Any:
762
+ """Load an existing result CSV without starting or resuming training."""
763
+ path = _as_path(csv_path)
764
+ try:
765
+ import pandas as pd
766
+ except ImportError:
767
+ with path.open("r", encoding="utf-8", newline="") as handle:
768
+ return list(csv.DictReader(handle))
769
+ return pd.read_csv(path)
770
+
771
+
772
+ __all__ = [
773
+ "ABLATION_IDENTIFIER_PATTERN", "DalaAblationRunner", "MODEL_FAMILY",
774
+ "RUNNER_VERSION", "load_results", "run_ablation_case",
775
+ "run_ablation_suite", "run_dala_benchmark", "validate_plan",
776
+ ]