| """Bounded detector fit interface; learning-gate orchestration is separate.""" | |
| from dataclasses import dataclass | |
| from pathlib import Path | |
| from copy import deepcopy | |
| import json | |
| import math | |
| import os | |
| import random | |
| import time | |
| import hashlib | |
| import torch | |
| from load_dataset import dataset, load_sample | |
| from training.detection_data import convert_detection_sample, detection_batch, transform_example | |
| from training.detection_loss import SourceAwareOBBLoss, build_adapted_detector | |
| from training.model_factory import ROOT, load_pretrained_detector, public_mapping | |
| from training.runtime import load_runtime_config | |
| def freeze_batchnorm_statistics(model): | |
| for module in model.modules(): | |
| if isinstance(module, torch.nn.modules.batchnorm._BatchNorm): | |
| module.eval() | |
| def batchnorm_buffers(model): | |
| return {f"{name}.{field}": getattr(module, field).detach().clone() | |
| for name, module in model.named_modules() | |
| if isinstance(module, torch.nn.modules.batchnorm._BatchNorm) | |
| for field in ("running_mean", "running_var", "num_batches_tracked") | |
| if getattr(module, field) is not None} | |
| def freeze_detector_backbone(model): | |
| for block in list(model.model)[:-1]: | |
| for parameter in block.parameters(): | |
| parameter.requires_grad_(False) | |
| class DetectorTrainConfig: | |
| root: Path = ROOT / "datasets/corpus" | |
| output: Path = ROOT / "training/runs/detector" | |
| learning_rate: float = 0.0001 | |
| epochs: int = 10 | |
| patience: int = 3 | |
| seed: int = 42 | |
| record_initial_metrics: bool = False | |
| expected_initial_sha256: str | None = None | |
| freeze_bn_statistics: bool = False | |
| freeze_backbone: bool = False | |
| distillation_teacher: Path | None = None | |
| distillation_weight: float = 0.0 | |
| def from_json(cls, path: Path, **overrides): | |
| data = json.loads(path.read_text()) | |
| fixed = {"checkpoint": "yolo26n-obb.pt", "image_size": 1024, "batch_size": 1, | |
| "device": "cpu", "use_amp": False, "source_classes": 16, | |
| "license_scope": "all", "optimizer": "AdamW", | |
| "augmentation": {"horizontal_flip": True, "vertical_flip": True, | |
| "right_angle_rotations": True}} | |
| if set(data) != set(fixed) | {"learning_rate", "epochs", "patience", "seed"}: | |
| raise ValueError("unexpected detector configuration fields") | |
| if any(data[k] != value or type(data[k]) is not type(value) for k, value in fixed.items()): | |
| raise ValueError("detector config changes the approved training policy") | |
| return cls(**{**{k: data[k] for k in ("learning_rate", "epochs", "patience", "seed")}, **overrides}) | |
| def __post_init__(self): | |
| if not math.isfinite(self.distillation_weight) or self.distillation_weight < 0: | |
| raise ValueError("distillation weight must be finite and nonnegative") | |
| if (self.distillation_teacher is None) != (self.distillation_weight == 0): | |
| raise ValueError("teacher and positive distillation weight must be supplied together") | |
| if type(self.freeze_backbone) is not bool: | |
| raise ValueError("freeze_backbone must be boolean") | |
| if type(self.freeze_bn_statistics) is not bool: | |
| raise ValueError("freeze_bn_statistics must be boolean") | |
| if not Path(self.output).resolve().is_relative_to(ROOT / "training"): | |
| raise ValueError("detector outputs must remain under training/") | |
| if isinstance(self.learning_rate, bool) or not math.isfinite(self.learning_rate) or self.learning_rate <= 0: | |
| raise ValueError("positive finite learning rate required") | |
| for name, value, low, high in [("epochs", self.epochs, 1, 10), ("patience", self.patience, 1, 3), | |
| ("seed", self.seed, 0, 2**32 - 1)]: | |
| if type(value) is not int or not low <= value <= high: | |
| raise ValueError(f"invalid {name}") | |
| class Trainer: | |
| def __init__(self, config: DetectorTrainConfig): | |
| self.config = config | |
| def fit(self, train_ids: list[str], validation_ids: list[str], *, max_seconds: int) -> dict: | |
| return self._fit(train_ids, validation_ids, max_seconds=max_seconds, diagnostic=False) | |
| def fit_overfit(self, sample_ids: list[str], *, max_seconds: int) -> dict: | |
| if len(sample_ids) != 24 or len(set(sample_ids)) != 24 or not 0 < max_seconds <= 900: | |
| raise ValueError("overfit requires exactly24 unique train tiles and <=900 seconds") | |
| return self._fit(sample_ids, sample_ids, max_seconds=max_seconds, diagnostic=True) | |
| def _fit(self, train_ids, validation_ids, *, max_seconds, diagnostic): | |
| if type(max_seconds) is not int or not 0 < max_seconds <= 3600: | |
| raise ValueError("fit budget must be in (0, 3600]") | |
| config = self.config | |
| train = dataset(config.root, "detection", "train", license_scope="all") | |
| val = train if diagnostic else dataset(config.root, "detection", "val", license_scope="all") | |
| training = {row["id"]: row for row in train.samples} | |
| validation = {row["id"]: row for row in val.samples} | |
| manifest = json.loads((ROOT / "evaluation/quick_eval_manifest.json").read_text()) | |
| reserved = {row["sample_id"] for row in manifest["selection_validation"] if row["task"] == "detection"} | |
| for ids, allowed in [(train_ids, set(training)), (validation_ids, set(training) if diagnostic else set(validation) & reserved)]: | |
| if not ids or len(ids) != len(set(ids)) or not set(ids) <= allowed: | |
| raise ValueError("unique train IDs and reserved selection-validation IDs required") | |
| output = Path(config.output).resolve() | |
| output.mkdir(parents=True, exist_ok=False) | |
| started = time.monotonic() | |
| def budget(): | |
| if time.monotonic() - started >= max_seconds: | |
| raise TimeoutError("cooperative fit budget exhausted") | |
| runtime_path = Path(os.environ.get("LONGMEMORY_GEO_RUNTIME_CONFIG", ROOT / "training/configs/runtime.json")) | |
| runtime = load_runtime_config(runtime_path) | |
| device = runtime.device | |
| if device == "cpu": | |
| torch.set_num_threads(runtime.num_threads) | |
| torch.manual_seed(config.seed) | |
| if device.startswith("cuda"): | |
| torch.cuda.manual_seed_all(config.seed) | |
| rng = random.Random(config.seed) | |
| history, best_metrics, best_checkpoint = [], {}, None | |
| status, stale, best = "COMPLETED", 0, -1. | |
| try: | |
| budget() | |
| pretrained = load_pretrained_detector(ROOT / "training/cache/checkpoints", device=device) | |
| model, transfer = build_adapted_detector(pretrained, seed=config.seed) | |
| model.to(device) | |
| # The loss captures its device at construction time; rebuild it after | |
| # moving the adapted model so target preprocessing follows CUDA. | |
| model.criterion = SourceAwareOBBLoss(model) | |
| teacher = None | |
| teacher_sha256 = None | |
| if config.distillation_teacher is not None: | |
| from training.model_factory import _yolo_class | |
| teacher_path = Path(config.distillation_teacher) | |
| if not teacher_path.is_file(): | |
| raise FileNotFoundError(teacher_path) | |
| with teacher_path.open('rb') as handle: | |
| teacher_sha256 = hashlib.file_digest(handle, 'sha256').hexdigest() | |
| expected_teacher = 'd7b1d805b0ec149890efde89119ef9d60481566ec83166052c04b5d89d9e3cb7' | |
| if teacher_sha256 != expected_teacher: | |
| raise ValueError('teacher checkpoint hash mismatch') | |
| teacher = _yolo_class()(str(teacher_path)).model.to(device).train() | |
| teacher.requires_grad_(False) | |
| freeze_batchnorm_statistics(teacher) | |
| teacher_names = {name.replace(' ', '-'): int(idx) for idx, name in teacher.names.items()} | |
| pairs = [(int(idx), teacher_names[name.replace(' ', '-')]) for idx, name in model.names.items() | |
| if name.replace(' ', '-') in teacher_names] | |
| if not pairs: | |
| raise ValueError('no matching teacher and student classes') | |
| for key, value in {"imgsz": 1024, "batch": 1, "device": "cpu", "amp": False, | |
| "seed": config.seed, "epochs": config.epochs, "patience": config.patience, | |
| "optimizer": "AdamW", "lr0": config.learning_rate, "weight_decay": .01}.items(): | |
| setattr(model.args, key, device if key == "device" else (runtime.use_amp if key == "amp" else value)) | |
| if config.freeze_backbone: | |
| freeze_detector_backbone(model) | |
| fixed_parameters = {name: p.detach().clone() for name, p in model.named_parameters() if not p.requires_grad} | |
| optimizer = torch.optim.AdamW((p for p in model.parameters() if p.requires_grad), lr=config.learning_rate) | |
| predictor = deepcopy(pretrained) | |
| predictor.model, predictor.predictor = model, None | |
| from evaluation.metrics import evaluate_detection | |
| from evaluation.quick_eval import detection_target | |
| mapping = public_mapping(model.names, "detection") | |
| from training.model_factory import model_state_sha256 | |
| initial_sha = model_state_sha256(model) | |
| initial_bn = batchnorm_buffers(model) if config.freeze_bn_statistics else {} | |
| if config.expected_initial_sha256 is not None and initial_sha != config.expected_initial_sha256: | |
| raise ValueError("adapted initialization differs from approved baseline") | |
| def evaluate(): | |
| model.eval() | |
| predictions, targets = [], [] | |
| predictor.model = deepcopy(model) | |
| predictor.predictor = None | |
| for sample_id in validation_ids: | |
| budget() | |
| sample = load_sample(config.root, validation[sample_id], val.expected_hashes) | |
| # Predictor uses an unfused model, and does not mutate the training module. | |
| with torch.inference_mode(): | |
| result = predictor.predict(sample["image"][:, :, ::-1].copy(), imgsz=1024, | |
| device=device, conf=.001, max_det=300, save=False, verbose=False)[0] | |
| objects = [{"category_id": mapping[int(cls)], "confidence": float(conf), | |
| "obb_polygon": points.reshape(-1).tolist()} | |
| for points, cls, conf in zip(result.obb.xyxyxyxy.cpu().numpy(), | |
| result.obb.cls.cpu().numpy(), result.obb.conf.cpu().numpy()) | |
| if int(cls) in mapping] | |
| predictions.append({"sample_id": sample_id, "annotations": objects}) | |
| row = detection_target(sample, "train_overfit" if diagnostic else "selection_validation") | |
| if diagnostic: | |
| row["split"] = "train" | |
| targets.append(row) | |
| budget() | |
| metrics = evaluate_detection(predictions, targets) | |
| return metrics | |
| if config.record_initial_metrics or diagnostic: | |
| history.append({"epoch": 0, "metrics": evaluate(), "initial_state_sha256": initial_sha, | |
| "evaluation_ids": validation_ids, "diagnostic_train_only": diagnostic, | |
| "elapsed_seconds": time.monotonic() - started}) | |
| (output / "initial_evaluation.json").write_text(json.dumps(history[0], indent=2), encoding="utf-8") | |
| initial_progress = {"status": "IN_PROGRESS", "best_checkpoint": None, "history": history, | |
| "best_metrics": {}, "elapsed_seconds": time.monotonic() - started} | |
| temporary_progress = output / "progress.json.partial" | |
| temporary_progress.write_text(json.dumps(initial_progress, indent=2), encoding="utf-8") | |
| temporary_progress.replace(output / "progress.json") | |
| for epoch in range(config.epochs): | |
| budget() | |
| model.train() | |
| if config.freeze_bn_statistics: | |
| freeze_batchnorm_statistics(model) | |
| ids = list(train_ids) | |
| rng.shuffle(ids) | |
| total = 0. | |
| total_distillation = 0. | |
| for sample_id in ids: | |
| budget() | |
| loaded = load_sample(config.root, training[sample_id], train.expected_hashes) | |
| example = transform_example(convert_detection_sample(loaded), horizontal=False if diagnostic else rng.random() < .5, | |
| vertical=False if diagnostic else rng.random() < .5, rotations=0 if diagnostic else rng.randrange(4)) | |
| if example.image.shape != (1024, 1024, 3): | |
| raise ValueError("native 1024 RGB inputs required") | |
| batch = {key: value.to(device) if hasattr(value, "to") else value | |
| for key, value in detection_batch([example]).items()} | |
| optimizer.zero_grad(set_to_none=True) | |
| outputs = model(batch["img"]) | |
| loss, _ = model.criterion(outputs, batch) | |
| loss = loss.sum() | |
| if teacher is not None: | |
| from training.distillation import confident_logit_distillation | |
| from training.detection_loss import anchor_classification_weights | |
| from ultralytics.utils.tal import make_anchors | |
| with torch.no_grad(): | |
| teacher_outputs = teacher(batch['img']) | |
| anchors, strides = make_anchors(outputs['one2many']['feats'], model.model[-1].stride, .5) | |
| valid = anchor_classification_weights(anchors * strides, batch['valid_mask']).bool() | |
| kd = sum(confident_logit_distillation(outputs[branch]['scores'], teacher_outputs[branch]['scores'], | |
| valid, batch['class_valid_mask'], pairs) for branch in ('one2many', 'one2one')) | |
| total_distillation += kd.detach().item() | |
| loss = loss + config.distillation_weight * kd | |
| if not torch.isfinite(loss): | |
| raise FloatingPointError("nonfinite detector loss") | |
| loss.backward() | |
| optimizer.step() | |
| total += loss.detach().item() | |
| budget() | |
| metrics = evaluate() | |
| if config.freeze_bn_statistics and any( | |
| not torch.equal(value, batchnorm_buffers(model)[name]) | |
| for name, value in initial_bn.items()): | |
| raise RuntimeError("frozen BatchNorm buffers changed") | |
| current_parameters = dict(model.named_parameters()) | |
| if any(not torch.equal(value, current_parameters[name]) for name, value in fixed_parameters.items()): | |
| raise RuntimeError("frozen backbone parameters changed") | |
| history.append({"epoch": epoch + 1, | |
| "backbone_parameters_unchanged": True if config.freeze_backbone else None, "mean_loss": total / len(ids), "metrics": metrics, | |
| "mean_distillation_loss": total_distillation / len(ids) if teacher is not None else None, | |
| "bn_buffers_unchanged": True if config.freeze_bn_statistics else None, | |
| "elapsed_seconds": time.monotonic() - started}) | |
| if metrics["map50_95"] > best: | |
| best, stale, best_metrics = metrics["map50_95"], 0, metrics | |
| best_checkpoint = str(output / "best.pt") | |
| temporary = output / "best.pt.partial" | |
| torch.save({"model": deepcopy(model).cpu(), "optimizer": optimizer.state_dict(), | |
| "train_args": vars(model.args).copy(), | |
| "augmentation": {"horizontal_flip_probability": 0 if diagnostic else .5, "vertical_flip_probability": 0 if diagnostic else .5, | |
| "uniform_quarter_turns": [0] if diagnostic else [0, 1, 2, 3], "photometric": False, "scale_jitter": False}, | |
| "diagnostic_train_only": diagnostic, "initial_state_sha256": initial_sha, | |
| "epoch": epoch + 1, "metrics": metrics, "transfer": transfer, | |
| "distillation_teacher_sha256": teacher_sha256, | |
| "train_ids": train_ids, "validation_ids": validation_ids, | |
| "config": {k: str(v) if isinstance(v, Path) else v for k, v in vars(config).items()}, | |
| "corpus_content_sha256": json.loads((config.root / "stats.json").read_text())["validation_content_sha256"]}, temporary) | |
| temporary.replace(best_checkpoint) | |
| else: | |
| stale += 1 | |
| model.criterion.update() | |
| progress = {"status": "IN_PROGRESS", "best_checkpoint": best_checkpoint, | |
| "history": history, "best_metrics": best_metrics, | |
| "elapsed_seconds": time.monotonic() - started} | |
| temporary_progress = output / "progress.json.partial" | |
| temporary_progress.write_text(json.dumps(progress, indent=2), encoding="utf-8") | |
| temporary_progress.replace(output / "progress.json") | |
| if stale >= config.patience: | |
| status = "EARLY_STOPPED" | |
| break | |
| except TimeoutError: | |
| status = "TIME_LIMIT" | |
| except Exception as error: | |
| (output / "fit_STOP.json").write_text(json.dumps({"status": "FAILED", | |
| "diagnosis": f"{type(error).__name__}: {error}"}), encoding="utf-8") | |
| raise | |
| result = {"status": status, "best_checkpoint": best_checkpoint, "history": history, | |
| "best_metrics": best_metrics, "elapsed_seconds": time.monotonic() - started} | |
| (output / "fit.json").write_text(json.dumps(result, indent=2), encoding="utf-8") | |
| return result | |
| def make_detection_trainer(config: DetectorTrainConfig) -> Trainer: | |
| return Trainer(config) | |
Xet Storage Details
- Size:
- 18.8 kB
- Xet hash:
- 0aed4267edaaee5299be6adf8cdbcaff0a42213bc386995217db68132f3fc659
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.